From e120ac4b95c15e9b2692aa67ab8391daa1ef473f Mon Sep 17 00:00:00 2001 From: Stuart Date: Sun, 11 Oct 2026 15:10:57 +1100 Subject: [PATCH 01/10] feat(composer): remove autocomplete; hold the demo caret solid while keys land Autocomplete is out until it is re-scoped in its own milestone. Typing no longer produces a ghost completion: the 13 local patterns, the suggestion session, the debounce, Tab-to-accept, Escape-to-dismiss, the Tab hint button and the polite live region are all removed. Tab and Escape keep their native behaviour. The ghost layer stays because it positions the demo caret, and the input handler now mirrors into it directly (the suggestion helpers used to do that). The orange demo caret now behaves like a real text cursor: is-demo-keying holds it solid on every character the hero demo types or erases, and on every character a chip types. It blinks only while the field is idle: the hold before typing and the rest on the full example. Before, it blinked through the backspace, so it was invisible in about half the frames. Tests: suggestion unit and e2e specs replaced by "typing makes no suggestion" and "Tab moves focus and never changes the prompt". The hero spec now asserts the caret's computed state on every sampled frame (blinking at the hold and the rest; animation none and opacity 1 on each typed or erased character). New spec: a chip fills behind a solid caret. --- dist/assets/index-BeVS7Wr2.css | 1 + dist/assets/index-D2LZqiXQ.js | 328 --------------------------------- dist/assets/index-DYbo9B-C.js | 328 +++++++++++++++++++++++++++++++++ dist/assets/index-DbG5mQ4q.css | 1 - dist/index.html | 55 +----- e2e/stu376-composer.spec.js | 183 +++++++++--------- index.html | 51 +---- src/composerAdapter.js | 233 ++++------------------- src/composerAdapter.test.js | 160 +--------------- src/htmlFidelity.css | 3 - 10 files changed, 464 insertions(+), 879 deletions(-) create mode 100644 dist/assets/index-BeVS7Wr2.css delete mode 100644 dist/assets/index-D2LZqiXQ.js create mode 100644 dist/assets/index-DYbo9B-C.js delete mode 100644 dist/assets/index-DbG5mQ4q.css diff --git a/dist/assets/index-BeVS7Wr2.css b/dist/assets/index-BeVS7Wr2.css new file mode 100644 index 0000000..3d2c9b7 --- /dev/null +++ b/dist/assets/index-BeVS7Wr2.css @@ -0,0 +1 @@ +@font-face{font-family:Delight;src:url(/assets/Delight-VF-CnVpVuQk.ttf) format("truetype");font-weight:100 900;font-display:swap}:root{--bg: oklch(96.65% .0074 260.73);--surface: oklch(100% 0 0);--surface-translucent: oklch(100% 0 0 / .65);--surface-glass: oklch(100% 0 0 / .72);--surface-sunken: oklch(98.4% .004 260);--fg: oklch(20.77% .0398 265.75);--muted: oklch(48% .02 260);--muted-2: oklch(68% .018 260);--on-dark: oklch(100% 0 0);--border: oklch(90% .012 260);--border-strong: oklch(80% .02 260);--fill-hover: color-mix(in oklch, var(--fg) 5%, var(--surface));--fill-subtle: color-mix(in oklch, var(--fg) 6%, var(--surface));--fill-selected: color-mix(in oklch, var(--fg) 4%, var(--surface));--track: color-mix(in oklch, var(--fg) 7%, var(--surface));--avatar: oklch(88% .02 260);--accent: oklch(63% .22 32);--accent-soft: oklch(from var(--accent) l c h / .18);--accent-ring: oklch(from var(--accent) l c h / .45);--fx-ink: oklch(70% .13 250);--ok: oklch(52% .11 165);--ok-soft: oklch(52% .11 165 / .12);--warn: oklch(66% .13 70);--warn-soft: oklch(66% .13 70 / .14);--bad: oklch(55% .19 25);--bad-soft: oklch(55% .19 25 / .1);--disabled-bg: oklch(88% .015 260);--disabled-fg: oklch(58% .02 260);--font-display: "Delight", "Outfit", "DM Sans", system-ui, sans-serif;--font-body: "Delight", "Outfit", "DM Sans", system-ui, sans-serif;--font-mono: "DM Mono", ui-monospace, SFMono-Regular, Menlo, monospace;--fw-ui: 560;--fw-bold: 620;--fw-black: 700;--ls-display: -.04em;--ls-heading: -.03em;--ls-mono: .13em;--fs-display: 54px;--fs-h2: 28px;--fs-h3: 22px;--fs-h4: 18px;--fs-lead: 17px;--fs-body: 14.5px;--fs-small: 13.5px;--fs-caption: 12.5px;--fs-mono: 11.5px;--fs-micro: 10.5px;--lh-display: 1.04;--lh-heading: 1.15;--lh-body: 1.6;--radius-xl: 22px;--radius-lg: 20px;--radius-md: 16px;--radius-sm: 14px;--radius-control: 12px;--radius-nav: 11px;--radius-icon: 10px;--radius-chip: 999px;--radius-badge: 7px;--shadow-sm: 0 1px 2px oklch(20% .03 260 / .06);--shadow-md: 0 1px 2px oklch(20% .03 260 / .06), 0 18px 46px -22px oklch(20% .03 260 / .3);--shadow-control: 0 2px 6px oklch(20% .03 260 / .22);--shadow-composer: 0 0 0 3px var(--accent-soft), 0 1px 2px oklch(20% .03 260 / .06), 0 0 44px -8px oklch(63% .22 32 / .16), 0 20px 52px -20px oklch(63% .22 32 / .18);--blur-chrome: 14px;--ease: cubic-bezier(.2, 0, 0, 1);--ease-overshoot: cubic-bezier(.32, 1.38, .5, 1);--t-fast: .15s;--t-enter: .22s;--t-reveal: .5s;--t-progress: .7s;--t-ring: .9s;--t-morph: 1.12s;--touch: 44px;--control-h: 46px;--stage-w: 1920px;--stage-h: 1080px;--measure-prose: 62ch;--measure-lead: 68ch}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;transition-duration:.01ms!important;transition-delay:0ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}:where(button,[role=button],input,select,textarea,a){-webkit-tap-highlight-color:transparent}:where(button,[role=button],.control-button,.icon-button){min-height:44px;border-radius:var(--radius-md, 12px);transition:color var(--motion-fast, .16s) ease,background-color var(--motion-fast, .16s) ease,border-color var(--motion-fast, .16s) ease,box-shadow var(--motion-fast, .16s) ease,transform var(--motion-fast, .16s) ease,opacity var(--motion-fast, .16s) ease}:where(.icon-button,.modal-close,button:has(>svg:only-child)){min-width:44px;min-height:44px;display:inline-flex;align-items:center;justify-content:center}:where(button,[role=button],input,select,textarea,a[href]):focus-visible{outline:3px solid color-mix(in srgb,var(--accent, #3b82f6) 45%,transparent);outline-offset:2px}:where(button,[role=button]):active:not(:disabled){transform:scale(.98)}:where(button,[role=button]):disabled,:where(button,[role=button])[aria-disabled=true]{cursor:not-allowed;opacity:.5;box-shadow:none}:where(button,[role=button])[aria-busy=true]{cursor:progress;pointer-events:none}:where(button,[role=button])[aria-busy=true]:after{content:"";width:1em;height:1em;margin-inline-start:.55em;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:shared-control-spin .7s linear infinite}:where(input,select,textarea,.control-field){min-height:44px;border:1px solid var(--border, #dfe3ea);border-radius:var(--radius-md, 12px);background:var(--surface-sunken, #f8fafc)}:where(.badge,.sb-section-badge,.results-file-count,.pm-popular-badge){display:inline-flex;align-items:center;border-radius:999px;font-weight:600}:where(.panel,.results-panel,.pm-card){border:1px solid var(--border, #dfe3ea);border-radius:var(--radius-lg, 16px);background:var(--surface, #fff)}.modal-overlay{overflow:auto;overscroll-behavior:contain;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left))}.modal-overlay.open .modal-content{transform:scale(1) translateY(0)!important}.modal-overlay[aria-hidden=true]{pointer-events:none}.modal-overlay[aria-busy=true]{cursor:progress}.modal-content{width:min(100%,680px);max-height:calc(100dvh - 32px)!important;overflow:auto!important;overscroll-behavior:contain}.modal-content>:is(.border-t,.wt-footer){position:sticky;bottom:0;z-index:2;background:#fff}.modal-content>:is(.border-b,.pm-header){position:sticky;top:0;z-index:2;background:#fff}@media(max-width:480px),(max-height:600px){.modal-overlay{align-items:flex-start;padding:8px}.modal-content{max-height:calc(100dvh - 16px)!important;border-radius:14px}}@media(hover:hover){:where(button,[role=button]):hover:not(:disabled):not([aria-disabled=true]){filter:brightness(.97)}}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}@keyframes shared-control-spin{to{transform:rotate(360deg)}}.hero-field{position:absolute;inset:0;overflow:hidden;z-index:-2;pointer-events:none}.fx-grid{position:absolute;inset:0;width:100%;height:100%;display:block;z-index:-2;pointer-events:none;opacity:0;transition:opacity var(--t-reveal) var(--ease)}.fx-grid.is-ready{opacity:1}.fx-mask{position:absolute;z-index:-1;pointer-events:none;background:var(--bg);filter:blur(46px)}.fx-mask-hero{left:50%;top:50%;width:980px;height:520px;transform:translate(-50%,-54%)}.fx-mask-top{left:-48px;right:-48px;top:-48px;height:132px}.fx-mask-bottom{left:-48px;right:-48px;bottom:-48px;height:132px}@media(max-width:920px){.fx-mask{filter:blur(36px)}.fx-mask-hero{width:92%;height:62%;top:50%;transform:translate(-50%,-50%)}.fx-mask-top{height:104px}.fx-mask-bottom{height:124px}}@media(prefers-reduced-motion:reduce){.hero-field,.fx-grid,.fx-mask{display:none}}.pipeline-glyph.logo-loop{position:relative;width:100%;height:88px;margin:0 0 24px;overflow:hidden;pointer-events:none;color:var(--muted)}.loop-mark,.loop-shadow{position:absolute}.loop-mark{left:0;top:50%;width:52px;height:52px;margin:-26px 0 0;will-change:transform}.loop-piece{position:absolute;inset:0;display:block;will-change:transform,opacity}.loop-piece svg{display:block;width:100%;height:100%;overflow:visible}.loop-halo{position:absolute;left:50%;top:50%;width:74px;height:74px;margin:-37px 0 0 -37px;border-radius:50%;background:radial-gradient(circle,color-mix(in oklch,var(--accent) 60%,transparent),transparent 64%);filter:blur(5px);opacity:.09;will-change:transform,opacity}.loop-shadow{left:var(--mark-c, 26px);bottom:13px;width:46px;height:6px;margin-left:-23px;border-radius:50%;background:color-mix(in oklch,var(--fg) 26%,transparent);opacity:0;will-change:transform,opacity}@media(max-width:920px){.pipeline-glyph.logo-loop{height:66px;margin-bottom:16px}.loop-mark{width:40px;height:40px;margin:-20px 0 0}.loop-halo{width:58px;height:58px;margin:-29px 0 0 -29px}.loop-shadow{bottom:6px}}.shell-frame{display:flex;justify-content:center;align-items:flex-start;width:100%}.shell-stage{position:relative;flex:none;width:1920px;height:1080px;overflow:hidden;background:var(--bg);transform-origin:top center;transform:scale(var(--fit,1));margin-bottom:calc(1080px * (var(--fit,1) - 1));isolation:isolate}.shell-stage .topbar{position:absolute;inset:0 0 auto;height:88px;padding:0 40px;background:transparent;border:0}.shell-stage .brand{width:246px;max-width:calc(100% - 140px);min-height:44px}.shell-stage .brand-mark{display:block;width:100%;height:auto;overflow:visible}.shell-stage .topbar-account{gap:10px}.shell-stage .topbar{gap:0}.shell-stage .topbar-credits{height:32px;min-height:32px;padding:0 10px 0 8px;gap:5px}.shell-stage .topbar-credits{display:inline-flex}.shell-stage .topbar-plan{text-transform:uppercase}.shell-stage .topbar-plan{height:22px;min-height:22px;padding:0 8px;border-radius:6px;cursor:pointer}.shell-stage .topbar-avatar{width:32px;height:32px;min-height:32px;min-width:32px}.shell-stage .viewport{position:static;top:auto;min-height:0}.shell-stage .view-home{min-height:1080px;transform:none;transition:none}.shell-stage .hero-field{z-index:-1}.glow{position:absolute;left:50%;top:55%;width:1360px;height:760px;transform:translate(-50%,-50%);background:radial-gradient(ellipse at 28% 46%,oklch(from var(--bg) calc(l - .07) calc(c + .035) h / .42),transparent 62%),radial-gradient(ellipse at 72% 56%,oklch(from var(--accent) l c h / .09),transparent 58%);filter:blur(64px);pointer-events:none}.shell-stage .hero{position:absolute;left:50%;top:50%;transform:translate(-50%,-52%);width:1280px;padding:0;flex:none;z-index:1}.shell-stage #hero.is-exiting{display:flex!important;pointer-events:none}.shell-stage .headline{font-size:80px;line-height:1.05}.shell-stage .sub{margin-top:28px;font-size:20px}.shell-stage .composer{margin-top:46px;width:760px;height:148px;flex:none}.shell-stage .composer .field,.shell-stage .composer .ghost{left:23px;right:23px;top:19px;width:auto;height:58px;min-height:0;font-size:18px;line-height:1.5}.shell-stage .composer .field{overflow-y:auto;box-shadow:none}.shell-stage .composer .tools{left:15px;bottom:12px}.shell-stage .icon-btn,.shell-stage .send{width:44px;height:44px;min-width:44px;min-height:44px}.shell-stage .send{right:15px;bottom:15px}.shell-stage .send:disabled{opacity:1}.shell-stage .chips{max-width:none}.shell-stage .chip{min-height:44px;background:#ffffffb3}.composer.is-pointer-focus{outline:none}#generation-stage{position:absolute;inset:164px auto auto 50%;width:1420px;transform:translate(-50%);padding:0;background:transparent;opacity:1;transition:none}#generation-stage.is-active,body.results-fullscreen #generation-stage{display:block}#generation-stage.is-active #main-stage-container{opacity:1;pointer-events:auto}#main-stage-container[data-morphing],#main-stage-container[data-morphing] *{visibility:hidden!important}#main-stage-container{position:relative;inset:auto;display:grid;grid-template-columns:310px minmax(0,1fr);width:100%;height:auto;min-height:590px;border:2px solid oklch(from var(--accent) l c h / .85);border-radius:20px;background:var(--surface);box-shadow:var(--shadow-composer);overflow:hidden}#main-stage{min-width:0;padding:0;display:grid;grid-template-columns:minmax(0,1fr);grid-template-areas:"stack";overflow:visible}#main-stage>*{grid-area:stack}#main-stage-container .pipeline-prompt-recap{grid-area:auto;padding:30px}#main-stage-container .pipeline-prompt-text{margin:12px 0 32px;font-size:17px;line-height:1.5}#pipeline-progress{grid-area:stack;height:auto;padding:0;overflow:visible;align-self:center}#pipeline-progress.visible{display:block}#pipeline-progress .pipeline-view{display:block;padding:48px 64px}#pipeline-stage-nav{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%)}#pipeline-stage-nav:focus-within,#pipeline-stage-nav.is-open{position:relative;width:auto;height:auto;margin:20px 0 0;clip-path:none}#progress-stage-count{position:relative;min-height:0;padding:0;border:0;border-radius:0;font:inherit;line-height:normal;color:inherit;background:none;text-align:left}#progress-stage-count:after{content:"";position:absolute;inset:-15px 0}#progress-elapsed{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}.composer-morph{background:var(--surface);border:2px solid oklch(from var(--accent) l c h / .85);border-radius:20px;box-shadow:var(--shadow-composer)}.panel-in{animation:fidelity-rise .5s var(--ease) both}@keyframes fidelity-rise{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}body.results-fullscreen #generation-stage{inset:104px 40px auto;width:auto;transform:none}body.results-fullscreen #main-stage-container{height:936px;min-height:0}body.results-fullscreen #main-stage{height:100%;min-height:0;grid-template-rows:1fr}body.results-fullscreen .pipeline-prompt-edit{margin-bottom:10px}#results-view{min-width:0;min-height:0;height:100%;padding:40px 48px;overflow:hidden}#results-view.visible{display:flex;flex-direction:column}#results-view .results-header{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%)}#bundle-strip{flex:none;gap:10px;margin:0 0 22px;padding:0 0 14px;border:0;border-bottom:1px solid var(--border);background:transparent;overflow-x:auto}#bundle-strip.visible{display:flex;align-items:center}#artifact-tabs{display:flex;gap:10px;flex:none;width:auto;padding:0}#bundle-strip .results-summary-tab{flex:none;min-height:38px;padding:0 13px;border-radius:9px;font:700 13px var(--font-display)}#bundle-strip .artifact-tab{min-width:172px;max-width:260px;padding:8px 11px;border-radius:9px;background:var(--surface)}#bundle-strip .artifact-tab-name{font:700 13px var(--font-display)}#bundle-strip .artifact-tab-meta{font:11px var(--font-mono);margin-top:3px}#bundle-strip .artifact-tab.active{border-color:var(--fg);box-shadow:inset 0 0 0 1px var(--fg)}#bundle-strip .artifact-tab-status.status-pass{color:var(--ok);background:var(--ok-soft)}#bundle-strip .artifact-tab-status.status-warning{color:var(--warn);background:var(--warn-soft)}#bundle-strip .artifact-tab-status.status-fail{color:var(--bad);background:var(--bad-soft)}#results-summary-detail{flex:1;min-height:0;max-height:none;padding:16px 4px;overflow:auto;border:0;background:transparent}#results-summary-detail .review-summary{display:flex;align-items:flex-start;justify-content:space-between;gap:32px;padding:0;border:0;background:none;box-shadow:none}#results-summary-detail .review-summary-copy{flex:1;min-width:0}.summary-heading{font:500 28px/1.2 var(--font-display);margin:0 0 16px;letter-spacing:normal}#results-summary-detail .review-summary-text{max-width:var(--measure-prose);font-size:14px;line-height:1.6;color:var(--muted)}.summary-spec{margin-top:24px;display:grid;gap:16px}.summary-spec>div{display:flex;gap:20px;justify-content:space-between;border-top:1px solid var(--border);padding-top:12px;font-size:14px}.summary-spec dt{color:var(--muted)}.summary-spec dd{text-align:right;overflow-wrap:anywhere}.summary-spec .summary-manual-callout{padding:0;margin:0;border:0;background:none;color:var(--fg);text-align:left}.summary-spec .summary-manual-callout ol{padding-left:1.4em;display:grid;gap:4px}.summary-spec .summary-manual-callout li{display:list-item;font-size:14px;font-weight:400}.summary-spec .summary-manual-callout li strong{font-weight:400}#results-summary-detail .review-score-column{width:184px;flex:none}#results-summary-detail .review-score{min-height:164px;padding:18px 16px;border-radius:12px;background:var(--surface-sunken)}#results-summary-detail .review-score strong{font:700 58px/.95 var(--font-display);margin-top:3px;letter-spacing:-.05em}#results-summary-detail .review-score-feedback{font-size:11px}#results-summary-detail .review-score-pass{color:var(--ok);border-color:var(--ok-soft)}#results-summary-detail .review-score-warning{color:var(--warn);border-color:var(--warn-soft)}#results-summary-detail .review-score-fail{color:var(--bad);border-color:var(--bad-soft)}#results-summary-detail .review-score-label{font:700 11px/1 var(--font-mono)}#results-summary-detail .review-score-status{font:800 11px/1 var(--font-mono);letter-spacing:.08em}#results-summary-detail .review-score-feedback{font-weight:600;color:var(--muted);line-height:normal}#results-summary-detail .feedback-btn{width:36px;height:36px;min-width:36px;min-height:36px;border-radius:8px}#results-summary-detail .feedback-btn svg{width:16px;height:16px}#results-view .flutterflow-deploy-icon{display:block;width:18px;height:18px;filter:none;mix-blend-mode:normal}#results-view .results-action-bar{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;flex:none;margin:20px 0 0;padding:12px 0 0;border-top:1px solid var(--border);background:transparent}#results-view .results-action{display:contents}#results-view .results-action-scope{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}#results-view .results-action-bar .btn-header-action{min-height:44px;padding:9px 16px;border:1px solid var(--border);border-radius:12px;font:600 12.5px var(--font-display);letter-spacing:-.01em;background:var(--surface);color:var(--fg);box-shadow:none}#results-view .results-action-bar .btn-deploy-results{background:var(--fg);color:var(--surface);border-color:var(--fg);box-shadow:0 2px 8px -2px oklch(from var(--accent) l c h / .4)}#results-view .results-action-bar .btn-error-regen{border-color:color-mix(in oklch,var(--warn) 45%,var(--surface));color:oklch(from var(--warn) 48% c h)}#artifact-results-split{flex:1;min-height:0;gap:22px;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr)}#artifact-results-split .results-panel{min-width:0;min-height:0;border:1px solid var(--border);border-radius:14px;overflow:hidden}#artifact-results-split .panel-body{min-height:0;overflow:auto}#artifact-results-split .panel-code-wrap{height:100%;min-height:0;background:var(--surface-sunken)}#results-code-output{color:var(--fg);background:var(--surface-sunken);font:12px/1.8 var(--font-mono);white-space:pre-wrap;overflow-wrap:anywhere}#results-code-output .hljs-keyword,#results-code-output .hljs-meta{color:oklch(from var(--accent) 46% calc(c*.7) h)!important}#results-code-output .hljs-string{color:var(--fg)!important}#results-code-output .hljs-comment{color:var(--muted)!important;font-style:normal}#results-code-output .hljs-number,#results-code-output .hljs-type,#results-code-output .hljs-built_in,#results-code-output .hljs-title{color:oklch(from var(--fg) 45% c h)!important}.code-line{display:block;min-height:1.8em}.code-line.is-in{animation:code-land .52s var(--ease) both;animation-delay:var(--d)}@keyframes code-land{0%{opacity:0;transform:translateY(6px);background:var(--accent-soft)}42%{opacity:1;transform:translateY(0);background:var(--accent-soft)}to{opacity:1;transform:none;background:transparent}}body[data-shell-view=account] .shell-stage,body[data-shell-view=plans] .shell-stage{width:100%;height:auto;min-height:100vh;transform:none;margin:0;overflow:visible}body[data-shell-view=account] .viewport,body[data-shell-view=plans] .viewport{padding-top:88px}@media(max-width:920px){.shell-frame{display:block}.shell-stage{display:flex;flex-direction:column;width:100%;height:auto;min-height:100svh;transform:none;margin:0}.shell-stage .topbar{position:relative;flex:none;height:64px;padding:0 20px}.shell-stage .topbar-credits{height:30px;min-height:30px;padding:0 9px 0 7px;font-size:12px}.shell-stage .topbar-avatar{width:30px;height:30px;min-width:30px;min-height:30px}.shell-stage .viewport,.shell-stage .view-home{flex:1;display:flex;flex-direction:column;min-height:0}.shell-stage .hero{position:relative;left:auto;top:auto;transform:none;width:100%;padding:24px 20px 32px;flex:1}.shell-stage .headline{font-size:clamp(34px,6.8vw,56px);line-height:1.08;letter-spacing:-.03em;text-wrap:balance}.shell-stage .sub{margin-top:18px;font-size:16px;max-width:34ch}.shell-stage .composer{margin-top:32px;width:100%;max-width:520px;height:148px;border-radius:16px}.shell-stage .composer .field,.shell-stage .composer .ghost{left:18px;right:18px;top:16px;height:94px;font-size:16px;line-height:1.45}.shell-stage .composer .tools{left:10px;bottom:12px}.shell-stage .send{right:10px;bottom:10px}.shell-stage .chips{max-width:520px}.shell-stage .chips .chip{height:auto;padding-block:10px}.glow{width:140vw;height:60vh;top:48%;filter:blur(40px)}#generation-stage,body.results-fullscreen #generation-stage{position:relative;inset:auto;width:100%;transform:none;padding:28px 20px;flex:1}#main-stage-container,body.results-fullscreen #main-stage-container{grid-template-columns:minmax(0,1fr);min-height:0;height:auto;border-radius:18px}#main-stage-container .pipeline-prompt-recap{padding:22px;border-right:0;border-top:1px solid var(--border)}#main-stage-container .pipeline-prompt-text{margin:8px 0 20px;font-size:15px;max-height:100px}body.results-fullscreen .pipeline-prompt-edit{margin-bottom:0}#pipeline-progress .pipeline-view{padding:34px 24px;min-height:300px}#results-view{height:auto;padding:22px;overflow:visible}#results-summary-detail .review-summary{flex-direction:column;gap:22px}#results-summary-detail .review-score-column{width:100%}#results-summary-detail{overflow:visible}.summary-spec>div{flex-wrap:wrap;gap:6px}#results-view .results-action-bar,#artifact-results-split{grid-template-columns:1fr}#results-code-output{height:260px}body[data-shell-view=account] .viewport,body[data-shell-view=plans] .viewport{padding-top:0}}@media(prefers-reduced-motion:reduce){.panel-in,.code-line.is-in{animation:none}} diff --git a/dist/assets/index-D2LZqiXQ.js b/dist/assets/index-D2LZqiXQ.js deleted file mode 100644 index d8e257d..0000000 --- a/dist/assets/index-D2LZqiXQ.js +++ /dev/null @@ -1,328 +0,0 @@ -(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 E=typeof window<"u"?window:void 0,He=typeof globalThis<"u"?globalThis:E,Ke=He?.navigator,F=He?.document,be=He?.location,Rl=He?.fetch,ya=He!=null&&He.XMLHttpRequest&&"withCredentials"in new He.XMLHttpRequest?He.XMLHttpRequest:void 0,Gc=He?.AbortController,Fg=He?.CompressionStream,et=Ke?.userAgent;function Zd(){return!(!E||E.navigator.onLine===!1)}var Ri=typeof globalThis<"u"?globalThis:E;Ri&&typeof self>"u"&&(Ri.self=Ri),Ri&&typeof File>"u"&&(Ri.File=function(){});var O=E??{},se={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Kc(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 le(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){Kc(s,i,r,o,a,"next",l)}function a(l){Kc(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 Xd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var Yc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Jc(t){return typeof t=="string"||t}function Zc(t){return typeof t=="string"?t:void 0}var Ti,Rg=["$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"],Yt=(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})({}),Xc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Tg=["$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"],$g=["token"],Qd="NativeGzipValidationError",_a=t=>t.length>=2&&t[0]===31&&t[1]===139,Qc=(t,e)=>t===Xc.GZipJS||e===Xc.GZipJS||e==="gzip",eu=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Nr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Qd,e},Mg=(function(){var t=le((function*(e,n){18>e.size&&Nr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());_a(i)&&i[2]===8||Nr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Ti)return Ti;Ti=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;Ti[c]=d>>>0}return Ti})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Nr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Nr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function wa(){return wa=le((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=le((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 Mg(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),wa.apply(this,arguments)}var Lg=["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"],tu=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Lg.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Js=function(t){return t.trim()},ba=function(t){return t.replace(/^\$/,"")};function ef(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 tf=Object.prototype,nf=tf.hasOwnProperty,Zs=tf.toString,U=Array.isArray||function(t){return Zs.call(t)==="[object Array]"},ze=t=>typeof t=="function",ve=t=>t===Object(t)&&!U(t),sn=t=>{if(ve(t)){for(var e in t)if(nf.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,X=t=>Zs.call(t)=="[object String]",Ea=t=>X(t)&&t.trim().length===0,rt=t=>t===null,q=t=>C(t)||rt(t),Re=t=>Zs.call(t)=="[object Number]"&&t==t,Gt=t=>Re(t)&&t>0,xt=t=>Zs.call(t)==="[object Boolean]",Ng=t=>t instanceof FormData,Og=t=>j(Tg,t),Bg=t=>j($g,t);function rf(t){return t===null||typeof t!="object"}function us(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Tl(t){return typeof Event<"u"&&sf(t,Event)}function sf(t,e){try{return t instanceof e}catch{return!1}}var Dg=[!0,"true",1,"1","yes"],Bo=t=>j(Dg,t),jg=[!1,"false",0,"0","no"];function $t(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Re(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),$t(r||n,e,n,i))}class Ug{constructor(e){this.tt={},this.et=e.et,this.it=$t(e.bucketSize,0,100,e.rt),this.nt=$t(e.refillRate,0,this.it,e.rt),this.st=$t(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 dt="Mobile",ds="iOS",on="Android",gi="Tablet",of=on+" "+gi,af="iPad",lf="Apple",cf=lf+" Watch",Qi="Safari",mi="BlackBerry",uf="Samsung",df=uf+"Browser",ff=uf+" Internet",Hn="Chrome",Hg=Hn+" OS",hf=Hn+" "+ds,$l="Internet Explorer",pf=$l+" "+dt,Ml="Opera",Wg=Ml+" Mini",Ll="Edge",gf="Microsoft "+Ll,ui="Firefox",mf=ui+" "+ds,lr="Nintendo",cr="PlayStation",di="Xbox",vf=on+" "+dt,yf=dt+" "+Qi,Wi="Windows",Sa=Wi+" Phone",nu="Nokia",xa="Ouya",_f="Generic",qg=_f+" "+dt.toLowerCase(),wf=_f+" "+gi.toLowerCase(),Ia="Konqueror",bf="Oculus Browser",fs="Vivaldi",Ef="Yandex",hs="Whale",ka="DuckDuckGo",Sf="Pale Moon",ps="Waterfox",er="Brave",xf="Google Search App",Ce="(\\d+(\\.\\d+)?)",Do=new RegExp("Version/"+Ce),zg=new RegExp(di,"i"),Vg=new RegExp(cr+" \\w+","i"),Gg=new RegExp(lr+" \\w+","i"),Nl=new RegExp(mi+"|PlayBook|BB10","i"),Kg={"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"},If=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?er:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?xf:j(t," OPR/")&&j(t,"Mini")?Wg:j(t," OPR/")?Ml:Nl.test(t)?mi:j(t,"IE"+dt)||j(t,"WPDesktop")?pf:j(t,"OculusBrowser")?bf:j(t,df)?ff:j(t,Ll)||j(t,"Edg/")?gf:j(t,fs+"/")?fs:j(t,"YaBrowser/")?Ef:j(t,hs+"/")?hs:j(t,ka+"/")||j(t,"Ddg/")?ka:j(t,"FBIOS")?"Facebook "+dt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?hf:j(t,"CrMo")||j(t,Hn)?Hn:j(t,on)&&j(t,Qi)?vf:j(t,"FxiOS")?mf:j(t.toLowerCase(),Ia.toLowerCase())?Ia:j(t,er+"/")?er:((s,o)=>o&&j(o,lf)||(function(a){return j(a,Qi)&&!j(a,Hn)&&!j(a,on)})(s))(t,e)?j(t,dt)?yf:Qi:j(t,"PaleMoon/")?Sf:j(t,ps+"/")?ps:j(t,ui)?ui:j(t,"MSIE")||j(t,"Trident/")?$l:j(t,"Gecko")?ui:"")},Yg={[pf]:[new RegExp("rv:"+Ce)],[gf]:[new RegExp(Ll+"?\\/"+Ce)],[Hn]:[new RegExp("("+Hn+"|CrMo)\\/"+Ce)],[hf]:[new RegExp("CriOS\\/"+Ce)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Ce)],[Qi]:[Do],[yf]:[Do],[Ml]:[new RegExp("(Opera|OPR)\\/"+Ce)],[ui]:[new RegExp(ui+"\\/"+Ce)],[mf]:[new RegExp("FxiOS\\/"+Ce)],[Ia]:[new RegExp("Konqueror[:/]?"+Ce,"i")],[mi]:[new RegExp(mi+" "+Ce),Do],[vf]:[new RegExp("android\\s"+Ce,"i")],[ff]:[new RegExp(df+"\\/"+Ce)],[bf]:[new RegExp("OculusBrowser\\/"+Ce)],[fs]:[new RegExp(fs+"\\/"+Ce)],[Ef]:[new RegExp("YaBrowser\\/"+Ce)],[hs]:[new RegExp(hs+"\\/"+Ce)],[er]:[new RegExp(er+"\\/"+Ce)],[ka]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Ce)],[Sf]:[new RegExp("PaleMoon\\/"+Ce)],[ps]:[new RegExp(ps+"\\/"+Ce)],[xf]:[new RegExp("GSA\\/"+Ce)],[$l]:[new RegExp("(rv:|MSIE )"+Ce)],Mozilla:[new RegExp("rv:"+Ce)]},Jg=function(t,e,n,i){var r=If(t,e,n,i),s=Yg[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},iu=[[new RegExp(di+"; "+di+" (.*?)[);]","i"),t=>[di,t&&t[1]||""]],[new RegExp(lr,"i"),[lr,""]],[new RegExp(cr,"i"),[cr,""]],[Nl,[mi,""]],[new RegExp(Wi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Sa,""];if(new RegExp(dt).test(e)&&!/IEMobile\b/.test(e))return[Wi+" "+dt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Kg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Wi,i]}return[Wi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[ds,[t[3],t[4],t[5]||"0"].join(".")]:[ds,""]],[/(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("("+on+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+on+")","i"),t=>t&&t[2]?[on,[t[2],t[3],t[4]||"0"].join(".")]:[on,""]],[/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/,[Hg,""]],[/Linux|debian/i,["Linux",""]]],ru=function(t){return Gg.test(t)?lr:Vg.test(t)?cr:zg.test(t)?di:new RegExp(xa,"i").test(t)?xa:new RegExp("("+Sa+"|WPDesktop)","i").test(t)?Sa:/iPad/.test(t)?af:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?cf:Nl.test(t)?mi:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(nu,"i").test(t)?nu:/(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(dt).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)?on:of:new RegExp("(pda|"+dt+")","i").test(t)?qg:new RegExp(gi,"i").test(t)&&!new RegExp(gi+" pc","i").test(t)?wf:""},Zg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function su(t,e){return typeof(n=t)=="string"&&Zg.test(n)?t:e();var n}function bn(t){return t&&t.split("#")[0]}function Ol(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function ou(t,e,n){return kf.apply(this,arguments)}function kf(){return(kf=le((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 Xg=t=>t instanceof Error,Cf={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}},Qg=Cf.info;function Pf(t){if(xt(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=>Pf(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function gs(t){var e=[];for(var n in t){var i=t[n];rt(i)||C(i)||e.push({key:n,value:Pf(i)})}return e}function em(t,e){var n=Cf[t.level||"info"]||Qg,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),q(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),q(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:gs(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 Af(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 Ff(t,e,n,i){return{resourceLogs:[{resource:{attributes:gs(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let tm=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:em(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 le((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return le((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Yt.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=Ff(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(Yt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return le((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Yt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Yt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Af(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Yt.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(Yt.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(Yt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return le((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield ou(n,t):yield n}))()}flushWithTimeout(t){var e=this;return le((function*(){var n=e.flush();yield ou(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 jo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function au(t){return String(t)+"000000"}function lu(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 nm=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=le((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=lu(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(jo.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,jo)]+=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 le((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:gs(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=au(Date.now()),n=new Map;for(var i of t.values()){var r,s=lu(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=gs((r=i.attributes)!==null&&r!==void 0?r:{}),l=au(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:jo})}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 Or,cu,Uo;function im(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Uo&&n.length===cu||(cu=n.length,Uo=n.reduce(((i,r)=>{Or||(Or={});var s=Or[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,Or[r]=[u,c];break}}return i}),{})),Uo}}class rm{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 le((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 le((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:im(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 vi="?";function Ca(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?vi:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Rf=(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]:vi,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},sm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,om=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,am=/\((\S*)(?::(\d+))(?::(\d+))\)/,lm=(t,e)=>{var n=sm.exec(t);if(n)return Ca(e,n[1],vi,+n[2],+n[3]);var i=om.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=am.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Rf(i[1]||vi,i[2]);return Ca(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},cm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,um=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dm=(t,e)=>{var n=cm.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=um.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]||vi,o=Rf(s,r);return Ca(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},uu=/\(error: (.*)\)/;class fm{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 us(e,"DOMException")}isDOMError(e){return us(e,"DOMError")}}class hm{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 sf(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 pm{constructor(){}match(e){return!!us(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 gm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class mm{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(gm);return r&&(n=r[1],i=r[2]),[n,i]}}var vm=["fatal","error","warning","log","info","debug"];function Tf(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 ym{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: "+Tf(e)}isSeverityLevel(e){return X(e)&&!Ea(e)&&vm.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(Xg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class _m{match(e){return Tl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Tf(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class wm{match(e){return rf(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 bm{match(e){return us(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 rf(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 ms="$message",vs="$timestamp",Em=new Set([ms,vs]),Ho={enabled:!0,max_bytes:32768};function ys(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Ho.enabled,max_bytes:xm(t.max_bytes,Ho.max_bytes)}:k({},Ho)}class Sm{constructor(e){this.Ke=[],this.Je=0,this.Ne=ys(e)}setConfig(e){this.Ne=ys(e),this.Xe()}add(e){var n=(function(r){var s;try{s=ef(r)}catch{return}try{var o=JSON.parse(s);if(!ve(o))return;var a=o,l=a[ms],u=a[vs];return!X(l)||l.trim().length===0||!X(u)&&!Re(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 xm(t,e){if(!Re(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var $f=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(E&&(se.DEBUG||E.POSTHOG_DEBUG||n)&&!C(E.console)&&E.console){for(var s=("__rrweb_original__"in E.console[r])?E.console[r].__rrweb_original__:E.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)=>$f(t+" "+r,s)};return i},A=$f("[PostHog.js]"),ye=A.createLogger,Im=ye("[ExternalScriptsLoader]"),Wo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Im.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)};O.__PosthogExtensions__=O.__PosthogExtensions__||{},O.__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)}},O.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);Wo(t,i,n)};se.DEBUG=!1,se.LIB_VERSION="1.415.7",se.LIB_NAME="web";var Mf="$people_distinct_id",ur="$device_id",qo="$device_model",qi="__alias",zi="__timers",Pa="$autocapture_disabled_server_side",Aa="$heatmaps_enabled_server_side",Fa="$exception_capture_enabled_server_side",Ra="$error_tracking_suppression_rules",Ta="$error_tracking_capture_extension_exceptions",$a="$web_vitals_enabled_server_side",Bl="$dead_clicks_enabled_server_side",Dl="$product_tours_enabled_server_side",Ma="$web_vitals_allowed_metrics",jn="$session_recording_remote_config",Lf="$replay_sample_rate",Nf="$replay_override_sampling",Of="$replay_override_linked_flag",Bf="$replay_override_url_trigger",Df="$replay_override_event_trigger",ai="$sesid",jl="$session_is_sampled",Mn="$enabled_feature_flags",Vi="$active_feature_flags",Jr="$early_access_features",La="$feature_flag_details",Gi="$feature_flag_payloads",Zr="$feature_flag_request_id",_s="$minimal_flag_called_events",Ft="$override_feature_flags",Ln="$override_feature_flag_payloads",Kt="$stored_person_properties",Nn="$stored_group_properties",Na="$surveys",ws="$surveys_loaded_at",Oa="$surveys_activated",Xr="$surveys_activated_session",Qr="$surveys_activated_timestamps",Ki="ph_product_tours",Bn="$flag_call_reported",Yi="$flag_call_reported_session_id",es="$feature_flag_errors",tr="$feature_flag_evaluated_at",mt="$user_state",Ba="$client_session_props",Da="$capture_rate_limit",ja="$initial_campaign_params",Ua="$initial_referrer_info",bs="$initial_person_info",Es="$epp",Br="$posthog_cookieless",jf="$cookieless_mode",Uf="$sdk_debug_extensions_init_method",Hf="$sdk_debug_extensions_init_time_ms",Wf="$sdk_debug_recording_script_not_loaded",Ul="PostHog loadExternalDependency extension not found.",On="on_reject",Qt="always",ei="anonymous",Pn="identified",Ha="identified_only",Ss="visibilitychange",xs="beforeunload",si="$pageview",zo="$pageleave",Vo="$identify",du="$groupidentify";function Dr(t,e){U(t)&&t.forEach(e)}function oe(t,e){if(!q(t))if(U(t))t.forEach(e);else if(Ng(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)nf.call(t,n)&&e(t[n],n)}var me=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 ts(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 fu=function(t){try{return t()}catch{return}},km=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 oe(t,(function(n,i){(X(n)&&n.length>0||Re(n))&&(e[i]=n)})),e},Cm=["herokuapp.com","vercel.app","netlify.app"];function Pm(t){var e=t?.hostname;if(!X(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Cm)if(n===i)return!1;return!0}function Ee(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 Wa(t){return t.name==="ph_toolbar_internal"}var qf=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 Re(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 Am{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 Fm}}var hu,zf=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};E&&!C(E.crypto)&&crypto.getRandomValues&&(zf=t=>crypto.getRandomValues(t));class Fm{nextUint32(){return this.R.length>this.O||(zf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Jt=()=>Rm().toString(),Rm=()=>(hu||(hu=new Am)).generate(),$i="",Tm=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,en={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:qf,H(t){var e;try{e=JSON.parse(en.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(h,g){if(g===void 0&&(g=F),$i)return $i;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),x="dmn_chk_"+Jt();!$i&&v--;){var b=m.slice(v).join("."),_=x+"=1;domain=."+b+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(x)&&(g.cookie=_+";max-age=0",$i=b)}return $i})(c);if(!f){var p=(h=>{var g=h.match(Tm);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}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{en.F(t,"",-1,e)}catch{return}}},Go=null,ue={N(){if(!rt(Go))return Go;var t=!0;if(C(E))t=!1;else try{var e="__mplssupport__";ue.F(e,"xyz"),ue.P(e)!=='"xyz"'&&(t=!1),ue.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Go=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return E?.localStorage.getItem(t)}catch(e){ue.j(e)}return null},H(t){try{return JSON.parse(ue.P(t))||{}}catch{}return null},F(t,e){try{return E?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ue.j(n)}return!1},q(t){try{E?.localStorage.removeItem(t)}catch(e){ue.j(e)}}},$m=[ur,"distinct_id",ai,jl,Es,bs,mt],jr={},Mm={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>jr[t]||null,H:t=>jr[t]||null,F:(t,e)=>(jr[t]=e,!0),q(t){delete jr[t]}},An=null,Pe={N(){if(!rt(An))return An;if(An=!0,C(E))An=!1;else try{var t="__support__";Pe.F(t,"xyz"),Pe.P(t)!=='"xyz"'&&(An=!1),Pe.q(t)}catch{An=!1}return An},j(t){A.error("sessionStorage error: ",t)},P(t){try{return E?.sessionStorage.getItem(t)}catch(e){Pe.j(e)}return null},H(t){try{return JSON.parse(Pe.P(t))||null}catch{}return null},F(t,e){try{return E?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){Pe.j(n)}return!1},q(t){try{E?.sessionStorage.removeItem(t)}catch(e){Pe.j(e)}}};class Lm{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===Qt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===On}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 Bo(e)?1:j(jg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?ue:en;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?en:ue;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Bo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[Ke?.doNotTrack,Ke?.msDoNotTrack,O.doNotTrack].some((e=>Bo(e)))}}function Vf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!ze(i))return e;try{var r=i(e);return X(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var Gf="__POSTHOG_TOOLBAR__",Nm=1,Om=3,Bm=11;function pu(t){return t instanceof Element&&(t.id===Gf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function En(t){return!!t&&t.nodeType===Nm}function at(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Kf(t){return!!t&&t.nodeType===Om}function Yf(t){return!!t&&t.nodeType===Bm&&En(t.host)}var Jf=1e3;function Wl(t){return t?Js(t).split(/\s+/):[]}function gu(t,e){var n=(function(i){var r,s=E==null||(r=E.location)==null?void 0:r.href;return C(s)?void 0:Vf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ks(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 Wl(e)}function Zf(t){return q(t)?null:Js(t).split(/(\s+)/).filter((e=>nr(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function dr(t){var e="";return za(t)&&!th(t)&&t.childNodes&&t.childNodes.length&&oe(t.childNodes,(function(n){var i;Kf(n)&&n.textContent&&(e+=(i=Zf(n.textContent))!==null&&i!==void 0?i:"")})),Js(e)}function Ko(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ql=["a","button","form","input","select","textarea","label"];function qa(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 Xf(t){var e=t.parentNode;return!(!e||!En(e))&&e}var Dm=[".ph-no-autocapture","[data-ph-no-autocapture]"],Qf=["next","previous","prev",">","<"],jm=[...Qf,"+","-","−","–"],mu=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,vu=[".ph-no-rageclick",".ph-no-capture"],Um=["","text","search","email","password","url","tel","number"];function yu(t,e){if(!E||zl(t))return!1;var n,i,r,s,o;if(xt(e)?(n=!!e&&vu,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:vu,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!En(l))&&(!!at(l,"textarea")||(at(l,"input")?j(Um,(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=eh(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=Qf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,p=d.ariaLabel;return c.some((h=>mu(f,h)||mu(p,h)))}))})(i,a.map((l=>{var u;return{safeText:dr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!qa(a,n)}var zl=t=>!t||at(t,"html")||!En(t),eh=(t,e)=>{if(!E||zl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!at(r,"body");)if(Yf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=Xf(r);if(!s)break;if(e||ql.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=E.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function za(t){for(var e=new Set,n=0,i=t;i.parentNode&&!at(i,"body");i=i.parentNode){if(n++>=Jf||e.has(i))return!1;e.add(i);var r=ks(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(ks(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 th(t){return!!(at(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||at(t,"select")||at(t,"textarea")||t.getAttribute("contenteditable")==="true")}var _u=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}))$"),wu=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Hm=[16,15,14,13],Wm=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),bu=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Eu=/[0-9A-Za-z_]/;function qm(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 nr(t,e){if(e===void 0&&(e=!0),q(t))return!1;if(X(t)){t=Js(t);var n=e?_u.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(wu.lastIndex=0;s=wu.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Hm){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(_u.test(d)&&qm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Wm.test(t):(function(r){var s;for(bu.lastIndex=0;s=bu.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Eu.test(o)&&Eu.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Su(t){var e=dr(t);return nr(e=(e+" "+nh(t)).trim())?e:""}function nh(t){var e="";return t&&t.childNodes&&t.childNodes.length&&oe(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=dr(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+nh(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function xu(t){return t.replace(/"|\\"/g,'\\"')}function zm(t){var e=t.attr__class;if(e)return U(e)?e:Wl(e)}var Ur=ye("[Dead Clicks]"),Vm=()=>!0,Gm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(Bl)),i=t.instance.config.capture_dead_clicks;return xt(i)?i:!!ve(i)||n};class Iu{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({[Bl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=O.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=O.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Ur.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=O.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=ve(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=O.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),Ur.info("starting...")}}else Ur.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Ur.info("stopping..."))}}var Yo=ye("[SegmentIntegration]"),ih="posthog-js";function rh(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,p,h,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,x=((d=c.exception)==null?void 0:d.values)||[],b=x.map((S=>k({},S,{stacktrace:S.stacktrace?k({},S.stacktrace,{type:"raw",frames:(S.stacktrace.frames||[]).map((I=>k({},I,{platform:"web:javascript"})))}):void 0}))),_={$exception_message:((f=x[0])==null?void 0:f.value)||c.message,$exception_type:(p=x[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:b,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=x[0])==null?void 0:h.value)||c.message,$sentry_exception_type:(g=x[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 Km{constructor(e,n,i,r,s,o){this.name=ih,this.setupOnce=function(a){a(rh(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class ku{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=E?.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?$t(a/o,0,1,A):1,p=o>1?$t(l/o,0,1,A):1,h=u>1?$t(c/u,0,1,A):1,g=u>1?$t(d/u,0,1,A):1;r=me(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Jo=["flags","surveys"],Ym={[Mf]:{exposure:"hidden"},[qi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[zi]:{exposure:"hidden"},[Pa]:{exposure:"event"},[Aa]:{exposure:"hidden"},[Fa]:{exposure:"event"},[Ra]:{exposure:"hidden"},[Ta]:{exposure:"event"},[$a]:{exposure:"event"},[Bl]:{exposure:"event"},[Dl]:{exposure:"hidden"},[Ma]:{exposure:"event"},[jn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ai]:{exposure:"hidden"},[jl]:{exposure:"event"},[Lf]:{exposure:"event",shouldSkipFromEventProperties:t=>rt(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"},[Mn]:{exposure:"hidden",storageGroup:"flags"},[Vi]:{exposure:"hidden",storageGroup:"flags"},[Jr]:{exposure:"hidden"},[La]:{exposure:"hidden",storageGroup:"flags"},[Gi]:{exposure:"hidden",storageGroup:"flags"},[Zr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[_s]:{exposure:"hidden",storageGroup:"flags"},[Ft]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Kt]:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[Na]:{exposure:"hidden",storageGroup:"surveys"},[ws]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Oa]:{exposure:"event"},[Xr]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[Ki]:{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"},[Bn]:{exposure:"hidden"},[Yi]:{exposure:"hidden"},[es]:{exposure:"hidden"},[tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[mt]:{exposure:"hidden"},[Ba]:{exposure:"hidden"},[Da]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[Ua]:{exposure:"hidden"},[bs]:{exposure:"hidden"},[Es]:{exposure:"hidden"},[Nf]:{exposure:"event"},[Of]:{exposure:"event"},[Bf]:{exposure:"event"},[Df]:{exposure:"event"},[Uf]:{exposure:"event"},[Hf]:{exposure:"event"},[Wf]:{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"}},Jm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Fn=t=>{var e=Ym[t];if(e)return e;for(var n of Jm){var i=n[1];if(t.indexOf(n[0])===0)return i}},li=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return ef(t)}},Cs=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},yi=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," ")},fr=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},Ps=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},sh=(t,e)=>t>=e&&Zd(),oh=(t,e,n,i)=>{if(t===0){if(Zd()){var r=e+1;return r===n&&i(),r}return e}return 0},Hr="https?://(.*)",_i=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Zm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",..._i],hr="",Xm=["li_fat_id"];function ah(t,e,n){if(!F)return{};var i,r=e?[..._i,...n||[]]:[],s=lh(fr(F.URL,r,hr),t),o=(i={},oe(Xm,(function(a){var l=qf(a);i[a]=l||null})),i);return me(o,s)}function lh(t,e){var n=Zm.concat(e||[]),i={};return oe(n,(function(r){var s=yi(t,r);i[r]=s||null})),i}function ch(t){var e=(function(s){return s?s.search(Hr+"google.([^/?]*)")===0?"google":s.search(Hr+"bing.com")===0?"bing":s.search(Hr+"yahoo.com")===0?"yahoo":s.search(Hr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!rt(e)){i.$search_engine=e;var r=F?yi(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Cu(){return navigator.language||navigator.userLanguage}var As="$direct";function uh(){return F?.referrer||As}function dh(t,e,n){n===void 0&&(n=!1);var i=t?[..._i,...e||[]]:[],r=n?bn(be?.href):be?.href,s=r?.substring(0,1e3);return{r:uh().substring(0,1e3),u:s?fr(s,i,hr):void 0}}function fh(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?bn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==As?As:(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=lh(s);me(o,l)}if(i){var u=ch(i);me(o,u)}return o}function hh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Qm(){try{return new Date().getTimezoneOffset()}catch{return}}var ev={flags:tr,surveys:ws},tv=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ti="main";class Zo{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(),E){var r=()=>this.flush();Ee(E,"beforeunload",r,{capture:!1}),Ee(E,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Re(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){tv.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=[...$m,...o];return k({},ue,{H(u){try{var c={};try{c=en.H(u)||{}}catch{}var d,f=JSON.parse(ue.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];rt(g)||g===""||(p[h]=g)}d=me(f,p)}else d=me(c,f);return ue.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=ue.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&en.F(u,m,d,f,p,h)}catch(v){ue.j(v)}return g},q(u,c){try{E?.localStorage.removeItem(u),en.q(u,c)}catch(d){ue.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&ue.N()?(n=ue,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&Pe.N()?n=Pe:s==="memory"?n=Mm:s==="cookie"?n=en:i.N()?(n=i,r=!0):n=en,this.fi=r,n}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return oe(this.props,((n,i)=>{var r=Fn(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=me({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Jo){var n=ue.H(this.Si(e));if(n&&!sn(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||me(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Fn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=ev[e];if(!i)return!1;var r=n[i],s=this.props[i];return Re(r)&&Re(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Fn(e))==null?void 0:n.storageGroup:void 0,r=i?ue.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,ti))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,ti),Jo)){var s,o=i[r];(!sn(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(ue,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return oe(this.props,((i,r)=>{var s,o=(s=Fn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===ti)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return oe(e,((r,s)=>{var o;i[s]=(o=Fn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===ti||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!==ti&&(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 Jo)ue.q(this.Si(r));i?delete this.ci[ti]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(ve(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(oe(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(ve(e)){this.$i=C(n)?this.ji:n;var i=!1;if(oe(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||ve(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=ah(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);sn(Hl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?ch(e):{})}update_referrer_info(){var e;this.register_once({$referrer:uh(),$referring_domain:F!=null&&F.referrer&&((e=Cs(F.referrer))==null?void 0:e.host)||As},void 0)}set_initial_person_info(){this.props[ja]||this.props[Ua]||this.register_once({[bs]:dh(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={};oe([Ua,ja],(r=>{var s=this.props[r];s&&oe(s,(function(o,a){e["$initial_"+ba(a)]=o}))}));var n=this.props[bs];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=fh(r,s),a={};return oe(o,(function(l,u){a["$initial_"+ba(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);me(e,i)}return e}safe_merge(e){return oe(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,p)=>f===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[zi]||{};i[e]=n,this.Pi(zi,i),this.save()}remove_event_timer(e){var n=this.props[zi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(zi,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=Fn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Fn(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&&ze(n.then)&&n.then(void 0,(()=>{}))}}}}var Ve={GZipJS:"gzip-js",Base64:"base64"},Mi={Activation:"events",Cancellation:"cancelEvents"},Xo={Popover:"popover",API:"api",Widget:"widget"},tn={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Qo={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},Va={Popover:"popover",Inline:"inline"},nv={SHOWN:"product tour shown"},Pu={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Au=ye("[RateLimiter]");class iv{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=>{Au.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Au.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=(Re(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")&&be!=null&&be.pathname)return""+((e=be.origin)!==null&&e!==void 0?e:"")+be.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 vn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void vn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return vn.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){vn.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||vn.warn("Failed to fetch remote config from PostHog."):vn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){vn.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){vn.error("Error loading feature flags",r)}}}var yt=Uint8Array,it=Uint16Array,wi=Uint32Array,Vl=new yt([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]),Gl=new yt([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]),Fu=new yt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),gh=function(t,e){for(var n=new it(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]},mh=gh(Vl,2),Ga=mh[1];mh[0][28]=258,Ga[258]=28;for(var Ru=gh(Gl,0)[1],vh=new it(32768),Se=0;32768>Se;++Se){var ni=(43690&Se)>>>1|(21845&Se)<<1;vh[Se]=((65280&(ni=(61680&(ni=(52428&ni)>>>2|(13107&ni)<<2))>>>4|(3855&ni)<<4))>>>8|(255&ni)<<8)>>>1}var ir=function(t,e,n){for(var i=t.length,r=0,s=new it(e);i>r;++r)++s[t[r]-1];var o,a=new it(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new it(i),r=0;i>r;++r)o[r]=vh[a[t[r]-1]++]>>>15-t[r];return o},Vn=new yt(288);for(Se=0;144>Se;++Se)Vn[Se]=8;for(Se=144;256>Se;++Se)Vn[Se]=9;for(Se=256;280>Se;++Se)Vn[Se]=7;for(Se=280;288>Se;++Se)Vn[Se]=8;var Fs=new yt(32);for(Se=0;32>Se;++Se)Fs[Se]=5;var rv=ir(Vn,9),sv=ir(Fs,5),yh=function(t){return(t/8>>0)+(7&t&&1)},_h=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof it?it:t instanceof wi?wi:yt)(n-e);return i.set(t.subarray(e,n)),i},zt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Li=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},ea=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 yt(0),0];if(r==1){var o=new yt(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(S,I){return S.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 p=new it(f+1),h=Ka(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var x=s[i].s;if(e>=p[x])break;g+=v-(1<>>=m;g>0;){var b=s[i].s;e>p[b]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new yt(p),h]},Ka=function(t,e,n){return t.s==-1?Math.max(Ka(t.l,e,n+1),Ka(t.r,e,n+1)):e[t.s]=n},Tu=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new it(++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]},Ni=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ya=function(t,e,n){var i=n.length,r=yh(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)},$u=function(t,e,n,i,r,s,o,a,l,u,c){zt(e,c++,n),++r[256];for(var d=ea(r,15),f=d[0],p=d[1],h=ea(s,15),g=h[0],m=h[1],v=Tu(f),x=v[0],b=v[1],_=Tu(g),S=_[0],I=_[1],R=new it(19),w=0;x.length>w;++w)R[31&x[w]]++;for(w=0;S.length>w;++w)R[31&S[w]]++;for(var P=ea(R,7),$=P[0],L=P[1],M=19;M>4&&!$[Fu[M-1]];--M);var B,J,Y,T,V=u+5<<3,re=Ni(r,Vn)+Ni(s,Fs)+o,Ie=Ni(r,f)+Ni(s,g)+o+14+3*M+Ni(R,$)+(2*R[16]+3*R[17]+7*R[18]);if(re>=V&&Ie>=V)return Ya(e,c,t.subarray(l,l+u));if(zt(e,c,1+(re>Ie)),c+=2,re>Ie){B=ir(f,p),J=f,Y=ir(g,m),T=g;var ce=ir($,L);for(zt(e,c,b-257),zt(e,c+5,I-1),zt(e,c+10,M-4),c+=14,w=0;M>w;++w)zt(e,c+3*w,$[Fu[w]]);c+=3*M;for(var fe=[x,S],Te=0;2>Te;++Te){var Q=fe[Te];for(w=0;Q.length>w;++w)zt(e,c,ce[_e=31&Q[w]]),c+=$[_e],_e>15&&(zt(e,c,Q[w]>>>5&127),c+=Q[w]>>>12)}}else B=rv,J=Vn,Y=sv,T=Fs;for(w=0;a>w;++w)if(i[w]>255){var _e;Li(e,c,B[257+(_e=i[w]>>>18&31)]),c+=J[_e+257],_e>7&&(zt(e,c,i[w]>>>23&31),c+=Vl[_e]);var we=31&i[w];Li(e,c,Y[we]),c+=T[we],we>3&&(Li(e,c,i[w]>>>5&8191),c+=Gl[we])}else Li(e,c,B[i[w]]),c+=J[i[w]];return Li(e,c,B[256]),c+J[256]},ov=new wi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),av=(function(){for(var t=new wi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),ta=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function lv(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=av[255&p^f[h]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,p,h,g,m){var v=d.length,x=new yt(h+v+5*(1+Math.floor(v/7e3))+g),b=x.subarray(h,x.length-g),_=0;if(!f||8>v)for(var S=0;v>=S;S+=65535){var I=S+65535;v>I?_=Ya(b,_,d.subarray(S,I)):(b[S]=!0,_=Ya(b,_,d.subarray(S,v)))}else{for(var R=ov[f-1],w=R>>>13,P=8191&R,$=(1<S;++S){var _e=Y(S),we=32767&S,Le=M[_e];if(L[we]=Le,M[_e]=we,S>=Te){var ht=v-S;if((Ie>7e3||fe>24576)&&ht>423){_=$u(d,b,0,T,V,re,ce,fe,Q,S-Q,_),fe=Ie=ce=0,Q=S;for(var ne=0;286>ne;++ne)V[ne]=0;for(ne=0;30>ne;++ne)re[ne]=0}var je=2,N=0,$e=P,ke=we-Le&32767;if(ht>2&&_e==Y(S-ke))for(var he=Math.min(w,ht)-1,qe=Math.min(32767,S),Zn=Math.min(258,ht);qe>=ke&&--$e&&we!=Le;){if(d[S+je]==d[S+je-ke]){for(var Xe=0;Zn>Xe&&d[S+Xe]==d[S+Xe-ke];++Xe);if(Xe>je){if(je=Xe,N=ke,Xe>he)break;var Xn=Math.min(ke,Xe-2),Ut=0;for(ne=0;Xn>ne;++ne){var Ht=S-ke+ne+32768&32767,pt=Ht-L[Ht]+32768&32767;pt>Ut&&(Ut=pt,Le=Ht)}}}ke+=(we=Le)-(Le=L[we])+32768&32767}if(N){T[fe++]=268435456|Ga[je]<<18|Ru[N];var Wt=31&Ga[je],Ai=31&Ru[N];ce+=Vl[Wt]+Gl[Ai],++V[257+Wt],++re[Ai],Te=S+je,++Ie}else T[fe++]=d[S],++V[d[S]]}}_=$u(d,b,!0,T,V,re,ce,fe,Q,S-Q,_)}return _h(x,0,h+yh(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var p=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&ta(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),ta(u,c-8,n.d()),ta(u,c-4,i),u}var cv=!!ya||!!Rl,wh="text/plain",ns=!1,bh=(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:"")},Xs=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("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return oe(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},na=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===Ve.GZipJS){var i=lv((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new yt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new yt(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return _h(c,0,d)})(li(e)),{mtime:0});return{contentType:wh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===Ve.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(li(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:li(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=li(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Eh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Xs(t.url,{compression:Ve.Base64}),encodedBody:na(k({},t,{compression:Ve.Base64,Ji:void 0}))}:{url:bh(t.url,"compression"),encodedBody:na(k({},t,{compression:void 0,Ji:void 0}))};try{e=na(t)}catch(r){if(Qc(t.compression,yi(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&Qc(t.compression,yi(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?_a(new Uint8Array(n)):ArrayBuffer.isView(n)&&_a(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(ns=!0,i()):{url:t.url,encodedBody:e}},Sh=t=>{try{return Eh(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},uv=(function(){var t=le((function*(e){var n=li(e.data),i=yield(function(s,o,a){return wa.apply(this,arguments)})(n,se.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:wh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),dv=/Failed to fetch|NetworkError|Load failed/i,xh=t=>t?.name==="TypeError"&&dv.test(t?.message||""),Ih=t=>{var e=Sh(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;oe(t.headers,(function(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Gc){var d=new Gc;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||xh(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;Rl(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(h){u&&clearTimeout(u.timeout),f(h)}}},Ja=t=>{try{var e,n=Eh(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(Ke.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 Ja(k({},t,{data:d(u.slice(0,c))})),void Ja(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Ih(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Mu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Xs(n===Ve.GZipJS?bh(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===Ve.GZipJS?{}:{compression:n}))},is=[];Rl&&is.push({transport:"fetch",method:Ih}),ya&&is.push({transport:"XHR",method(t){var e=Sh(t);if(e){var n=new ya,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;oe(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)}}}),Ke!=null&&Ke.sendBeacon&&is.push({transport:"sendBeacon",method:Ja});var Za=3e3;class fv{constructor(e,n){this.Xi=!0,this.tr=[],this.er=$t(n?.flush_interval_ms||Za,250,5e3,A.createLogger("flush interval"),Za),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)&&oe(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 oe(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 hv=["retriesPerformedSoFar"];class pv{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(E)&&"onLine"in E.navigator&&(this.dr=E.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},Ee(E,"online",this.vr),Ee(E,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=Xd(e,hv);Gt(n)&&(i.url=Xs(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(E)||(this.vr&&(E.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(E.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 gv{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(){Ee(E,"scroll",this.yr,{capture:!0}),Ee(E,"scrollend",this.yr,{capture:!0}),Ee(E,"resize",this.yr)}scrollElement(){if(!this._r)return E?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=E?.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 E?e==="y"?E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop||0:E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var mv=t=>dh(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Lu{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({[Ba]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||mv,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Ba]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?fh(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 oe(Hl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+ba(i)]=n})),e}}class Kl{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 Oi=ye("[SessionId]");class Nu{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 Kl,this.Lr=(u,c)=>!(!Gt(u)||!Gt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Qt)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||Jt,this.Nr=i||Jt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*$t(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Oi.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=Pe.H(this.jr),a=Pe.H(this.Br);o&&!a?this.Or=o:Pe.q(this.jr),Pe.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){Oi.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&&Pe.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&Pe.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?Pe.H(this.jr):null}Zr(e){var n=this.Pr;return!rt(n)&&!rt(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({[ai]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Gt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(ai):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!rt(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({[ai]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Gt(e)?e:0,i=Gt(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[ai];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&&E&&(E.removeEventListener(xs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&Pe.q(this.Br)},Ee(E,xs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Qt)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=Gt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||Oi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),Oi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Oi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Gt(a)&&e&&!u?a:i,v=Gt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var x={noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((b=>b(s,l,x))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?x: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 kh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&tu(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>tu(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Ch(){return(Ch=le((function*(){var t=Ke?.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 Rs=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 ia(t,e,n){return li({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Ph={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=>Rs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Rs(n,i))))),icontains:(t,e)=>e.map(qr).some((n=>t.map(qr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(qr).every((n=>t.map(qr).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 Ah(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||rt(r))return!1;var s=[String(r)],o=Ph[i.operator];return!!o&&o(i.values,s)}))}var Xa="custom",Ou="i.posthog.com",vv=/^\/static\//;class yv{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":Xa),this.en[this.apiHost]}rn(e){if(vv.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=Ou+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Fh(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var ee=ye("[Surveys]"),Rh="seenSurvey_",Th=t=>{try{var e=(n=>((i,r)=>""+Rh+(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){ee.error("Failed to persist survey seen state",n)}},_v=[Xo.Popover,Xo.Widget,Xo.API],wv={ignoreConditions:!1,ignoreDelay:!1,displayType:Va.Popover},bv=ye("[PostHog ExternalIntegrations]"),Ev={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Sv{constructor(e){this._instance=e}ai(e,n){var i;(i=O.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return bv.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=O.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Ev[l],(()=>{var c;(c=O.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=O.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=O.__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 xv{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return le((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&&ze(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 Iv{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 Bu="extensionsRemoteConfig";class kv{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Iv(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(Bu,i);return this.un&&i(this.un),Wr(r)},this.vn=new xv(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(ur))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(ur);return typeof e=="string"?e:void 0}get library(){return{name:se.LIB_NAME,version:se.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 le((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(Bu,e))}sendRequest(e,n){var i=this;return le((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?Xs(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 rr={},ra=0,Ts=()=>{},Du='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Bi="Surveys module not available",ju="sanitize_properties is deprecated. Use before_send instead",$h="Invalid value for property_denylist config: ",Cv=["token","distinct_id",jf],oi="posthog",Mh=!cv&&et?.indexOf("MSIE")===-1&&et?.indexOf("Mozilla")===-1,sa=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:Pm(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Ts,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:be&&X(be?.search)&&be.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:(E==null||(e=E.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:Ha,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Za},error_tracking:{},_onCapture:Ts},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:jm,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))},Pv=[["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 Pv){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=me({},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($h+t.property_denylist)),s};class Av{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 st{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===Qt||this.config.cookieless_mode===On&&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 Av,this.mn=!1,this.version=se.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Kl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=sa(),this.SentryIntegration=Km,this.sentryIntegration=i=>(function(r,s){var o=rh(r,s);return{name:ih,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 gv(this),this.pageViewManager=new ku(this),this.rateLimiter=new iv(this),this.requestRouter=new yv(this),this.consent=new Lm(this),this.externalIntegrations=new Sv(this);var n=(e=st.__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!==oi){var r,s=(r=rr[i])!==null&&r!==void 0?r:new st;return s._init(e,n,i),rr[i]=s,rr[oi][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=sa(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=sa(n.defaults),u=Uu(n),c=me({},l,u,{name:i,token:a});ve(l.rageclick)&&ve(u.rageclick)&&(c.rageclick=me({},l.rageclick,u.rageclick)),ve(l.session_recording)&&ve(u.session_recording)&&(c.session_recording=me({},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:Ve.GZipJS;var d=this.En();if(this.persistence=new Zo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Zo(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&&Pe.N()){var f=Pe.H(this.bn);U(f)&&f.forEach((I=>{X(I)&&this.yn.add(I)}))}else Pe.q(this.bn);var p=k({},this.persistence.props),h=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new fv((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new pv(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Nu(this),this.sessionPropsManager=new Lu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,R,w)=>{(w!=null&&w.activityTimeout||w!=null&&w.sessionPastMaximumLength||w!=null&&w.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)),se.DEBUG=se.DEBUG||this.config.debug,se.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p,s:h}),!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(),x=this.persistence.get_property(mt);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&x===ei)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&x===Pn)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(Jt()),_=n.bootstrap.isIdentifiedID?b:m;this.persistence.set_property(mt,n.bootstrap.isIdentifiedID?Pn:ei),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Br,$device_id:null},"");else if(!this.get_distinct_id()){var S=this.config.get_device_id(Jt());this.register_once({distinct_id:S,$device_id:S},""),this.persistence.set_property(mt,ei)}return Ee(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,R){var w=I.config.segment;if(!w)return R();(function(P,$){var L=P.config.segment;if(!L)return $();var M=J=>{var Y=()=>J.anonymousId()||Jt();P.config.get_device_id=Y,J.id()&&(P.register({distinct_id:J.id(),$device_id:Y()}),P.persistence.set_property(mt,Pn)),$()},B=L.user();"then"in B&&ze(B.then)?B.then(M):M(B)})(I,(()=>{w.register((P=>{typeof Promise<"u"&&Promise.resolve||Yo.warn("This browser does not have Promise support, and can not use the segment integration");var $=(L,M)=>{if(!M)return L;L.event.userId||L.event.anonymousId===P.get_distinct_id()||(Yo.info("No userId set, resetting PostHog"),P.reset()),L.event.userId&&L.event.userId!==P.get_distinct_id()&&(Yo.info("UserId set, identifying with PostHog"),P.identify(L.event.userId));var B=P.calculateEventProperties(M,L.event.properties);return L.event.properties=Object.assign({},B,L.event.properties),L};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:L=>$(L,L.event.event),page:L=>$(L,si),identify:L=>$(L,Vo),screen:L=>$(L,"$screen")}})(I)).then((()=>{R()}))}))})(this,(()=>this.On())):this.On(),ze(this.config._onCapture)&&this.config._onCapture!==Ts&&(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 Ch.apply(this,arguments)})().then((I=>{I&&this.register({[qo]:I})})).catch(Ts),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=st.__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)),ze(this.featureFlags.onReloading)&&ze(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({},st.__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,Gm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Uf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Hf]: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,Ve.GZipJS)?Ve.GZipJS:j(r.supportedCompression,Ve.Base64)?Ve.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:Ha}),(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&&be!=null&&be.hostname){var e=be.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 ph(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()&&Dr(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(zo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(zo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Mh?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=Ve.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((x=>k({},x,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Mu(o.url,o.method,o.compression,o.timestampMode);var p=is.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var x=0;m.length>x;x++)if(m[x].transport===f)return m[x]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){xh(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===Ve.GZipJS&&Fg&&typeof Promise<"u"&&!ns?uv(o).then((m=>{g(m)})).catch((m=>{if(eu(m))return ns=!0,void g(k({},o,{compression:void 0,url:Mu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var x="name"in v?String(v.name):"";return eu(v)||x===Qd})(m)&&(ns=!0),g(o)})):h(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){ra++;try{var n,i=[],r=[],s=[];Dr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(ze(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&&ze(this[n])?s.push(a):r.push(a)}));var o=function(a,l){Dr(a,(function(u){try{if(U(u[0])){var c=l;oe(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{ra--}}push(e){if(ra>0&&U(e)&&X(e[0])){var n=st.prototype[e[0]];ze(n)&&n.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,n,i){var r,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!C(e)&&X(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){n!=null&&n.$current_url&&!X(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,p=su(i?.uuid,Jt),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===si&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(_s)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,x,b,_=g?void 0:this.Vn(i?.$set_once,e!==du,e===Vo);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=M=>X(M)?M.slice(0,s):M,l=new Set,h=(function M(B,J){if(B!==Object(B))return a?a(B):B;if(!l.has(B)){var Y;if(l.add(B),U(B))Y=[],Dr(B,(V=>{Y.push(M(V))}));else{var T={};oe(B,((V,re)=>{l.has(V)||(T[re]=M(V))})),Y=T}return Y}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function(M,B){B===void 0&&(B=[]);var J={},Y=T=>{M[T]!==void 0&&(J[T]=M[T])};return Rg.forEach(Y),B.forEach(Y),J})(h.properties,Cv)),e===tn.DISMISSED||e===tn.SENT){var S=n?.[Qo.SURVEY_ID],I=n?.[Qo.SURVEY_ITERATION];Th({id:S,current_iteration:I}),h.$set=k({},h.$set,{[(v={id:S,current_iteration:I},x=e===tn.SENT?"responded":"dismissed",b="$survey_"+x+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(b="$survey_"+x+"/"+v.id+"/"+v.current_iteration),b)]:!0})}else e===tn.SHOWN&&(h.$set=k({},h.$set,{[Qo.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===nv.SHOWN){var R=n?.[Pu.TOUR_TYPE];R&&(h.$set=k({},h.$set,{[Pu.TOUR_LAST_SEEN_DATE+"/"+R]:new Date().toISOString()}))}var w=k({},h.properties.$set,h.$set);if(sn(w)||this.setPersonPropertiesForFlags(w),!q(this.config.before_send)){var P=this.Pt(h);if(!P)return;(h=P).uuid=su(h.uuid,Jt)}this.dn.emit("eventCaptured",h);var $=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),L={method:"POST",url:$,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:i?._batchKey,transport:i?.transport};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Pn(L):this.In.enqueue(L),h}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new kv(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[jf]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!X(a.distinct_id)&&!Re(a.distinct_id)||Ea(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(S,I,R,w){var P,$,L,M;if(w===void 0&&(w=!1),!et)return{};var B,J=S?[..._i,...I||[]]:[],Y=(function(Zn){for(var Xe=0;iu.length>Xe;Xe++){var Xn=iu[Xe],Ut=Xn[1],Ht=Xn[0].exec(Zn),pt=Ht&&(ze(Ut)?Ut(Ht,Zn):Ut);if(pt)return pt}return["",""]})(et),T=Y[0],V=Y[1],re=(B=typeof navigator<"u"?navigator:void 0)!=null&&B.brave?{brave:!0}:{},Ie={};C(R)||(Ie.detectGoogleSearchApp=R);var ce={},fe=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,Te=($=navigator)==null?void 0:$.maxTouchPoints,Q=E==null||(L=E.screen)==null?void 0:L.width,_e=E==null||(M=E.screen)==null?void 0:M.height,we=E?.devicePixelRatio;C(fe)||(ce.userAgentDataPlatform=fe),C(Te)||(ce.maxTouchPoints=Te),C(Q)||(ce.screenWidth=Q),C(_e)||(ce.screenHeight=_e),C(we)||(ce.devicePixelRatio=we);var Le,ht,ne,je,N,$e,ke,he,qe=me(Hl({$os:T,$os_version:V,$browser:If(et,navigator.vendor,re,Ie),$device:ru(et),$device_type:(ht=et,ne=ce,he=ru(ht),he===af||he===of||he==="Kobo"||he==="Kindle Fire"||he===wf?gi:he===lr||he===di||he===cr||he===xa?"Console":he===cf?"Wearable":he?dt:ne?.userAgentDataPlatform==="Android"&&((je=ne?.maxTouchPoints)!==null&&je!==void 0?je:0)>0?600>Math.min((N=ne?.screenWidth)!==null&&N!==void 0?N:0,($e=ne?.screenHeight)!==null&&$e!==void 0?$e:0)/((ke=ne?.devicePixelRatio)!==null&&ke!==void 0?ke:1)?dt:gi:"Desktop"),$timezone:hh(),$timezone_offset:Qm()}),{$current_url:fr(w?bn(be?.href):be?.href,J,hr),$host:be?.host,$pathname:be?.pathname,$raw_user_agent:et.length>1e3?et.substring(0,997)+"...":et,$browser_version:Jg(et,navigator.vendor,re,Ie),$browser_language:Cu(),$browser_language_prefix:(Le=Cu(),typeof Le=="string"?Le.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:se.LIB_NAME,$lib_version:se.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return se.SDK_DIST_CHANNEL&&(qe.$sdk_dist_channel=se.SDK_DIST_CHANNEL),qe})(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&&me(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&me(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(S){a.$sdk_debug_error_capturing_properties=String(S)}if(this.requestRouter.region===Xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==si||s?e!==zo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=me(a,u),e===si&&F&&(a.title=F.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}et&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();oe(["$referrer","$referring_domain"],(S=>{S in g&&delete m[S]}));var v={};if(this._n.length>0)for(var x of this._n.slice())try{me(v,x())}catch(S){A.error("Failed to produce browser extension event properties",S)}(a=me({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?oe(this.config.property_denylist,(function(S){delete a[S]})):A.error($h+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(A.error(ju),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=me({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(ju),a=l(a,"$set_once")),n&&(this.mn=!0),sn(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||!Pe.N())Pe.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?Pe.F(this.bn,n):Pe.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:Bi}),()=>{})}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:Bi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Bi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=wv),(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:Bi}}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:Bi})}Jn(e){return!e||Ea(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Br?(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(Re(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(ur)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(qi)&&(this.unregister(qi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(mt)||ei)===ei,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(mt,Pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Vo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=ia(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(mt,Pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=ia(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Bn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=ia(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(du,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var p,h=this.get_property(ur),g=this.get_property(qo),m=this.get_property(jn),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(p=this.persistence)==null||p.register({[jn]: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(mt,ei),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Qt)this.register_once({distinct_id:Br,$device_id:null},"");else{var x=this.config.get_device_id(Jt());this.register_once({distinct_id:x,$device_id:e?x:h},""),e||C(g)||this.register({[qo]: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 le((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(Mf)?(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(qi,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(ve(e)){var i,r,s,o,a,l,u,c,d,f,p,h;me(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 Zo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);xt(m)&&(this.config.debug=m),xt(this.config.debug)&&(this.config.debug?(se.DEBUG=!0,ue.N()&&ue.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(se.DEBUG=!1,ue.N()&&ue.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){se.LIB_NAME=e,se.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:st.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:oi;return n!==oi&&(n=oi+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(mt))===Pn||((n=this.sessionPersistence)==null?void 0:n.get_property(mt))===Pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===Ha&&!this._isIdentified()&&sn(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[qi])&&((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!==On)}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!==Qt){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 Nu(this),this.pageViewManager=new ku(this),this.persistence&&(this.sessionPropsManager=new Lu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=st.__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==On&&((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(Du)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Qt?(this.config.cookieless_mode===On&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===On&&(this.register({distinct_id:Br,$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(Du)}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===Qt||(this.config.cookieless_mode===On?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return Ke?kh(Ke,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(si,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(Ss,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),Ee(F,Ss,this.kn)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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&&!q(n[i]),l=r in n&&!q(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(q(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Bg),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),q(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Og(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!sn(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&&q(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=xt(e)&&!e,i=ue.N()&&ue.P("ph_debug")==="true";return!n&&(!!i||e)}}st.__defaultExtensionClasses={},st.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]]=km(t.prototype[e[n]])})(st,["identify"]);class Hu{constructor(e){this.disabled=e===!1;var n=ve(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 oa="$copy_autocapture",aa=ye("[AutoCapture]");function la(t,e){return e.length>t?e.slice(0,t)+"...":e}function Fv(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!En(e));return e}function Rv(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!En(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!at(f,"body")&&Jf>c.length;)if(Yf(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!En(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},x=!1,b=!1;if(oe(c,(w=>{var P=za(w);if(at(w,"a")){var $=w.getAttribute("href");x=!!(P&&$&&nr($))&&(u?bn($):$)}j(ks(w),"ph-no-capture")&&(b=!0),m.push((function(M,B,J,Y,T){T===void 0&&(T=!1);var V=M.tagName.toLowerCase(),re={tag_name:V};ql.indexOf(V)>-1&&!J&&(re.$el_text=V.toLowerCase()==="a"||V.toLowerCase()==="button"?la(1024,Su(M)):la(1024,dr(M)));var Ie=ks(M);Ie.length>0&&(re.classes=Ie.filter((function(Q){return Q!==""}))),oe(M.attributes,(function(Q){var _e;if((!th(M)||["name","id","class","aria-label"].indexOf(Q.name)!==-1)&&(Y==null||!Y.includes(Q.name))&&!B&&nr(Q.value)&&(!X(_e=Q.name)||_e.substring(0,10)!=="_ngcontent"&&_e.substring(0,7)!=="_nghost")){var we=Q.value;Q.name==="class"&&(we=Wl(we).join(" ")),re["attr__"+Q.name]=la(1024,Q.name==="href"&&T?bn(we):we)}}));for(var ce=1,fe=1,Te=M;Te=Fv(Te);)ce++,Te.tagName===M.tagName&&fe++;return re.nth_child=ce,re.nth_of_type=fe,re})(w,s,o,a,u));var L=(function(M){if(!za(M))return{};var B={};return oe(M.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var Y=J.name.replace("data-ph-capture-attribute-",""),T=J.value;Y&&T&&nr(T)&&(B[Y]=T)}})),B})(w);me(v,L)})),b)return{props:{},explicitNoCapture:b};if(o||(m[0].$el_text=at(t,"a")||at(t,"button")?Su(t):dr(t)),x){var _,S;m[0].attr__href=x;var I=(_=Cs(x))==null?void 0:_.host,R=E==null||(S=E.location)==null?void 0:S.host;I&&R&&I!==R&&(h=x)}return{props:me({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(w){return w.map((P=>{var $,L,M="";if(P.tag_name&&(M+=P.tag_name),P.attr_class)for(var B of(P.attr_class.sort(),P.attr_class))M+="."+B.replace(/"/g,"");var J=k({},P.text?{text:P.text}:{},{"nth-child":($=P.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(L=P.nth_of_type)!==null&&L!==void 0?L:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),Y={};return ts(J).sort(((T,V)=>T[0].localeCompare(V[0]))).forEach((T=>{var V=T[1];return Y[xu(T[0].toString())]=xu(V.toString())})),(M+=":")+ts(Y).map((T=>T[0]+'="'+T[1]+'"')).join("")})).join(";")})((function(w){return w.map((P=>{var $,L,M={text:($=P.$el_text)==null?void 0:$.slice(0,400),tag_name:P.tag_name,href:(L=P.attr__href)==null?void 0:L.slice(0,2048),attr_class:zm(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return ts(P).filter((B=>B[0].indexOf("attr__")===0)).forEach((B=>M.attributes[B[0]]=B[1])),M}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var Di=ye("[ExceptionAutocapture]"),Wu=()=>{},Tv=ye("[TracingHeaders]"),Rn=ye("[Web Vitals]"),qu=9e5,zu="disabled",Vu="lazy_loading",ji="awaiting_config",zr="missing_config";ye("[SessionRecording]"),ye("[SessionRecording]");var Qa="[SessionRecording]",Vt=ye(Qa),$v=ye("[Heatmaps]");function ca(t){return ve(t)&&"clientX"in t&&"clientY"in t&&Re(t.clientX)&&Re(t.clientY)}var Vr=ye("[Product Tours]"),ua=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Dl))},Mv=["$set_once","$set"],Ct=ye("[SiteApps]"),Gu="Error while initializing PostHog app with config id ";function ii(t,e,n){if(q(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 Lv{constructor(e){this.ns=new Kl,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"||!ii(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=>ii(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&ii((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=>ii(u.text,n.text,n.text_matching||"exact")||ii(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;!q(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=>ii(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||Ah(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 Nv{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&&Ah(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===Mi.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 Lv(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,Mi.Activation),this.ks=this.Ps(e,Mi.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,Mi.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,Mi.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&&(sn(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Re(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=>Re(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 Ov extends Nv{constructor(e){super(e)}Js(){return Oa}Ys(){return Xr}Ms(){return Qr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Qr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Qr)}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 Re(r)&&r>0}ra(){return tn.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 ee}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Oa]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Xr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Xr)}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 Fh(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===tn.SHOWN?"consume":"ignore":e===tn.SHOWN?"persist":e===tn.DISMISSED||e===tn.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Gr="SDK is not enabled or survey functionality is not yet loaded",Ku="Disabled. Not loading surveys.",Bv=E!=null&&E.location?Ps(E.location.hash,"__posthog")||Ps(location.hash,"state"):null,Yu="_postHogToolbarParams",Ju=ye("[Toolbar]"),Zu=ye("[FeatureFlags]");class Dv{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||(Zu.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)||Zu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Xu=ye("[FeatureFlags]"),Tn=ye("[FeatureFlags]",{debugEnabled:!0}),da=`" failed. Feature flags didn't load in time.`,Qu="connection_error",ed=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},td=t=>{var e={};for(var n of ts(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},Pt=ye("[Error tracking]"),nd="Refusing to render web experiment since the viewer is a likely bot",jv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Rs(e,t),not_regex:(t,e)=>!Rs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Ue{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Ue.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Ue.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];Ue.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())Ue.aa(nd);else if(!this.Ne.disable_web_experiments){if(q(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Ue.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=Ue.getWindowLocation();if(e!=null&&e.search){var n=yi(e?.search,"__experiment_id"),i=yi(e?.search,"__experiment_variant");n&&i&&(Ue.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&&(Ue.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!q(e.conditions)&&Ue.da(e,n)&&Ue.va(e)}static da(e,n){var i;if(q(e.conditions)||q((i=e.conditions)==null?void 0:i.url))return!0;var r=Ue.getWindowLocation();if(r){var s,o,a,l=Vf(n,r.href);return(s=e.conditions)==null||!s.url||jv[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return E?.location}static va(e){var n;if(q(e.conditions)||q((n=e.conditions)==null?void 0:n.utm))return!0;var i=ah();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,h=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&h&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Ue.aa(nd):n!=="control"?i.forEach((r=>{if(r.selector){var s;Ue.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)}))}})):Ue.aa("Control variants leave the page unmodified.")}_is_bot(){return Ke&&this._instance?kh(Ke,this.Ne.custom_blocked_useragents):void 0}}var gt=ye("[Conversations]"),$n="Conversations not available yet.",id="console",Lh="__posthogHandledLogsRequestError",fa=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Lh]=!0,n},rd=t=>!!t&&typeof t=="object"&&t[Lh]===!0,Qs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Xu,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 Dv(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 E&&Ee(E,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){E?.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=[],E?.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[Vi,Gi,Zr,Ft]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa(Mn);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(tr);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(Mn))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Gi))!==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:Jc(f),variant:Zc(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(Ft),n=this.Oa(Ln);if(!n&&!e)return t||{};var i=me({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],p=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Jc(i),variant:Zc(i),payload:Yc(e[n])}}))}getFlagVariants(){var t=this.Oa(Mn),e=this.Oa(Ft);if(!e)return t||{};for(var n=me({},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(Gi),e=this.Oa(Ln);if(!e)return t||{};for(var n=me({},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(Bn)}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(Kt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Nn),timezone:hh()};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({[es]:[Qu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?Ve.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Qu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[es]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(p,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return sh(this.Sa,3)}Ua(t){this.Sa=oh(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+da)}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(Zr)||void 0,u=this.Oa(tr)||void 0,c=this.Oa(Bn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Yi);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Bn]:c,[Yi]:n});else{var h,g,m,v,x,b,_,S,I,R;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Bn]:c},n?{[Yi]:n}:{}));var w=this.getFeatureFlagDetails(t),P=[...(h=this.Oa(es))!==null&&h!==void 0?h:[]];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(w==null||(v=w.metadata)==null?void 0:v.has_experiment)||($.$feature_flag_has_experiment=w.metadata.has_experiment),C(w==null||(x=w.metadata)==null?void 0:x.version)||($.$feature_flag_version=w.metadata.version);var L,M=(b=w==null||(_=w.reason)==null?void 0:_.description)!==null&&b!==void 0?b:w==null||(S=w.reason)==null?void 0:S.code;M&&($.$feature_flag_reason=M),w!=null&&(I=w.metadata)!=null&&I.id&&($.$feature_flag_id=w.metadata.id),C(w?.original_variant)&&C(w?.original_enabled)||($.$feature_flag_original_response=C(w.original_variant)?w.original_enabled:w.original_variant),w!=null&&(R=w.metadata)!=null&&R.original_payload&&($.$feature_flag_original_payload=w==null||(L=w.metadata)==null?void 0:L.original_payload),P.length&&($.$feature_flag_error=P.join(",")),this.za($)}else n&&this.F({[Bn]:c,[Yi]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Yc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+da)}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 le((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"?Ve.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+da),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=Xu);var c=((I,R)=>{var w=I.flags;return w?k({},I,{featureFlags:Object.fromEntries(Object.keys(w).map((P=>{var $;return[P,($=w[P].variant)!==null&&$!==void 0?$:w[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(w).filter((P=>w[P].enabled)).filter((P=>{var $;return($=w[P].metadata)==null?void 0:$.payload})).map((P=>{var $;return[P,($=w[P].metadata)==null?void 0:$.payload]})))}):(I.featureFlags&&R.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,p=c.featureFlagPayloads;if(f){var h=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Vi]:f,[Mn]:m,[_s]:!1}}var x=f,b=p,_=d;if(l!=null&&l.partialResponse)x=k({},s,x),b=k({},o,b),_=k({},a,_);else if(r.errorsWhileComputingFlags)if(d){var S=new Set(Object.keys(d).filter((I=>{var R;return!((R=d[I])!=null&&R.failed)})));x=k({},s,Object.fromEntries(Object.entries(x).filter((I=>S.has(I[0]))))),b=k({},o,Object.fromEntries(Object.entries(b||{}).filter((I=>S.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>S.has(I[0])))))}else x=k({},s,x),b=k({},o,b),_=k({},a,_);return k({[Vi]:Object.keys(td(x)),[Mn]:x||{},[Gi]:b||{},[La]:_||{},[_s]:r.minimalFlagCalledEvents===!0},h?{[Zr]:h}:{},g?{[tr]: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([Ft,Ln]),this.Va(),void Tn.info("All overrides cleared");if(U(t))return this.F({[Ft]:ed(t)}),this.Va(),void Tn.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[Ft]=U(r)?ed(r):r),s&&(i[Ln]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([Ft,Ln]):r===!1?this.q(Ft):s===!1&&this.q(Ln),this.Va(),r===!1?Tn.info("Flag overrides cleared"):r&&Tn.info("Flag overrides set",{flags:r}),void(s===!1?Tn.info("Payload overrides cleared"):s&&Tn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[Ft]:t}),this.Va(),void Tn.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(Jr)||[]).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({[Vi]:Object.keys(td(o)),[Mn]:o,[Kt]:k({},this.Oa(Kt)||{},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(Jr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return le((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({[Jr]: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(Kt)||{},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({[Kt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Kt)||{});t.forEach((i=>{delete n[i]})),this.F({[Kt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Kt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(Nn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[Nn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Nn)||{};this.F({[Nn]:k({},e,{[t]:{}})})}else this.q(Nn)}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}}},Uv={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===ji||this.Ya===zr?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=zu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=E==null||(e=E.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 Vt.error("started without valid sessionManager"),new Error(Qa+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Qt)throw new Error(Qa+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&Ee(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(jn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return E&&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),Vt.info("starting")):(this.Ya=zu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ji&&this.Ya!==zr&&(this.Ya=Vu),O!=null&&(e=O.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=O.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=O.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return Vt.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(jl),(e=this.Mr)==null||e.unregister(Lf)}uo(t,e){if(q(t))return null;var n,i=Re(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(Vt.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;q(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[jn]: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===ji&&(this.Ya=zr,Vt.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):Vt.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(jn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(jn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return Vt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!q(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=O.__PosthogExtensions__)==null||!e.initSessionRecording)return Vt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Wf]:!0});var r;if(this.Ja||(this.Ja=(r=O.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===zr||this.Ya===ji?void 0:(this.Ya=ji,Vt.info("persisted remote config is stale, requesting fresh config before starting"),void new ph(this._instance).load());this.Ya=Vu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Of]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Nf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Bf:Df]:!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))}}},Hv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Hu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=ve(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(E&&F){var t=n=>{n=n||E?.event;try{this.bo(n)}catch(i){aa.error("Failed to capture event",i)}};if(Ee(F,"submit",t,{capture:!0}),Ee(F,"change",t,{capture:!0}),Ee(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||E?.event;try{this.bo(n,oa)}catch(i){aa.error("Failed to capture copy/cut event",i)}};Ee(F,"copy",e,{capture:!0}),Ee(F,"cut",e,{capture:!0})}}}else aa.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;xt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Pa]: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[Pa],i=this.co,r=this.instance.Qi()&&!this.fo;if(rt(i)&&!xt(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=Ko(t);Kf(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())&&yu(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===oa;if(i&&(function(d,f,p,h,g,m){var v;if(!E||zl(d)||p!=null&&p.url_allowlist&&!gu(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&gu(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var x=p.dom_event_allowlist;if(x&&!x.some((w=>f.type===w)))return!1}var b=eh(d,h),_=b.parentIsUsefulElement,S=b.targetElementList;if(!(function(w,P){var $=P?.element_allowlist;if(C($))return!0;var L,M=function(J){if($.some((Y=>J.tagName.toLowerCase()===Y)))return{v:!0}};for(var B of w)if(L=M(B))return L.v;return!1})(S,p)||!qa(S,p?.css_selector_allowlist)||qa(S,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Dm))return!1;try{var I=E.getComputedStyle(d);if(I&&I.getPropertyValue("cursor")==="pointer"&&f.type==="click")return!0}catch{}var R=d.tagName.toLowerCase();switch(R){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&&(ql.indexOf(R)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Rv(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===oa){var l,u=Zf(E==null||(l=E.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 ze(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(E==null||(e=E.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(){E&&E.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(E&&((e=E.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return Wu;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 ze(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];ze(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 Wu}})(E.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=E==null||(e=E.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(si,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};Ee(E,"popstate",t),this.wo=()=>{E&&E.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Aa]),this.rageclicks=new Hu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return ve(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return q(this.Ne.capture_heatmaps)?q(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;$v.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Aa]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ca(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(){E&&F&&(this.Po=this.cr.bind(this),Ee(E,xs,this.Po),this.Ro=t=>this.ke(t||E?.event),Ee(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||E?.event),Ee(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Iu(this.instance,Vm,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),Ee(F,Ss,this.Oo),this.vo=!0)}Eo(){var t;E&&F&&(this.Po&&E.removeEventListener(xs,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.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&&En(u)&&!at(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:E)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=Xf(u)}return!1})(Ko(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"),!pu(t.target)&&ca(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&yu(Ko(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!pu(t.target)&&ca(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(E){var e=this.Ne.disable_capture_url_hashes?bn(E.location.href):E.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[..._i,...n||[]]:[],r=fr(e,i,hr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!sn(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Iu,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},q(n?.name)||q(n?.value))Rn.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=Re(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 Rn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=O.__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 Rn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[$a]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=ve(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return q(n)?((e=this._instance.persistence)==null?void 0:e.props[Ma])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(ve(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=ve(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=ve(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=ve(this.Wo)&&Re(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:qu;return t>0&&6e4>=t?qu:t}get isEnabled(){var t=be?.protocol;if(t!=="http:"&&t!=="https:")return Rn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=ve(this.Wo)?this.Wo.web_vitals:xt(this.Wo)?this.Wo:void 0;return xt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Rn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=ve(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=ve(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[$a]:n}),this._instance.persistence.register({[Ma]: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=O.__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?Rn.error("failed to load script",r):t()}))}Bo(t){var e=t||E?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?bn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[..._i,...i||[]]:[];return fr(n,r,hr)}Rn.error("Could not determine current URL")}}},Wv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(E&&this.isEnabled&&(n=O.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=O.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=O.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=O.__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){Di.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Fa]),this.Jo=new Ug(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:Di})),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 ve(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?(Di.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=O.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=O.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Di.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({[Fa]: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)?Di.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 rm([new fm,new bm,new pm,new hm,new _m,new ym,new mm,new wm],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var p=uu.test(f)?f.replace(uu,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((x=>{return k({},x,{filename:x.filename||(b=v,b[b.length-1]||{}).filename,function:x.function||vi});var b}))})(u)}})("web:javascript",lm,dm)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(Ra))!==null&&e!==void 0?e:[],this.el=ys(this.il()),this.rl=new Sm(this.el)}onConfigChange(){this.el=ys(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,[Ta]:o})}}}get nl(){var t,e=!!this._instance.get_property(Ta),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 Pt.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)=>Em.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&&Pt.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[ms]:t,[vs]:new Date().toISOString()},i))}catch(s){Pt.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 Pt.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 Pt.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 Pt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&q(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 Pt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Pt.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 Pt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[ms]:t,[vs]:new Date().toISOString()})}sl(t){return ve(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=Ph[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 Pt.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!q(t)&&U(t)}}},qv=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({[Dl]:!!e.productTours}),!ua(this._instance))return!this.vl&&q((n=this.Mr)==null?void 0:n.props[Ki])||Vr.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&&ua(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=O.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=O.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Vr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=O.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=O.__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[Ki];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(ua(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||Vr.warn(o):Vr.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({[Ki]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){q(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(Ki)}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)}}},Qs),zv={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=O._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var p=t.$set_once,h=t.$set;return{event:k({},Xd(t,Mv),{properties:k({},t.properties,h?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ct.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)||(Ct.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,p=(m,v,x)=>{if(m!=null&&m[v]){var b=m[v];m[v]=x(b),c.push((()=>{m[v]=b}))}},h=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:h(v))).filter((v=>!rt(v)));return p(u,"appendChild",(m=>function(v){var x=h(v);return x?m.call(this,x):v})),p(u,"insertBefore",(m=>function(v,x){var b=h(v);return b?m.call(this,b,x):v})),p(u,"replaceChild",(m=>function(v,x){var b=h(v);return b?m.call(this,b,x):x})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var x=arguments.length,b=new Array(x),_=0;x>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),p(m,"prepend",(v=>function(){for(var x=arguments.length,b=new Array(x),_=0;x>_;_++)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=>{p(m,"before",(v=>function(){for(var x=arguments.length,b=new Array(x),_=0;x>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),p(m,"after",(v=>function(){for(var x=arguments.length,b=new Array(x),_=0;x>_;_++)b[_]=arguments[_];return v.apply(this,g(b))})),p(m,"replaceWith",(v=>function(){for(var x=arguments.length,b=new Array(x),_=0;x>_;_++)b[_]=arguments[_];var S=g(b);return b.length&&!S.length?void 0:v.apply(this,S)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,x){var b=h(x);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&&(Ct.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,Ct.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){Ct.error(Gu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){Ct.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){Ct.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 Ct.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;O["__$$ph_site_app_"+u]=r._instance,(l=O.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return Ct.error(Gu+u,d)}))};for(var a of s.siteApps)o()}else Ct.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Vv={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=O.__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=O.__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=O.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=O.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Tv.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()}}},Gv=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 ee.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(q(e))return ee.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,ee.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)ee.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)ee.info(Ku);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())ee.info("Not loading surveys in cookieless mode without consent.");else{var t=O?.__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 ee.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Ov(this._instance),ee.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){ee.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 ee.info(Ku),t([]);var n,i=this._instance.get_property(Na);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?ee.error(a):r.error||ee.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&(Fh(p)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[Na]:c,[ws]: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(ws);return Re(t)&&Date.now()-t>3e5}Bl(){return Re(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Th(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){ee.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!q(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);ee.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(q(this._surveyManager))return{eligible:!1,reason:Gr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(q(this._surveyManager))return{eligible:!1,reason:Gr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(q(this._surveyManager))return ee.warn("init was not called"),{visible:!1,disabledReason:Gr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return q(this._surveyManager)?(ee.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Gr})):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(q(this._surveyManager))ee.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(_v.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(ee.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;ee.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),ee.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);ee.warn("Survey element not found")}else ee.warn("Surveys of type "+r.type+" cannot be rendered in the app");else ee.warn("Survey not found")}}displaySurvey(t,e){var n;if(q(this._surveyManager))ee.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!==Va.Popover&&e.initialResponses&&ee.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 ee.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==Va.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else ee.warn("Survey not found")}}cancelPendingSurvey(t){q(this._surveyManager)?ee.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Qs),Kv={toolbar:class{constructor(t){this.instance=t}Wl(t){O.ph_toolbar_state=t}Vl(){var t;return(t=O.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),Wa(this.instance.config)||!E||!F)return!1;t=t??E.location,n=n??E.history;try{if(!e){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}e=E?.localStorage}var i,r=Bv||Ps(t.hash,"__posthog")||Ps(t.hash,"state"),s=r?fu((()=>JSON.parse(atob(decodeURIComponent(r)))))||fu((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(Yu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=O.ph_load_toolbar||O.ph_load_editor;!q(e)&&ze(e)?e(t,this.instance):Ju.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(Gf));if(!E||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(E.localStorage.setItem(Yu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=O.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Ju.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),Ee(E,"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)}}},Yv=k({experiments:Ue},Qs),Jv={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;q(e)||(xt(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||Wa(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=O?.__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 gt.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,gt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else gt.error("Cannot complete initialization: remote config is null")}eu(t,e){gt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():gt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!rt(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Wa(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?q(this.Jl)||!this.Jl.token?"missing_token":O!=null&&O.__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 le((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(gt.warn($n),null)}))()}getMessages(t,e){var n=this;return le((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(gt.warn($n),null)}))()}markAsRead(t){var e=this;return le((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(gt.warn($n),null)}))()}getTickets(t){var e=this;return le((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(gt.warn($n),null)}))()}requestRestoreLink(t){var e=this;return le((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(gt.warn($n),null)}))()}restoreFromToken(t){var e=this;return le((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(gt.warn($n),null)}))()}restoreFromUrlToken(){var t=this;return le((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(gt.warn($n),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()}}},Zv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ye("[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(rd)||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),E&&Ee(E,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,x=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:(p=b?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=b?.["deployment.environment"])!==null&&h!==void 0?h:o?.environment,resourceAttributes:b,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:x,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 tm(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},id);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;!q(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){rd(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=O?.__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===Yt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Yt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>se.LIB_NAME,getLibraryVersion:()=>se.LIB_VERSION}}Ot(t){return new Promise((e=>{if(sh(this.Sa,3))e({kind:"fatal",error:fa(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:fa(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:fa(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=oh(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,se.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,id,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ff(s,Af(n,se.LIB_NAME,se.LIB_VERSION),i,se.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,q(r)||(e.sessionStartTimestamp=r),q(s)||(e.lastActivityTimestamp=s)}if(O!=null&&(t=O.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?bn(O.location.href):O.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Xv={metrics:class{constructor(t){this.rt=ye("[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 nm(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:()=>se.LIB_NAME,getLibraryVersion:()=>se.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)}}},Qv=k({},Qs,Uv,Hv,Wv,qv,zv,Gv,Vv,Kv,Yv,Jv,Zv,Xv);st.__defaultExtensionClasses=k({},Qv);var Nh=(function(){se.SDK_DIST_CHANNEL="npm";var t=rr[oi]=new st;return(function(){function e(){e.done||(e.done=!0,Mh=!1,oe(rr,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():Ee(F,"DOMContentLoaded",e,{capture:!1}):E&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ey=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let tt=null,$s=null,Oh="";const el=new Map;function Bh(t){return[...t.querySelectorAll(ey)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function ty(t){for(const n of document.body.children)n===t||n.tagName==="SCRIPT"||(el.set(n,{inert:n.inert,ariaHidden:n.getAttribute("aria-hidden")}),n.inert=!0,n.setAttribute("aria-hidden","true"));const e=document.activeElement;e&&e!==document.body&&!t.contains(e)&&e.blur()}function ny(){for(const[t,e]of el)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);el.clear()}function Dh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Je(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=tt&&tt!==n?tt:null,r=$s;if(i&&Ze(i,{restoreFocus:!1,force:!0}),tt!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),$s=a,Oh=document.body.style.overflow,ty(n),document.body.style.overflow="hidden"}tt=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(tt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Bh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function Ze(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Dh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==tt)return!0;ny(),document.body.style.overflow=Oh,tt=null;const i=$s;return $s=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function iy(){return!!tt}function sd(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 ry(t){if(!Dh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ze(t)}document.addEventListener("keydown",t=>{if(!tt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),ry(tt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Bh(tt);if(!e.length){t.preventDefault(),(tt.querySelector(".modal-content")||tt).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 sy(){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 Yl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),oy=Object.freeze({free:2,professional:50,power:2e3}),ay="(contact us)",ly=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 ${ay}`])}),jh="CodeFile",Uh="GeneratedCode",cy={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function yn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tl(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function uy(t={},e=0){const n=tl(t.artifactType||t.type||jh),i=tl(t.artifactName||t.name||t.fileName||`${Uh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Hh(t={},e=0){const n=yn(t),i=n.artifactType||n.type||jh,r=n.artifactName||n.name||Uh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:tl(n.id)||uy({...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:Wh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:qh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:yn(n.metadata),codeType:n.codeType||cy[i]||"O"}}function Wh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=yn(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(yn(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function qh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=yn(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 nl(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 pr(t,e={}){const n=[],i=typeof t=="string"?nl(t):t,s=yn(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)=>Hh(d,f)),l=new Map(o.map((d,f)=>[yn(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=qh(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:Wh(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:yn(s.metadata)}}function bi(t){return pr(t).artifacts[0]||Hh()}function ln(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Ei(t){return JSON.stringify(t,null,2)}function dy(t){return Ei({task:"architect",userRequest:String(t??"")})}function fy(t){const e=ln(t);return e&&typeof e=="object"&&typeof e.task=="string"?Ei(e):Ei({task:"generate_bundle",bundleSpec:e})}function hy(t){return Ei({task:"review_bundle",generatedBundle:ln(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 Jl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=ln(e)),n}function py({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return Ei({task:"regenerate_artifact",artifactId:i,bundleSpec:ln(t),artifactBundle:ln(e),bundleReview:ln(n),userFeedback:String(r)})}function zh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Ei({task:"regenerate_bundle",bundleSpec:ln(t),artifactBundle:ln(e),bundleReview:ln(n),userFeedback:String(i??"")})}const od={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"},gy=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function lt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function my(t){return lt(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||lt(t.filterSummary)||lt(t.filterResults):!1}function Vh(t,e=0){if(!lt(t)||e>3)return null;if(my(t))return t;for(const n of gy){const i=t[n];if(lt(i)){const r=Vh(i,e+1);if(r)return r}}return null}function Ms(t){return Array.isArray(t)?t.some(Ms):lt(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(Ms):!1}function il(t){return Array.isArray(t)?t.some(il):lt(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(il):!1}function Gh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function vy(t,e){if(lt(t))for(const[n,i]of Object.entries(t)){if(!lt(i))continue;const r=lt(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>lt(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Gh(n))}}function yy(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>lt(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!Ms(r))continue;const s=Gh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=lt(o)?Object.entries(o).filter(([,l])=>Ms(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function _y(t){return od[t]?od[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ad(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 wy(t){const e=Vh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);vy(e.filterSummary,n),yy(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=il(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function by(t,e){const n=wy(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(_y))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ad(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 ${ad(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 Ey(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ld(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Ey(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 Zl(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 cd(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 Sy(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=Zl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await cd(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await cd(c)),n[o]=u,a.type==="F"){const d=ld(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const r=new Set(ld(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 xy=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),ud={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Iy=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),ky=["Struct","Record"],Cy=[{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=>ha(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=>ha(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 { - const _P({required this.t}); - final double t; -} -class W extends StatefulWidget { - const W({this.value = 1.0}); - final double value; -}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>ha(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { - const W({this.textStyle}); - final TextStyle? textStyle; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { - const W({this.width}); - final double? width; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function At(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function gr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Ay(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;rFy(t).usable);function Ty(t=""){const e=gr(t);return Ry.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function $y(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=Py(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rdd(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function eo(t=""){return Array.from(gr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function My(t="",e=""){return Xl(t,e)?.returnType||null}function fd(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 Ly(t,e){const n=eo(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>fd(l)===r)||n.length>1)return null;const[o]=n,a=`${fd(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 Ql(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Ny(t,e,n=""){const i=Xl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Zl(r,"A");if(s===i)return null;const o=`${Ql(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 Oy(t="",e=""){return Xl(t,e)!==null}function By(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Iy.has(i)?!1:!ky.some(s=>i.endsWith(s))||e.has(i))}function Dy(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=My(t,e),r=By(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 jy(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(xy.has(t.artifactType)||n.push(At(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(At(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(At(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(At(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ty(r))n.push(At(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Oy(r,t.artifactName)&&n.push(At(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(eo(r)),o=Dy(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(At(t,"error",o));const a=Ny(i,r,t.artifactName);a&&n.push(At(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(At(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Ly(i,r);s&&n.push(At(t,"info",s))}return n}function Uy(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>eo(s.code||""))),i=e.flatMap(s=>jy(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:ud[s.artifactType]||ud.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const hd="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function pd(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Hy(t=""){const e=t.indexOf(hd);return e===-1?t:t.slice(e+hd.length).replace(/^\s*\n/,"")}const Wy=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function qy(t="",e=""){const n=Hy(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(pd).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=pd(s);return o===null||!i.has(o)?!0:!Wy.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const zy=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","flutter_web_plugins","integration_test","sky_engine"]);function Vy(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 Qy(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(p=>p.id)).map(p=>n.find(h=>h.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(p=>{const h=Xy(p),g=p.fixedCode||p.code||"",m=p.codeType||Jy[p.artifactType]||ot.OTHER;g.trim()||s.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:h,content:g,type:m,path:p.deployPath||Zy(h,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,h)=>({entry:p,index:h})).filter(({entry:p})=>p.type===ot.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],h={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} -${m.content}`).join(` - -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=h}const u={...gd(t?.dependencies),...r.reduce((p,h)=>({...p,...gd(h.dependencies)}),{})},c={};r.forEach(p=>{ec(p.fixedCode||p.code||"").forEach(h=>{h in u||(c[h]="")})});const d={...c,...u},f=Qy(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=new Map){const n=[],i=[];for(const r of t)(e.has(r.path)?n:i).push(r);return{landed:n,notLanded:i}}function rl(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}function o_(t){return t?t.notLanded.length===0&&t.landed.length>0:!1}function a_(t,e,n){const i=rl(t,e),r=new Map(i);return r.set("pubspec.yaml",{content:n,type:"D",path:"pubspec.yaml"}),r}const md={pass:0,warning:1,fail:2},l_=["manualActions"];function ft(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function nn(...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 Rt(t){return t==null?[]:Array.isArray(t)?t:[t]}function c_(t){const e=ft(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return vd(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?vd(Number(i[1])):null}function vd(t){return t>=0&&t<=100?t:null}function vt(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function tc(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 sl(...t){return t.filter(Boolean).reduce((e,n)=>md[n]>md[e]?n:e,"pass")}function Zh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ft(t),r=nn(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:tc(i.severity||i.status||i.level)||e,message:r,suggestion:nn(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function ol(t,e="review"){const n=ft(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>Rt(n[r]).map(o=>Zh(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=ft(t),r=nn(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:nn(i.detail,i.instructions,i.description),location:nn(i.location,i.flutterFlowPath,i.path),timing:nn(i.timing,i.phase)||"unspecified",artifactId:n,source:nn(i.source)||"Code Review"}:null}function al(t,e=null){const n=ft(t);return l_.flatMap(i=>Rt(n[i])).map((i,r)=>u_(i,r,e)).filter(Boolean)}function d_(t){let e=typeof t=="string"?nl(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ft(e);typeof n.content=="string"&&(e=nl(n.content)||e);const i=ft(e),r=ft(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(vt);return t.find(i=>{const r=ft(i);return[r.id,r.fileName,r.artifactName,r.name].map(vt).some(s=>s&&n.includes(s))})||null}function h_(t,e){return Rt(t?.metadata?.compatibility?.deployHints).find(r=>vt(r?.artifactId)===vt(e.id)||vt(r?.fileName)===vt(e.fileName))?.pathHint||""}function p_(t,e){return Rt(t?.relationships).filter(n=>vt(n?.from)===vt(e.id)||vt(n?.to)===vt(e.id))}function g_(t,e){return Rt(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||vt(n.artifactId)===vt(e.id)).map(n=>Zh(n,"warning","Compatibility check")).filter(Boolean)}function m_(t,e,n,i){const r=f_(e,n),s=ft(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...ol(s),...g_(t,n)],l=al(s,n.id),u=tc(s.status||s.verdict||s.outcome||s.result),c=a.length?sl(...a.map(f=>f.severity)):null,d=sl(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?nn(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 y_({bundle:t,reviewResult:e}){const n=ft(t),i=Rt(n.artifacts),{root:r,rawText:s}=d_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ft).find(b=>Object.keys(b).length)||{},a=Rt(r.artifacts||r.files||r.reviews),l=i.map((b,_)=>m_(n,a,b,_)),u=ol(r),d=[...ol(o),...u],f=[...al(o),...al(r),...l.flatMap(b=>b.manualSteps)].filter((b,_,S)=>S.findIndex(I=>I.title===b.title&&I.artifactId===b.artifactId)===_),p=tc(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=sl(p,...d.map(b=>b.severity),...l.map(b=>b.status)),g=o.score??r.score??r.overallScore??s,m=c_(g),v=nn(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:h,score:m,artifactPresentations:l,manualSteps:f}),x=l.reduce((b,_)=>(b[_.status]+=1,b),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:x,reviewCoverage:{reviewed:l.filter(b=>b.reviewComplete).length,total:l.length},deployOrder:Rt(n.deployOrder),relationships:Rt(n.relationships),warnings:Rt(n.warnings),compatibility:ft(n.metadata?.compatibility)}}const __="x-ff-api-key",yd="dr_",w_=/^[A-Za-z0-9_-]{1,120}$/;function b_(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`${yd}${t.randomUUID()}`;if(t&&typeof t.getRandomValues=="function"){const e=t.getRandomValues(new Uint8Array(16));return`${yd}${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}return null}function E_(t){return typeof t=="string"&&w_.test(t)}function S_(t,e){return`${String(t).replace(/\/deployCustomClasses$/,"")}/runStatus/${encodeURIComponent(e)}`}function x_(t){if(!t||typeof t!="object")return null;const{status:e}=t;return e!=="running"&&e!=="done"&&e!=="failed"?null:{status:e,phase:typeof t.phase=="string"?t.phase:"",message:typeof t.message=="string"?t.message:"",error:typeof t.error=="string"?t.error:null,deployed:Array.isArray(t.deployed)?t.deployed:[],dryRun:t.dryRun===!0}}const I_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function k_(t){return!t||!t.status?{definitive:null}:t.status==="done"?{definitive:"success",deployed:Array.isArray(t.deployed)?t.deployed:[]}:t.status==="failed"&&I_.has(t.phase)?{definitive:"failed",error:t.error||"The deploy failed before writing anything to FlutterFlow."}:{definitive:null}}async function C_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,timeoutMs:r=8e3}){if(!E_(e))return null;const s=i||globalThis.fetch;if(!s)return null;const o=new AbortController,a=setTimeout(()=>o.abort(),r);try{const l=await s(S_(t,e),{method:"GET",headers:{[__]:String(n||"")},signal:o.signal});if(!l.ok)return null;const u=await l.json();return x_(u)}catch{return null}finally{clearTimeout(a)}}async function P_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,budgetMs:r=12e3,intervalMs:s=2e3}){const o=Date.now()+r;let a=0;for(;Date.now()=2)return{definitive:null};const u=o-Date.now();if(u<=0)break;await new Promise(c=>setTimeout(c,Math.min(s,u)))}return{definitive:null}}const A_=/^\uFEFF/;function Ui(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function F_(t){const e=String(t??"").replace(A_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ui(n);{const c=ll(e);if(!c.error&&o.every(f=>wd(f,c.commentAndStringRanges)))return Ui(n)}if(r===1){const c=Ui(n.slice(0,s)),d=Ui(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 R_(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 Xh(t){const e=R_(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 Qh(t){return`${Ql(t)}.dart`}function T_(t){return Zl(t,"W")}const _d={"(":")","[":"]","{":"}"},$_={")":"(","]":"[","}":"{"},M_=/[A-Za-z0-9_]/;function ll(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]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!M_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(_d[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if($_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&_d[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function L_(t){return ll(String(t??"")).error}function wd(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 N_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],O_="MAGIC_LINK_SENT",B_="PLUS_ALIAS_REJECTED",D_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",to={allowlistedDomains:N_,successCode:O_,validationCode:B_,messageTemplate:D_},j_=new Set(to.allowlistedDomains),U_=to.successCode,H_=to.validationCode;function no(t){return typeof t=="string"?t.trim():""}function W_(t){const e=no(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 j_.has(r)?i.includes("+"):!1}function q_(t,e){return to.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ep(t){if(!W_(t))return null;const e=no(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return q_(e,i)}function ic(t){return!t||typeof t!="object"||Array.isArray(t)||t.success===!1||t.error?!1:t.code?t.code===U_:t.success===!0||typeof t.message=="string"}function tp(t,e){return t?.code===H_?t.message||ep(e)||"Please enter your primary email address.":ic(t)?`Check your email — we sent a link to ${no(e)}`:t?.message||"Something went wrong. Please try again."}const z_="ccc_auth_session",V_="ccc_subscription",G_=Object.freeze(["hasSeenWalkthrough"]);function K_(t){const e=[];for(const n of G_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function Y_(){return[z_,V_]}function J_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of Y_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function Z_(t){const e=t?.message||t?.error;return typeof e=="string"&&e.trim()?e.trim():"The server could not send the link."}function X_({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());if(!ic(o))throw new Error(Z_(o));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 Q_=/^dependencies\s*:\s*(?:#.*)?$/,e0=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function xr(t){const e=t.match(e0);return e?e[1]??e[2]??e[3]:null}function Ir(t){const e=t.trim();return e===""||e.startsWith("#")}function Sn(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function rc(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;sc&&/\s/.test(s[d-1]);)d-=1}return t[r]=s.slice(0,c)+oc(n)+s.slice(d),!0}return!1}function bd(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?oc(i):">=0.0.0"}`]}function r0(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(ap(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=sc(r);if(l){const u=o.flatMap(([c,d])=>bd(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(...bd(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function s0(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=io(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l),d=c&&!c.isScalar&&c.sourceKey===null&&c.version!==null;if(!c||!c.isScalar&&!d||!String(u||"").trim()){a.push(l);continue}if(d){i0(r,c,String(u).trim())?o.push({name:l,from:c.version,to:u}):a.push(l);continue}const f=" ".repeat(Sn(r[c.lineIndex]));r[c.lineIndex]=`${f}${l}: ${oc(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function cp(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),sc(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),ap(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 o0=">=3.0.0 <4.0.0";function cl(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 a0(t=""){const e=Jh(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Ed(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=cl(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=cl(s.version);continue}i.push(r)}return i}function l0(t){const e=new Set,n=new Set,i={},r={},s=Ed(io(t),i,e),o=Ed(t0(t,"dependency_overrides"),r,n),a=[...s,...o],l=new Set([...Object.keys(i),...e]),{sdk:u}=lp(t);return{sdkConstraint:cl(u)||o0,dependencies:i,dependencyOverrides:r,sdkPackages:[...e].sort(),sdkOverrides:[...n].sort(),availablePackages:l,unrepresentable:a,unrepresentableOverrides:o}}function c0(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 u0(t,e){const{sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o,availablePackages:a,unrepresentable:l,unrepresentableOverrides:u}=l0(e),c={sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o},d=[],f=[],p=[];for(const h of t){const{className:g,content:m}=h,v=ec(m),x=Jh(m).some(S=>S.startsWith("package:"));if(l.length>0&&x){const S=v.filter(R=>l.includes(R));let I;if(S.length>0)I=`${g} was not compiled before deploying: it imports or exports ${S.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`;else{const R=l.filter(P=>!u.includes(P)),w=[R.length>0?`your project's pubspec.yaml declares ${R.join(", ")} from a source that cannot be reproduced outside it`:null,u.length>0?`your project's dependency_overrides redirects ${u.join(", ")} to a source that cannot be reproduced outside it`:null].filter(Boolean).join(", and ");I=`${g} was not compiled before deploying: ${w}, and an entry like that can change what every package depending on it resolves to - including packages this class reaches transitively - so package resolution could not be matched exactly.`}f.push({className:g,reason:I});continue}const{unresolvableImports:b}=a0(m),_=v.filter(S=>!a.has(S));if(b.length>0||_.length>0){f.push({className:g,reason:c0(g,b,_)});continue}d.push({fileName:`${Ql(g)}.dart`,content:m})}return{manifest:c,sources:d,skipped:f,approximate:p}}function Sd(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=up(s);o&&r.push(o)}return{events:r,buffer:i}}function d0(t){const e=up(t);return e?[e]:[]}function up(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 De=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),dp=84e4,fp=1e4;function hp(t){return t?.unconfirmed===!0||t?.outcome===De.UNCONFIRMED?De.UNCONFIRMED:t?.partial===!0||t?.outcome===De.PARTIAL?De.PARTIAL:t?.success===!0?De.COMMITTED:De.FAILED}class Ge extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=De.UNCONFIRMED}}function xd({httpStatus:t}={}){return new Ge(`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 f0(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}if(u.event==="result"){r=u;return}u.event===void 0&&typeof u.success=="boolean"&&(r=u)};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const p=Sd(o,c.decode(f,{stream:!0}));o=p.buffer,p.events.forEach(a)}}else{const u=Sd("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return d0(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 h0=new Set(["connected","workspace_init","workspace_ready","verifying"]);function pp(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?h0.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Id(t){if(t?.finalResultReceived){const e=hp(t);return e===De.FAILED&&!pp(t)?De.UNCONFIRMED:e}return t?.httpRejected&&typeof t.httpStatus=="number"&&t.httpStatus>=400&&t.httpStatus<500?De.FAILED:De.UNCONFIRMED}function p0(){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,p,h,g,m,v;function x(G,z){if(!i)return null;const D=i.createShader(G);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const G=x(i.VERTEX_SHADER,o),z=x(i.FRAGMENT_SHADER,a());if(G&&z&&(l=i.createProgram(),i.attachShader(l,G),i.attachShader(l,z),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),p=i.getUniformLocation(l,"parallax"),h=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function b(G){if(!G)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(G);if(z){let D=z[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const pe=D.getContext("2d");pe.fillStyle="rgb(9, 8, 7)";const Fe=String(pe.fillStyle);pe.fillStyle=G;const Ne=String(pe.fillStyle);if(Ne===Fe)return null;const wt=/^#([0-9a-f]{6})$/i.exec(Ne);if(wt){const bt=wt[1];return[parseInt(bt.slice(0,2),16)/255,parseInt(bt.slice(2,4),16)/255,parseInt(bt.slice(4,6),16)/255]}const qt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Ne);if(qt)return[Number(qt[1])/255,Number(qt[2])/255,Number(qt[3])/255]}catch{}return null}function _(){let G="";try{const z=getComputedStyle(document.documentElement);G=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return b(G)||[.56,.68,.88]}const S=_();let I=1920,R=1080,w=960,P=540,$=960,L=540,M=.66,B=0,J=-1e9,Y=!1,T=0,V=0,re=null,Ie=!1,ce=!1,fe=!1;const Te=64,Q=15.2;let _e=0,we=0;const Le=.0032,ht=0,ne=.56,je=.26,N=.32,$e=.16,ke=.349;let he=ht;function qe(){const G=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!G.width||!z||!D)return;const pe=Math.min(window.devicePixelRatio||1,2),Fe=Math.max(.2,Math.min(2,G.width/z*pe)),Ne=Math.max(2,Math.round(z*Fe)),wt=Math.max(2,Math.round(D*Fe));(Ne!==t.width||wt!==t.height)&&(t.width=Ne,t.height=wt,i&&i.viewport(0,0,Ne,wt)),I=z,R=D,Y||(w=$=I/2,P=L=R/2,Y=!0)}function Zn(G){!l||!Ie||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,R),i.uniform2f(d,w,P),i.uniform1f(f,M),i.uniform1f(p,B),i.uniform2f(v,Math.cos(he),Math.sin(he)),i.uniform1f(h,G),i.uniform3f(g,S[0],S[1],S[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Xe(G,z,D){const pe=Math.max(0,Math.min(1,(D-G)/(z-G)));return pe*pe*(3-2*pe)}function Xn(G){if(!re||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/I;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const pe=Math.min(I,R),Fe=Math.max(64,Math.min(118,pe/10)),Ne=Fe*2.9,wt=2*Ne*Ne,qt=Math.sin(G*.11)*7,bt=Math.cos(G*.09)*7-B,$r=w+qt,Mr=P+bt,Fo=Ne*Math.sqrt(2*Math.log(1/.06)),Fi=Fo+Le*Fo*Fo+Fe,Ig=Math.floor(($r-Fi)/Fe)-1,kg=Math.ceil(($r+Fi)/Fe)+1,Cg=Math.floor((Mr-Fi)/Fe)-1,Pg=Math.ceil((Mr+Fi)/Fe)+1;for(let Ro=Cg;Ro<=Pg;Ro++){const Ag=(Ro+.5)*Fe;for(let To=Ig;To<=kg;To++){const $o=(To+.5)*Fe-$r,Mo=Ag-Mr,Lo=Math.sqrt($o*$o+Mo*Mo)+1e-5;if(Lo>Fi)continue;const Lr=(-1+Math.sqrt(1+4*Le*Lo))/(2*Le),qc=Math.exp(-(Lr*Lr)/wt),zc=Xe(.06,.8,qc)*M*.26;if(zc<.004)continue;const mn=Fe/(1+2*Le*Lr)*.26*(.32+1.1*qc),Vc=Lr/Lo,No=$r+$o*Vc,Oo=Mr+Mo*Vc;No<-mn*1.6||No>I+mn*1.6||Oo<-mn*1.6||Oo>R+mn*1.6||(z.globalAlpha=zc,z.save(),z.translate(No,Oo),z.rotate(he),z.drawImage(re,-mn,-mn,mn*2,mn*2),z.restore())}}z.globalAlpha=1}function Ut(G){if(!ce)return;const z=V?Math.min(.05,(G-V)/1e3):.016;V=G;const pe=G-J>2400?.6:1;M+=(pe-M)*Math.min(1,z*3.2);const Fe=Math.min(.05,z);_e+=(($-w)*Te-_e*Q)*Fe,we+=((L-P)*Te-we*Q)*Fe,w+=_e*Fe,P+=we*Fe,B=(window.scrollY||window.pageYOffset||0)*.55;const Ne=G/1e3,wt=w/(I||1)-.5,qt=P/(R||1)-.5;let bt=wt*(wt>=0?ne:je)+qt*(qt>=0?N:$e);bt>ke?bt=ke:bt<-ke&&(bt=-ke),he=ht+bt-B*6e-4,qe(),i?Zn(Ne):Xn(Ne),T=requestAnimationFrame(Ut)}function Ht(G){if(!ce)return;const z=t.getBoundingClientRect();!z.width||!I||!R||($=(G.clientX-z.left)/z.width*I,L=(G.clientY-z.top)/z.height*R,J=performance.now())}function pt(){ce||Ao||e.matches||n.matches||!fe||document.hidden||(ce=!0,V=0,T=requestAnimationFrame(Ut))}function Wt(){ce=!1,T&&(cancelAnimationFrame(T),T=0),V=0}function Ai(){e.matches?(Wt(),t.classList.remove("is-ready")):fe&&pt()}function Qn(){n.matches?Wt():fe&&pt()}function Uc(){document.hidden?Wt():fe&&pt()}const Hc=new IntersectionObserver(G=>{fe=G[0]?.isIntersecting||!1,fe?pt():Wt()},{threshold:0});Hc.observe(t),window.addEventListener("pointermove",Ht,{passive:!0,capture:!0}),window.addEventListener("resize",qe),e.addEventListener("change",Ai),n.addEventListener("change",Qn),document.addEventListener("visibilitychange",Uc);function xg(){const G=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(G&&window.Path2D){const pe=Math.min(8.533333333333333,8.421052631578947);D.setTransform(pe,0,0,pe,pe+(256-30*pe)/2,-6.4*pe),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(G),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const pe=D.getImageData(0,0,256,256),Fe=pe.data;for(let Ne=3;Ne{G.persisted?Wt():Wc()}),window.addEventListener("pageshow",G=>{G.persisted&&pt()}),{dispose:Wc,isRunning:()=>ce}}const g0=120;function m0(t,e,n){return tn?n:t}function ge(t,e,n){return m0((t-e)/(n-e),0,1)}function v0(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function pa(t){return 1-Math.pow(1-t,3)}function Qe(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 kd(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function ie(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(ge(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=ie(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),h=ie(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Qe}]),d=ie(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Qe},{t:10.6,v:0}]),p=ie(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Qe}]),o=ie(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=ie(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const S=ge(_,.45,2.2);a=S>0?-2.6*(1-kd(S)):0,g=ie(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=ge(_,.67,2.42);f=I>0?-2.6*(1-kd(I)):0,s=1-.05*(Math.sin(ge(_,1.9,2.5)*Math.PI)+Math.sin(ge(_,2.5,3.1)*Math.PI))}else if(t<74){let S=function(P){return[ie(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}]),ie(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=S;const _=t-60,I=1-ge(_,12,14),R=S(ge(_,0,12)),w=S(ge(_-.5,0,12));n=R[0]*I,i=(R[1]+.05*Math.sin(_*7))*I,o=(w[0]-R[0])*.6*I,a=(w[1]-R[1])*.6*I,p=(w[0]-R[0])*30*I,x=ge(_,0,.4)*I}else if(t<85.4){const _=t-74,S=ie(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Qe},{t:11.4,v:0}]);o=S*.5,d=-S*.5,l=ie(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Qe},{t:11.4,v:0}]),p=-l*.7,a=ie(_,[{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,S=ge(_,0,5.6),I=ge(_,5.6,7.6),R=.72*Math.min(1,_/.6)*(1-I);d=Math.cos(S*Math.PI*2)*R,f=Math.sin(S*Math.PI*2)*R*.55,p=S*360*(1-I);const w=ie(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:pa},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*w,d+=.16*w,l=-6*w,p+=6*w,s=1+.05*w,m=1+.9*w}else if(t<108.6){const _=t-96.4,S=ge(_,9.6,12.2);n=ie(_,[{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-S),i=-.35*Math.abs(Math.sin(ge(_,0,9.6)*Math.PI*3))*(1-S);const I=Math.sin(_*6.2)*(1-S);u=1+.12*I,h=1-.12*I,l=I*8,p=-I*8,o=.06*I,d=-.06*I,x=ge(_,0,.4)*(1-S)}else{const _=t-108.6,S=Math.sin(ge(_,0,8)*Math.PI),I=1-ge(_,8,11.4);s=1+.04*S*I,i=-.1*S*I,r=2*S*I,m=1+.5*Math.sin(ge(_,0,6)*Math.PI),v=1+.1*Math.sin(ge(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=x,e}function y0(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=g0;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function p(T){const V=Math.min(1,Math.max(0,T.x))*c,re=T.y*d;n.style.transform="translate3d("+V.toFixed(2)+"px,"+re.toFixed(2)+"px,0) rotate("+T.rot.toFixed(2)+"deg) scale("+T.scale.toFixed(3)+")",i.style.transform="translate3d("+(T.ax*u).toFixed(2)+"px,"+(T.ay*u).toFixed(2)+"px,0) rotate("+T.ar.toFixed(2)+"deg) scale("+T.asc.toFixed(3)+")",i.style.opacity=T.afade.toFixed(3),r.style.transform="translate3d("+(T.bx*u).toFixed(2)+"px,"+(T.by*u).toFixed(2)+"px,0) rotate("+T.br.toFixed(2)+"deg) scale("+T.bsc.toFixed(3)+")",r.style.opacity=T.bfade.toFixed(3),s.style.transform="scale("+T.hsc.toFixed(3)+")",s.style.opacity=(.09*T.hfade).toFixed(3),o.style.transform="translateX("+V.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(T.x)).toFixed(3)+")",o.style.opacity=(T.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,x=!1,b=!1,_=0;function S(){return b||a.matches||document.hidden||!e.offsetParent?!1:x}function I(T){if(!v)return;if(m=requestAnimationFrame(I),!S()){w();return}const V=g?(T-g)/1e3:0;g=T,h=(h+Math.min(V,.1))%l,_+=1,p(Hi(h))}function R(){v||b||S()&&(v=!0,g=0,m=requestAnimationFrame(I))}function w(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){S()?R():w()}function $(){a.matches?(w(),p(Hi(0))):P()}function L(){f(),v&&p(Hi(h))}function M(){g=0,P()}const B=new IntersectionObserver(T=>{x=T[0]?T[0].isIntersecting:!1,P()},{threshold:0});B.observe(e),window.addEventListener("resize",L),a.addEventListener("change",$),document.addEventListener("visibilitychange",M);function J(){b||(b=!0,w(),B.disconnect(),window.removeEventListener("resize",L),a.removeEventListener("change",$),document.removeEventListener("visibilitychange",M))}window.addEventListener("pagehide",T=>{T.persisted?w():J()}),window.addEventListener("pageshow",T=>{T.persisted&&P()});function Y(T){h=(T%l+l)%l,p(Hi(h))}return f(),p(Hi(0)),P(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:Y,dispose:J}}const _0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function cn(t){const e=String(t||"").trim().match(_0);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function w0(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 E0(t){const e=cn(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ac(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 cn(o)?{min:o,minInclusive:!0,max:E0(o),maxInclusive:!1}:null}if(cn(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(!cn(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Cd(t,e){const n=ac(t);if(!n||!cn(e))return!1;if(n.min!==null){const i=Ls(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=Ls(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function S0(t,e){const n=ac(t);if(!n||!cn(e))return!1;if(n.max===null)return!0;const i=Ls(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ri(t){const e=ac(t);return e?e.min:null}const x0="https://pub.dev/api/packages/",I0=8e3;function k0(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||b0(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Cd(l.sdk,n)||i&&l.flutter&&!Cd(l.flutter,i)||(!s||Ls(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function C0(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${x0}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(I0)});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=k0(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 P0(t,e={}){const n=await Promise.all(t.map(i=>C0(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function A0(t,e={},n={}){const{resolveVersions:i=P0}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=lp(t),o={dartSdkFloor:ri(s.sdk),flutterSdkFloor:ri(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=io(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(zy.has(d)?c:u).push(d);continue}const h=ri(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:d,constraint:p.constraint});continue}if(S0(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(ri(h)){a.additions[f]=`^${ri(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${ri(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const F0={"&":"&","<":"<",">":">",'"':""","'":"'"};function un(t){return String(t??"").replace(/[&<>"']/g,e=>F0[e])}function W(t){return t?un(t).replace(/\n/g,"
"):""}function an(t){return un(t).replace(/\r?\n/g," ")}function ro(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 mp(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 R0(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 T0(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 $0(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 Si(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 Pd(t){return t=un(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 vp(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=Si(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 un(i)}}}function so(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=$0(o),u=vp(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+=`
-

- ${R0(l)} - ${un(l)} -

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

- ${T0(l)} - ${un(l)} -

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

${Pd(a)}

`)}return i+="
",` -
-
-
- Live Audit Report -
- ${i} -
- `}const M0=[[/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"]],L0=220,N0=6,O0=5200,B0=73,D0=1600,j0=35,ga=new WeakMap;function Ad(t,e){return!!(t&&t.trim())&&!e}function U0(t,e=""){if(typeof t!="string"||!t||t===e||t.trim().lengthi.test(t));return n?n[1]:null}function H0(){let t="",e="";return{get active(){return t},resolve(n){return t=U0(n,e)??"",t},dismiss(){t=""},accept(n){if(!t)return null;const i=n+t;return e=i,t="",i}}}function W0({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=H0();let p=!1,h=!1,g=!1,m=!1,v=!1,x=null,b=null,_=null;const S=n.dataset.demoPrompt||"";function I(){return h||g||m||v}function R(){i.disabled=!Ad(n.value,I())}function w(){r&&(r.textContent=n.value)}function P(){s&&(s.textContent=""),w(),e.classList.remove("has-suggest"),o&&(o.hidden=!0,o.tabIndex=-1),a&&(a.textContent="")}function $(N){s&&(s.textContent=N),w(),e.classList.add("has-suggest"),o&&(o.hidden=!1,o.tabIndex=0,o.setAttribute("aria-label","Accept suggestion: "+N.trim())),a&&(a.textContent="Suggestion: "+N+". Press Tab to accept.")}function L(){f.dismiss(),P()}function M(){if(p||h)return;const N=f.resolve(n.value);N&&$(N)}function B(){clearTimeout(x),!p&&(x=setTimeout(M,L0))}function J(){const N=f.accept(n.value);return N===null?!1:(n.value=N,P(),R(),!0)}function Y(N){h=N,e.classList.toggle("is-busy",N),i.classList.toggle("is-busy",N),i.setAttribute("aria-label",N?"Generating":"Generate"),n.readOnly=N,l.forEach($e=>{$e.disabled=N}),u&&(u.disabled=N),c&&(c.disabled=N),R()}async function T(){if(Ad(n.value,I())){L(),Y(!0);try{await t()}finally{Y(!1)}}}function V(){m&&(m=!1,_&&(clearTimeout(_),_=null),e.classList.remove("is-demo-typing"),n.placeholder="Describe the widget or action you need",R())}function re(){if(d.matches||!S.trim())return;const N=window.location.hash.replace(/^#/,"");if(N&&N!=="home")return;m=!0,n.placeholder="",n.value="",w(),R(),e.classList.add("is-demo-typing");let $e=0;const ke=()=>{n.value=S.slice(0,$e),w()},he=()=>{m&&($e-=1,ke(),$e>0?_=setTimeout(he,j0):V())},qe=()=>{m&&($e+=1,ke(),_=$eN.classList.contains("is-active"))?.dataset.prompt||n.value,w(),fe())}function Q(){l.forEach(N=>{N.classList.remove("is-active"),N.setAttribute("aria-pressed","false")})}function _e(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function we(N){const $e=N.dataset.prompt||"";if(V(),fe(),clearTimeout(x),x=null,L(),l.forEach(he=>{const qe=he===N;he.classList.toggle("is-active",qe),he.setAttribute("aria-pressed",String(qe))}),d.matches||!$e){n.value=$e,w(),R(),_e();return}n.value="",w(),g=!0,R(),e.classList.add("is-demo-typing");let ke=0;b=setInterval(()=>{ke+=1,n.value=$e.slice(0,ke),w(),ke>=$e.length?(fe(),_e()):R()},22)}l.forEach(N=>{N.setAttribute("aria-pressed","false"),N.addEventListener("click",()=>we(N))}),n.addEventListener("keydown",N=>{if((m||g)&&N.key==="Enter"&&!N.shiftKey&&!N.isComposing&&!p){N.preventDefault();return}Ie(),Te(),N.key==="Tab"&&!N.shiftKey&&f.active?(N.preventDefault(),J()):N.key==="Escape"?(clearTimeout(x),x=null,L()):N.key==="Enter"&&!N.shiftKey&&!N.isComposing&&!p&&(N.preventDefault(),T())}),n.addEventListener("beforeinput",()=>Ie()),n.addEventListener("input",()=>{V(),fe(),Q(),L(),R(),B()}),n.addEventListener("compositionstart",()=>{p=!0}),n.addEventListener("compositionend",()=>{p=!1,L(),R(),B()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),o&&o.addEventListener("click",()=>{J(),n.focus({preventScroll:!0})}),i.addEventListener("click",T),n.addEventListener("pointerdown",()=>{Ie(),Te(),Q()}),n.addEventListener("focus",()=>Ie());const Le=ga.get(e);Le&&Le.mql.removeEventListener("change",Le.handler),d.addEventListener("change",ce),ga.set(e,{mql:d,handler:ce});function ht(){ne(),d.removeEventListener("change",ce),ga.delete(e),document.removeEventListener("visibilitychange",je)}function ne(){Ie(),Te(),clearTimeout(x)}function je(){document.hidden&&ne()}return document.addEventListener("visibilitychange",je),w(),R(),re(),{setAttachmentsPending(N){v=!!N,R()},dispose:ht,cancelTyping:ne}}const mr=window.matchMedia("(prefers-reduced-motion: reduce)");let fi=null,Zt=null;const Ns=new Map;function yp(){for(const[t,e]of Ns)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Ns.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Gn(){if(yp(),fi){const t=fi;fi=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Zt&&(Zt.animation.cancel(),Zt.hero.classList.remove("is-exiting"),Zt.hero.style.cssText=Zt.style,Zt=null)}function q0(t){return(fi?.ghost||t)?.getBoundingClientRect()}function z0(t){yp(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",mr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Ns.delete(e))}Ns.set(e,i),e.addEventListener("animationend",i)})}function V0(t,e){if(!t||!e||mr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Zt={hero:t,animation:i,style:n},i.onfinish=()=>{Zt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Zt=null)}}function _p(t,e,n,{results:i=!1}={}){if(Gn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,z0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(mr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};fi=h,p.onfinish=()=>{fi===h&&(Gn(),s())}}window.addEventListener("resize",Gn);window.addEventListener("pagehide",Gn);document.addEventListener("visibilitychange",()=>{document.hidden&&Gn()});mr.addEventListener("change",()=>{mr.matches&&Gn()});const Fd="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",G0="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",K0="https://us.i.posthog.com";Nh.init(G0,{api_host:K0,person_profiles:"identified_only"});function Dn(t,e={}){try{Nh.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const kt="https://4tgke4.buildship.run",wp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Os="ccc_auth_session",ul="ccc_signin_return",Y0=1800*1e3,Rd=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let de=Kn({isResolved:!0}),dl=Promise.resolve();const J0=`${kt}/service/runpipeline`,Z0="bs_user_id",X0="bs_identity_token",Q0=`${kt}/authUserCheck`;let Et={userId:null,token:null,status:null,resolved:!1};const Bs=oy,Ds="ccc_subscription",Td=3,ew=new Set(["active","trialing","paid"]),js="google/gemini-3.7-flash",rs=["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"],tw={"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 rn(t){return tw[t]||t}const nw=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 bp(t){return nw.has(t)}const fl=4,ma=8*1024*1024,iw="https://4tgke4.buildship.run/service/runpipeline-image";let We=[];const xn=[],rw=3e4;let lc=null;function sw(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function ow(t,e){const n=new FormData;return n.append("file",t),(await fetch(iw,{method:"POST",body:n,signal:e})).json()}function aw(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 lw(t,e,n){const i=await sw(t,n);i&&We.includes(e)&&(e.dataUrl=i,_n());let r="";if(i)try{r=aw(await ow(t,n))}catch{r=""}return We.includes(e)?!i||!r?(We.splice(We.indexOf(e),1),_n(),"failed"):(e.url=r,_n(),"added"):"dropped"}function Ep(t){const e=xn.indexOf(t);e>=0&&xn.splice(e,1),xp()}function Sp(t){t.controller.abort(),Ep(t);const e=We.indexOf(t.slot);e>=0&&(We.splice(e,1),_n())}function xp(){lc?.setAttachmentsPending(xn.length>0)}async function cw(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){xe("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>ma);n.length&&xe(`Skipped ${n.length} image(s) over the ${(ma/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ma);if(!i.length)return;const r=fl-We.length,s=i.slice(0,r);if(i.length>r&&xe(`You can attach up to ${fl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};We.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),rw);return d.job=lw(u,c,d.controller.signal),xn.push(d),d.job.finally(()=>{clearTimeout(f),Ep(d)}),d.job});_n(),xp();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&xe(`${l} image(s) could not be uploaded and were not attached.`,"error")}function uw(t){if(y.isRunning){xe("Wait for the current generation to finish before removing images.","info");return}const e=We[t],n=xn.find(i=>i.slot===e);if(n){Sp(n);return}We.splice(t,1),_n()}function _n(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",We.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=We.length>=fl?"Image limit reached":"Add images"))}function cc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=bp(e?.value);t.classList.toggle("hidden",!n),!n&&We.length&&!y.isRunning&&(xn.slice().forEach(Sp),We=[],_n())}const Wn="ccc_usage",Ip="google/gemini-3.7-flash",kp="google/gemini-3.7-flash",Kr="google/gemini-3.7-flash",Ji={professional:11,power:49},hl={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"},ss={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 os={...ss};async function dw(){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(ss),...Object.values(pl),...Object.values(hl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:ss[a]&&(s[a]=ss[a]));os=s}catch{}finally{clearTimeout(e)}}const pl={"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 uc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&pl[s])return pl[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=hl[e];if(n)return n;const i=e.split("_")[0],r=hl[i];return r||"USD"}function Zi(t,e){const n=os[e]??os.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*os.USD)}}const St="ccc_api_key_",Mt="ccc_session_api_key_",Bt="ccc_encryption_key",vr="ccc_encryption_key_scope",fw="ccc_keystore",Us="keys",yr="ccc_encryption_key_version";let gl=null,Hs=null,_r=!1,Ws=!1,$d=!1;class qs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Md(){if($d)return;$d=!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&&xe(t,"warning")}function Cp(){return localStorage.getItem(yr)||""}function ml(){return crypto.randomUUID?.()||Ap(crypto.getRandomValues(new Uint8Array(16)))}function hw(){const t=Cp();if(t)return t;const e=ml();return localStorage.setItem(yr,e),e}function xi(){gl=null,Hs=null,_r=!1,Ws=!1}window.addEventListener("storage",t=>{t.key===yr&&xi()});function pw(){return new Promise((t,e)=>{const n=indexedDB.open(fw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Us)||i.createObjectStore(Us)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function dc(t,e){const n=await pw();return new Promise((i,r)=>{const s=n.transaction(Us,t);let o;try{o=e(s.objectStore(Us))}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 gw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function mw(){const t=await dc("readonly",e=>e.get(Bt));return gw(t)?t:null}async function Pp(t){await dc("readwrite",e=>e.put(t,Bt))}async function vw(){xi();try{await dc("readwrite",t=>t.delete(Bt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function yw(){const t=sessionStorage.getItem(Bt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(e),sessionStorage.removeItem(Bt),sessionStorage.removeItem(vr),localStorage.removeItem(St+"salt"),e}async function Ld(t){const e=sessionStorage.getItem(Bt);if(e)return Ws=sessionStorage.getItem(vr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new qs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Bt,JSON.stringify(i)),sessionStorage.setItem(vr,"session"),Ws=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function _w(t){if(sessionStorage.getItem(vr)==="session"&&sessionStorage.getItem(Bt))return Md(),_r=!0,Ld(t);try{const e=await mw();if(e)return e;const n=await yw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Md(),_r=!0,Ld(t)}}async function fc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=hw();Hs!==n&&xi();const i=gl||_w(e);gl=i,Hs=n;try{return await i}catch(r){throw xi(),r}}async function ww(t){const e=await fc(),n=Hs,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:Ap(o),keyVersion:n,sessionFallback:_r}}async function bw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await fc({allowSessionFallbackCreation:!1});if(_r&&!n&&!Ws)throw new qs;const r=Ew(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 qs)throw i;return console.error("Decryption failed:",i),null}}function Ap(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ae="",Lt="",sr=null,Od=0,ct="not-configured",_t=0,vl=0,yl=0,oo=0,Xt=0,dn=0,nt=null,Nt=null,wr=null;function xw(){return vl+=1,vl}function Iw(){return yl+=1,yl}function br(t,e,n){nt=t?{projectId:t,key:e,generation:n}:null}function _l(t,e=Ae){if(!t)return!1;const n=nt;return n?n.projectId===t&&n.key===e&&n.generation===_t:!1}function hc(t,e,n){if(!Lt||nt&&nt.projectId!==Lt)return;(t||[]).some(r=>(r.id||r.projectId)===Lt)?br(Lt,e,n):nt&&br("",null,null)}function Fp({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==_t?!1:i===Ae||r===Ae}async function pc(){sessionStorage.getItem(Bt)&&await fc(),Ae=await Oe("flutterflow"),Lt=await Oe("flutterflow_project_id"),Rw(),gn(),Ae?yc():(ct="not-configured",It())}let Er=!1;function Rp(){const t=document.getElementById("api-keys-modal");Je(t),vc(),Ae&&co(Ae)}function gc(){Er=!1,Rp()}function kw(){Er=!0;const t=document.getElementById("walkthrough-modal");t&&Ze(t),Rp()}let Bd=!1;function Dd(){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 jd(){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=rn(t.value),r=bp(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.`),cc()}function Tp(){if(Er=!1,Dd(),jd(),!Bd){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")),Dd(),jd()}),Bd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Je("composer-settings-modal",{trigger:t})}function Cw(t){t&&t.target!==t.currentTarget||Ze("composer-settings-modal")}function $p(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ze(e);const n=Er;if(Er=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ct==="connected"&&mc(),Je(i))}}let fn=1;function Mp(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function ao(){const t=Mp();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===fn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&fn<=t&&(fn++,ao())}function Pw(){const t=document.getElementById("walkthrough-modal");t&&(fn=1,ao(),Je(t))}function Aw(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 Lp(){if(H.isVerified&&Dt()&&de.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(fn=1,ao(),Je(e))}}async function vc(){const t=document.getElementById("flutterflow-api-key-input");Ae?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Fw()}function Fw(){Ud("flutterflow","flutterflow-key-status"),Ud("flutterflow_project_id","flutterflow-project-status")}function Ud(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Tt(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 gn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function Rw(){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"?Tt("flutterflow")&&Tt("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Tt("flutterflow")||Tt("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)"):Tt(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)")}),gn()}async function Tw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==Ae,r=e?.value.trim()||"";if(n){const l=await Oe("flutterflow").catch(()=>"");await Nd("flutterflow",n),n!==l&&!r&&as()}const s=n||Ae;if(r){if(!lo(r)){xe("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}_l(r,s)?await Nd("flutterflow_project_id",r):(i?as():nt=null,e.value="",s&&!(Nt&&Nt.key===s&&Nt.generation===_t)&&co(s))}else i&&as();await pc(),n&&await yc(),vc();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),$p()},1e3)}async function $w(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(yr,ml()),xi(),localStorage.removeItem(St+"flutterflow"),localStorage.removeItem(St+"flutterflow_project_id"),sessionStorage.removeItem(Mt+"flutterflow"),sessionStorage.removeItem(Mt+"flutterflow_project_id"),sessionStorage.removeItem(Bt),sessionStorage.removeItem(vr),localStorage.removeItem(St+"salt"),await vw(),localStorage.setItem(yr,ml()),localStorage.removeItem(St+"flutterflow"),localStorage.removeItem(St+"flutterflow_project_id"),sessionStorage.removeItem(Mt+"flutterflow"),sessionStorage.removeItem(Mt+"flutterflow_project_id"),nt=null,Nt=null,wr=null,await pc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),vc()}function lo(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function It(){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=Ye();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Lt||"—"),!e)return;let r,s;if(!Tt("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ct){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 yc(){const t=Iw(),e=++oo,n=_t,i=Ae,r=await Oe("flutterflow"),s=()=>Fp({seq:t,currentSeq:yl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Xt)return null;const o=()=>{dn=Math.max(dn,e)};if(!r||!Tt("flutterflow"))return Xt=e,o(),ct="not-configured",It(),null;ct="validating",It();try{const l=await new kn(r,"","main",Ye()).listProjects();return!s()||e<=Xt?null:(Xt=e,o(),ct=l&&l.length>0?"connected":"no-projects",e>=dn&&hc(l,r,n),It(),l)}catch(a){if(!s()||e<=Xt)return null;Xt=e,o();const l=String(a&&a.message||"");return ct=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",It(),null}}function as(){Lt="",nt=null,localStorage.removeItem(St+"flutterflow_project_id"),sessionStorage.removeItem(Mt+"flutterflow_project_id")}function Mw(){_t+=1,Nt=null,wr=null,as();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Tt("flutterflow")?(ct="validating",co(Ae)):ct="not-configured",It()}function Lw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Nw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Lw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Ow(async n=>{const i=n.target.value.trim();i&&await co(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&Nt?br(n,Nt.key,Nt.generation):br("",null,null)})}function Ow(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function co(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=xw(),r=++oo,s=_t,o=Ae,a=()=>Fp({seq:i,currentSeq:vl,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Xt,u=()=>{Xt=Math.max(Xt,r)};Nt=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===Ae&&(Tt("flutterflow")||t)&&(ct="validating"),It();try{const d=await new kn(t,"","main",Ye()).listProjects();if(!a())return;Nt={key:t,generation:s};const f=t===Ae,p=l()&&f;if(p&&u(),r>dn&&f&&(dn=r,hc(d,t,s)),!d||d.length===0){p&&(ct="no-projects",It()),e.innerHTML='';return}p&&(ct="connected",It()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Lt&&(e.value=Lt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===Ae&&(u(),ct=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",It()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Bw(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 Dw(){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 jw(){y.bundleSpec=pr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function uo(){const t=bi(y.bundleSpec);y.artifactBundle=pr(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=Uy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=bi(y.artifactBundle).id}function fo(){const t=pr(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=pr({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Np(){const t=_c();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _c(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||bi(t)}function wc(){return _c().code||y.step2Result||""}async function Uw(){try{await pc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const ls={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Hw(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 kn{constructor(e,n,i="main",r=ls.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=[ls.production,ls.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(wl(f?d.clone():d,fp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new Ge(`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 Ge(`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 xd({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(Hw(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 wl(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 bc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Ww(t,e=fp){const n=t.clone();let i;try{i=JSON.parse(await wl(t,e))}catch{let o="";try{o=await wl(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new Ge(`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 ho(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 Z={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Op=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Bp=/extends\s+State<\w+>/;function qw(t,e=""){if(t==="pubspec.yaml")return Z.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return Z.OTHER;if(t==="custom_functions.dart")return Z.FUNCTION;if(e){const n=Op.test(e),i=Bp.test(e);if(n||i)return Z.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return Z.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return Z.FUNCTION}return Z.CODE_FILE}function Dp(t,e){switch(e){case Z.ACTION:return`lib/custom_code/actions/${t}`;case Z.WIDGET:return`lib/custom_code/widgets/${t}`;case Z.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case Z.CODE_FILE:return`lib/custom_code/${t}`;case Z.DEPENDENCIES:return"pubspec.yaml";case Z.OTHER:return`lib/custom_code/${t}`;default:return t}}async function po(t,e=new Map){return Sy(t,e)}const bl=new Map,hi=new Map,pi=new Map;function Cr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){bl.delete(Cr(t))}function Xi(t,e,n){const i=Cr(t),r=hi.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?hi.delete(i):hi.set(i,r)}function zw(t,e){Xi(t,e,{uncertain:1})}function Vw(t){const e=Cr(t);pi.set(e,(pi.get(e)??0)+1)}function Hd(t){const e=Cr(t),n=(pi.get(e)??0)-1;n<=0?pi.delete(e):pi.set(e,n)}function bc(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 go(t,e,n=dp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Ww(s)})();return bc(r,n,(s,o)=>{i.stop=!0,Yn(t),Vw(t),r.then(()=>Hd(t),()=>Hd(t)),o(new Ge("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 Gw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=s_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new Ge(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function Ec(t,e,n,i,r="",s=dp){const o=r_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=b_();let l=!1;const u=u0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),Be.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch(Fd,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new Ge("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 f0(m,{onPhase:v=>{p&&Be.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await bc(g,s,(m,v)=>{p=!1,v(new Ge("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(Id(h)===De.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new Ge(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Id(h)===De.UNCONFIRMED){const x=new Ge(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw x.causeDetail=v,x}throw new Error(v)}}catch(m){if(m instanceof Ge){Yn(t),zw(t,o),g?.then(b=>{l||(b?.finalResultReceived&&b.success?Xi(t,o,{uncertain:-1,verified:1}):b?.finalResultReceived&&pp(b)&&Xi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await P_({provisionEndpoint:Fd,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Xi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const x=await Gw(t,o,m);throw o_(x.reconcilePartition)&&(x.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:x.reconcilePartition.landed}),x}throw m}return Yn(t),Xi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Sc(t,e={}){const n=Cr(t);let i=bl.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=cp(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=hi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&hi.delete(n)}!hi.has(n)&&!pi.has(n)&&bl.set(n,i)}const r=await A0(i.pubspecYaml,e),s=s0(i.pubspecYaml,r.overrides),o=r0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Kw(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===Z.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=L_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===Z.WIDGET){const o=Xh(t.content),a=T_(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=`${Qh(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 jp(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=F_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Xh(s)[0],c=u?Qh(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=Z.CODE_FILE;switch(n){case"CustomAction":a=Z.ACTION;break;case"CustomWidget":a=Z.WIDGET;break;case"CustomFunction":a=Z.FUNCTION;break;case"CustomClass":case"CodeFile":a=Z.CODE_FILE;break}let l="";return a===Z.WIDGET?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom widget code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===Z.ACTION?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom action code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===Z.FUNCTION&&(l=`// Automatic FlutterFlow imports -import 'dart:convert'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:timeago/timeago.dart' as timeago; -import '/flutter_flow/lat_lng.dart'; -import '/flutter_flow/place.dart'; -import '/flutter_flow/uploaded_file.dart'; - -`),{content:qy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Yw(t){const e={};for(const n of ec(t))e[n]="";return e}function Jw(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 Zw(t,e,n,i=new Set,r=""){const s=[],o=Op.test(e),a=Bp.test(e);return n===Z.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function mo(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=>eo(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=Zw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=cp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const te={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:te.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=te.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(te).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===te.PREPARING&&(this.startTime=Date.now()),(t===te.SUCCESS||t===te.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(te.ERROR)},setSuccess(t){this.result=t,this.setState(te.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===te.PREPARING||this.currentState===te.VALIDATING||this.currentState===te.PUSHING}};async function xc(t){const e=t!==void 0?t:await Oe("flutterflow"),n=await Oe("flutterflow_project_id");if(!e||!n)return"";if(_l(n,e))return n;const i=++oo,r=_t;let s=!1;try{s=(await new kn(e,"","main",Ye()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==_t||e!==Ae||i<=dn||(dn=i,!s)?"":nt&&nt.projectId!==n&&_l(nt.projectId,e)?nt.projectId:((!nt||nt.projectId===n)&&br(n,e,r),n)}async function Xw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=Z.WIDGET),i==="CustomAction"&&(i=Z.ACTION),i==="CustomFunction"&&(i=Z.FUNCTION),i==="CustomClass"&&(i=Z.CODE_FILE),i==="CodeFile"&&(i=Z.CODE_FILE),K.reset(),K.setState(te.PREPARING);try{const o=await Oe("flutterflow"),a=Ye();let l=await xc(o);if((o!==Ae||a!==Ye())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!lo(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new kn(o,l,"main",a);K.setState(te.VALIDATING);const c=new Map,d=i||qw(e,t),f=Dp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),K.setProgress(0,c.size);const p=mo(c);if(!p.valid)throw new Error(`Validation failed: -${p.errors.join(` -`)}`);const h=await Sc(u,r),g=h.yaml,m=await Ec(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await po(m.syncFileMap,m.remoteFiles),x=new Map(m.syncFileMap);x.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),Be.set("package");const b=await vo(x),_={project_id:l,zipped_custom_code:b,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};K.setState(te.PUSHING),K.setProgress(1,c.size),Yn(u),Be.set("push");const S=await go(u,_);if(S.success)K.setSuccess({fileCount:c.size,projectId:l,warnings:S.errorMap&&S.errorMap.size>0?Array.from(S.errorMap.entries()):[]});else{const I=S.errorMessage||ho(S.responseCode),R=new Error(I);throw R.remoteRefusal=!0,R}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),o instanceof Ge?{success:!1,unconfirmed:!0,error:o.message,state:K.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:K.currentState}}}async function vo(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 Qw(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:Ye(),artifactType:n,artifactName:i,fileName:r};try{K.setState(te.PREPARING);const l=jp(t,{artifactType:n,artifactName:i,fileName:r}),u=Yw(l.content);console.log("Detected dependencies:",u),K.setState(te.VALIDATING);const c=await Oe("flutterflow"),d=Ye(),f=await Oe("flutterflow_project_id");let p=sr||await xc(c);if((c!==Ae||d!==Ye())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Dp(l.fileName,l.codeType),functionName:l.codeType===Z.FUNCTION?i:void 0}),K.setProgress(0,h.size);const g=mo(h);if(!g.valid)throw new Error(`File validation failed: -${g.errors.join(` -`)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),K.setState(te.PUSHING);const m=new kn(c,p,"main",d),v=await Sc(m,u),x=v.yaml,b=await Ec(m,h,v.remoteFiles,`Provision ${i} custom class`,x);o=b.provisionSucceeded===!0;const _=await po(b.syncFileMap,b.remoteFiles),S=new Map(b.syncFileMap);S.set("pubspec.yaml",{content:x,type:Z.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const I=await vo(S),R={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:x,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,h.size),Yn(m),Be.set("push");const w=await go(m,R);if(w.success){const P={...Jw(l,s),projectId:p};return K.setSuccess({...P,fileCount:h.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:b.unverified,approximate:b.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const P=w.errorMessage||ho(w.responseCode),$=new Error(P);throw $.errorMap=w.errorMap,$.remoteRefusal=!0,$}}catch(l){console.error("Commit execution failed:",l),K.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 Ge?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:K.currentState,elapsedTime:K.getElapsedTime(),...l.finishDeploy?{finishDeploy:cg(l.finishDeploy,a,K)}:{}}:o?{success:!1,partial:!0,error:l.message,errorMap:u,targetIdentity:a,state:K.currentState,elapsedTime:K.getElapsedTime()}:{success:!1,error:l.message,errorMap:u,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function eb(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:Ye(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(K.setState(te.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===Z.FUNCTION?I.artifactName:void 0}]));K.setProgress(0,s.size);const o=mo(s);if(!o.valid)throw new Error(`File validation failed: -${o.errors.join(` -`)}`);K.setState(te.VALIDATING);const a=await Oe("flutterflow"),l=Ye(),u=await Oe("flutterflow_project_id");let c=sr||await xc(a);if((a!==Ae||l!==Ye())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,K.setState(te.PUSHING);const d=new kn(a,c,"main",l),f=await Sc(d,t.dependencies),p=f.yaml,h=await Ec(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await po(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:Z.DEPENDENCIES,path:"pubspec.yaml"}),Be.set("package");const v=await vo(m),x={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};K.setProgress(1,s.size),Yn(d),Be.set("push");const b=await go(d,x);if(b.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((R,w)=>R+w.content.length,0),projectId:c};return K.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:f.added,unverified:h.unverified,approximate:h.approximate,warnings:b.errorMap?Array.from(b.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const _=b.errorMessage||ho(b.responseCode),S=new Error(_);throw S.errorMap=b.errorMap,S.remoteRefusal=!0,S}catch(s){console.error("Bundle commit execution failed:",s),K.setError(s);const o=s.errorMap||new Map;return s instanceof Ge?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:K.currentState,elapsedTime:K.getElapsedTime(),...s.finishDeploy?{finishDeploy:cg(s.finishDeploy,r,K)}:{}}:i?{success:!1,partial:!0,error:s.message,errorMap:o,targetIdentity:r,state:K.currentState,elapsedTime:K.getElapsedTime()}:{success:!1,error:s.message,errorMap:o,targetIdentity:r,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function tb(t,e=[]){const n=Jl("architect");try{return await Gs("architect",Ip,dy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function yo(t,e,n=[],i){const r=fy(t),s=Jl("generator",y.bundleSpec);try{return await Gs("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),oE(e,Kr,i);try{return await Gs("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 _o(t,e=null){const n={...Jl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Gs("review",kp,hy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function zs(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=` - - `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` - - `):i.innerHTML=` - - `)}function Me(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),zs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),zs(t,"completed"))}function nb(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 ib(t){ut(parseInt(t.replace("step","")))}function ut(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"),Jn();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 rb(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 El(t){const e=Sl(t);console.log(`Step 1 (Prompt Architect): ${rn(Ip)}`),console.log(e!==t?`Step 2 (Code Generator): ${rn(t)} → ${rn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${rn(t)}`),console.log(`Step 3 (Code Review): ${rn(kp)}`)}function Up(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function sb(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=bi(y.artifactBundle)?.id||null)}const Hp="results-replacement-error";function ob(t,{stage:e=2,runId:n,retry:i}){if(!ae(n))return;const r=document.getElementById(Hp);if(!r)return;const s=mp(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=`${So[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=()=>Ii(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Ic(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Ic(){const t=document.getElementById(Hp);t&&(t.hidden=!0)}function Wp(t,{previous:e,stage:n,runId:i,retry:r}){ae(i)&&(t.isUsageLimit&&wn(),sb(e),Pi(),jt(!0),Tr(),y.resultsViewMode=e.resultsViewMode||"summary",Rr(),Cn(),ob(t,{stage:n,runId:i,retry:r}),gn())}async function qp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=xo();kc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Up();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - - - Refining...`});try{Ic();const r=_c(),s=r.id,o=py({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."});Co({runId:e}),Ot(2,e),ut(2),Me(2,!0);const a=await yo(o,t,[],e);if(!ae(e))return;y.step2Result=a,uo(),hn(2,e);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Me(2,!1),ut(3),Ot(3,e),Me(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!ae(e))return;y.step3Result=c,fo(),hn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=bi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Me(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(r){if(console.error("Refinement failed:",r),!ae(e))return;const s=ro(r,{architect:2,generator:2,review:3});Wp(r,{previous:i,stage:s,runId:e,retry:qp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),ae(e)&&(y.isRunning=!1,gn())}}async function kc(t,e,n){const i=`${kt}/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 ab(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function zp(){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){xe("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=xo();kc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - - Fixing…`);const s=Up();try{Ic();const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});bg(),Co({runId:i}),Ot(2,i),ut(2),Me(2,!0);const a=await yo(o,n,[],i);if(!ae(i))return;y.step2Result=a,uo(),hn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Me(2,!1),ut(3),Ot(3,i),Me(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!ae(i))return;y.step3Result=c,fo(),hn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Me(3,!1),Pi();const f=so(y.step3Result);Tr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!ae(i))return;const a=ro(o,{architect:2,generator:2,review:3});Wp(o,{previous:s,stage:a,runId:i,retry:zp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),ae(i)&&(y.isRunning=!1,gn())}}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=We.slice();if(!t.trim()){xe("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=xo();try{if(await dl,!ae(i)||(xn.length&&await Promise.allSettled(xn.map(b=>b.job)),!ae(i))||!await Rb()||!ae(i)||(await Ib(),!ae(i)))return;const r=Sl(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),Dw(),y.submittedPrompt=t,y.submittedImages=n.filter(b=>b.url),Ys(!0),El(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Co({prompt:t,runId:i}),uE(a,l),ut(1),Ot(1,i),Me(1,!0);const u=y.submittedImages.map(b=>({url:b.url})),c=await tb(t,u);if(!ae(i))return;y.step1Result=c,jw(),hn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=Si(y.step1Result);d.textContent=f,d.dataset.raw=f,Me(1,!1),ut(2),Ot(2,i),Me(2,!0);const p=await yo(y.step1Result,r,u,i);if(!ae(i))return;y.step2Result=p,uo(),hn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=Si(y.step2Result);h.textContent=g,h.dataset.raw=g,Me(2,!1),ut(3),Ot(3,i),Me(3,!0);const m=await _o(y.step2Result,y.step1Result);if(!ae(i))return;y.step3Result=m,fo(),hn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Me(3,!1),Pi();const x=so(y.step3Result);Tr(g,x)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!ae(i))return;const s=ro(r,{architect:1,generator:2,review:3});r.isUsageLimit?wn():Dn("Pipeline Failed",{error:r.message,effectiveModel:Sl(document.getElementById("code-generator-model").value)}),ut(s),Me(s,!1),vg(r,{stage:s,runId:i}),zs(s,"error")}finally{ae(i)&&(y.isRunning=!1,Ys(!1),gn())}}function lb(){const t=document.getElementById("code-generator-model").value,e=[js,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? - -Current: ${t} - -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 cb(){const t=wc();if(!t){xe("No code to commit. Please run the pipeline first.","warning");return}const e=await Oe("flutterflow"),n=await Oe("flutterflow_project_id");if(!e||!n){xe("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}if(y.artifactBundle?.artifacts?.length>1){await ub();return}const{artifactType:i,artifactName:r,fileName:s}=Np(),o=jp(t,{artifactType:i,artifactName:r,fileName:s}),a=Kw(o);if(!a.canProceed){xe(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Ac(o,a,null,null)}async function ub(){const t=await Oe("flutterflow"),e=await Oe("flutterflow_project_id");if(!t||!e){xe("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}const n=e_(y.artifactBundle);if(n.errors.length>0){xe(`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=mo(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){xe(`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};Ac(o,s,n.dependencies,n)}function db(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
-

FlutterFlow Commit Failed

-

${W(t.error)}

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

Errors:

-
    `;for(const[r,s]of e.entries()){const o=nc(s);n+=`
  • - ${W(r)}: ${W(o)} -
  • `}n+="
"}n+="
",n+=`
- -
`;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Vp(t.error,e)}))}async function Vp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=xo(),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[p,h]of e.entries()){const g=nc(h);s+=`File: ${p} -Error: ${g} - -`}else s+=`${t} -`;const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Co({runId:i}),Ot(2,i),ut(2),Me(2,!0);const a=await yo(o,n,[],i);if(!ae(i))return;y.step2Result=a,uo(),hn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Me(2,!1),ut(3),Ot(3,i),Me(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!ae(i))return;y.step3Result=c,fo(),hn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Me(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!ae(i))return;const o=ro(s,{architect:2,generator:2,review:3});s.isUsageLimit&&wn(),ut(o),Me(o,!1),vg(s,{stage:o,runId:i,retry:()=>Vp(t,e)}),zs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),ae(i)&&(y.isRunning=!1,gn())}}async function fb(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Oe("flutterflow"),i=await Oe("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 Gp(t){try{const e=await fetch(`${kt}/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 hb(t){try{const n=await(await fetch(`${kt}/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 pb(t){try{const e=await fetch(`${kt}/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:`${kt}/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:`${kt}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Wd(t,e){const n=Yp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,de=Kn({isLoading:!0}),localStorage.setItem(Os,JSON.stringify({email:t,sessionToken:e})),i&&tg()}function Kp(){H.email=null,H.sessionToken=null,H.isVerified=!1,de=Kn({isResolved:!0}),localStorage.removeItem(Os),localStorage.removeItem(Ds)}function Yp(){try{const t=localStorage.getItem(Os);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(Os),{email:null,sessionToken:null}}}async function gb(){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 hb(e);Wd(n,i),Jp();const r=qd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){qd();const i=n.message||"Sign-in link invalid or expired.";xe(i,"error"),wo(),ci(i,"error")}}else{const{email:n,sessionToken:i}=Yp();if(n&&i){const r=await pb(i);r?Wd(r.email,r.sessionToken):Kp()}}Cc()}function mb(){try{localStorage.setItem(ul,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function qd(){try{const t=localStorage.getItem(ul);if(localStorage.removeItem(ul),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>Y0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function wo(){const t=document.getElementById("signin-modal");if(!t)return;mb(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ci(""),Je(t)}function Jp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ze(e)}function ci(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 vb(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=no(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"),ci("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ep(n);r&&ci(r,"error");try{const s=await Gp(n),o=ic(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ci(tp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ci("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function yb(){H.email=null,H.sessionToken=null,H.isVerified=!1,de=Kn({isResolved:!0}),J_({storage:window.localStorage,onIdentityChanged:Cc,onPlanChanged:Eo})}const _b=X_({sendLink:Gp,getEmail:()=>H.email||"",onState:wb});function wb(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=tp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function bb(){await _b()}function Eb(){const t=K_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";xe(`${e} Your run count, identity and stored keys are kept.`,"info")}function Sb(){const t=document.getElementById("delete-unavailable-modal");t&&Je(t,{trigger:document.activeElement})}function xb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ze(e)}function Cc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Mb(),Eo()}async function Zp(){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(Q0,{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(Et.userId=r.user_id,Et.token=r.identity_token||null,Et.status=r.status,Et.resolved=!0,sessionStorage.setItem(Z0,r.user_id),Et.token&&sessionStorage.setItem(X0,Et.token),r.usage_count!==void 0){const s=In(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),wn()}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 va=null;function Ib(t=5e3){return Et.resolved?Promise.resolve():(va||(va=Zp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([va,new Promise(e=>setTimeout(e,t))]))}function Xp(){const t=In();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function In(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Pr(){const t=Xp();return t.month!==In()?{count:0,month:In()}:t}function kb(){const e={count:Pr().count+1,month:In()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Ci(){return!!de.isLoading}function Dt(){return!!de.isResolved}function Cb(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(Bs,e)?e:null}function Pb(t){return t&&Object.entries(wp).find(([,e])=>e===t)?.[0]||null}function Yr(...t){return t.find(e=>e!=null&&e!=="")}function Ab(...t){return t.find(e=>e&&typeof e=="object")||{}}function Fb(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=Ab(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=Yr(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=Yr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=Cb(Yr(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=ew.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Pb(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Yr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function bo(){return Bs[de.tier]??Bs.free}async function Rb(){if(H.isVerified&&(!Dt()||Ci())&&(await eg({force:!0}),Eo()),H.isVerified&&!Dt())return xe("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Pr(),e=bo();if(t>=e)return Qp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;xe(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function zd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Qp(t,e,n={}){jt(!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){xe(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ii();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=de.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",H.isVerified),u.classList.remove("hidden"),n.openModal&&Ii()}function Sl(t){return de.tier==="free"&&rs.includes(t)?js:t}function Tb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=de.tier,r=!(H.isVerified&&!Dt())&&n==="free";Array.from(e.options).forEach(o=>{const a=rn(o.value),l=rs.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&rs.includes(e.value)&&(e.value=js),e.disabled=!1,Rd.has(e)||(e.addEventListener("change",()=>{Dt()&&de.tier==="free"&&rs.includes(e.value)&&(e.value=js,Ii()),El(e.value),cc()}),Rd.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(),El(e.value)}function Pc(){const t=H.isVerified&&!!H.email,e=t&&Ci(),n=!t||Dt(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Yl,u=n?de.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Xp(),v=m.month===In()?m.count??0:0;g.textContent=`${v} / ${Bs.free} generations used`}}$b()}function $b(){if(!(H.isVerified&&!!H.email))return;const e=Ci(),n=Dt(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=n?de.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const w=Zi(Ji[a]??0,uc());h.textContent=`${w} / 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 w=Date.parse(de.periodEnd||""),P=n&&a!=="free"&&!!de.periodEnd&&!Number.isNaN(w);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const $=new Date(w).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"),x=document.getElementById("acct-left-limit"),b=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),x&&(x.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"),S=document.getElementById("acct-meter-fill"),I=document.getElementById("acct-meter-meta"),R=document.getElementById("acct-meter-track");if(_&&(_.textContent=e?"…":n?String(r):"—"),S){const w=n&&s>0?Math.min(100,Math.round(r/s*100)):0;S.style.width=`${w}%`}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 w=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${w}%`}R&&(e?R.setAttribute("aria-label","Checking usage…"):n?R.setAttribute("aria-label",`${r} of ${s} generations used`):R.setAttribute("aria-label","Usage unavailable")),It()}function wn(){if(Pc(),H.isVerified&&(Ci()||!Dt())){zd();return}const{count:t}=Pr(),e=bo();t>=e&&!y.isRunning&&!iy()?Qp(t,e):zd()}function Mb(){Pc()}async function eg(t={}){const e=t.force===!0;if(!H.isVerified||!H.sessionToken){de=Kn({isResolved:!0});return}de={...de,isLoading:!0,error:null};const n=H.sessionToken,i=localStorage.getItem(Ds);if(!e&&i)try{const{data:r,email:s,ts:o,version:a}=JSON.parse(i);if(a===Td&&s===H.email&&Date.now()-o<300*1e3){de={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",i)}try{const s=await(await fetch(`${kt}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken,user_id:Et.userId})})).json();if(!H.isVerified||H.sessionToken!==n)return;if(s.error){if(["unauthorized","invalid session","expired session"].some(a=>String(s.error).toLowerCase().includes(a))){Kp(),Cc();return}de=Kn({isResolved:!1,error:s.error});return}de=Fb(s),localStorage.setItem(Ds,JSON.stringify({version:Td,data:de,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),de={...de,isLoading:!1,isResolved:!1,error:r.message}}}function tg(){localStorage.removeItem(Ds)}async function Lb(t){if(!H.isVerified||!H.sessionToken){ig(),wo();return}if(!wp[t]){xe("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(`${kt}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:uc()})})).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"),xe("Could not start checkout. Please try again.","error")}}async function Nb(t){if(!H.isVerified||!H.sessionToken){wo();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(`${kt}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),xe("Could not open billing portal. Please try again.","error")}}const Vs=new Set;function ng(){Vs.forEach(t=>t.abort()),Vs.clear()}async function Gs(t,e,n,i={},r=[]){const o=new AbortController;Vs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(J0,{method:"POST",headers:{"Content-Type":"application/json",...Et.token?{Authorization:`Bearer ${Et.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:Et.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(Wn,JSON.stringify({count:d.serverCount,month:In()})),wn());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=by(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=In();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),wn())}else kb(),wn();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Vs.delete(o)}}let xl=!1;function Ob(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),tg(),xl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),xe("Checkout cancelled.","info")),e}function Bb(){if(!xl)return;xl=!1;const t=de.tier!=="free";xe(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Eo(){const t=H.isVerified&&!!H.email,e=de.tier,n=t&&Ci(),i=!t||Dt(),r=document.getElementById("subscription-tier-badge");if(r){const a=Yl,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"),Db(i?e:null),Tb(),cc(),wn(),Eg()}function Db(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 jb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=ly[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 Il(){const t=uc(),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=Zi(Ji.professional,t)),n&&(n.textContent=Zi(Ji.power,t)),i&&(i.textContent=Zi(Ji.professional,t)),r&&(r.textContent=Zi(Ji.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ii(){Il();const t=document.getElementById("pricing-modal");t&&Je(t),dw().then(()=>Il())}function ig(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ze(e)}function xe(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()=>{sy(),tE(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Ub(),window.__heroField=p0(),window.__pipelineLogo=y0(),EE(),lc=W0({onSubmit:Sr}),dl=(async()=>{try{await gb(),Ob(),await eg()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await dl,Bb(),Eo(),Il(),jb(),await Uw(),Nw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=Ye();t.value=n}Lp(),Zp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{fn===2&&e.value.trim().length>0&&(mc(),ao())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");fn===2&&n&&Je(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");fn===2&&i&&setTimeout(()=>{Je(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===te.PREPARING||i===te.VALIDATING||i===te.PUSHING?(dg(),Be.phaseId||Rc(),Gd(i)):(i===te.SUCCESS||i===te.ERROR)&&(Gd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,Tc()},1e3))}),jc()});function Ub(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Hb(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Lp()}let or=null;async function kl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Od,n=++oo,i=()=>e===Od,r=_t;wr=null;const s=await Oe("flutterflow"),o=await Oe("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new kn(s,"","main",Ye()).listProjects();if(!i())return;if(r!==_t||s!==Ae)return kl();if(n>dn&&(dn=n,hc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),wr={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==_t||s!==Ae)return kl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function Wb(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=wr;return!n||n.key!==Ae||n.generation!==_t?null:e}function Ac(t,e,n,i=null){or={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,kl();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 ${un(c)}`:"version resolved from your project";return`
  • • ${un(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=>`
  • • ${un(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&&Je(l)}function rg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ze(e),or=null}function qb(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 sg(t){const e=(m,v)=>{const x=document.getElementById(m);x&&(x.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Je(g)}function og(t){Tc(),db(t);const e=t.remoteRefusal===!0;Fc(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 Fc(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(nc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Je(s),!0}function ag(t){Fc(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 lg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Cl=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Fc(t,{heading:e,title:n,guidance:i})}let Cl=null;function cg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function zb(){const t=Cl;if(!t||$c)return;Cl=null;const e=new kn(t.apiKey,t.projectId,t.branchName,t.endpoint);ug(),Mc(!0),Rc();try{Be.set("package");const n=a_(t.fileMap,t.landed,t.serializedYaml),i=await po(n,new Map),r=await vo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),Be.set("push");const o=await go(e,s);if(o.success){Ks({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||ho(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ks({...t.result,success:!1,error:n.message,unconfirmed:n instanceof Ge,remoteRefusal:n.remoteRefusal===!0})}}function ug(t){t&&t.target!==t.currentTarget||Ze(document.getElementById("commit-terminal-modal"))}function Vb(){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 Vd={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}},Gb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function dg(){Un&&clearTimeout(Un),Un=null}const Be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){dg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(sd(e,!0,"Deploying to FlutterFlow"),Je(e)),this.set("prepare")},set(t,e=null){if(!(!Vd[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=Vd[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=Gb.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(Kb(e)),fg(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&&(sd(t,!1),Ze(t,{force:!0,restoreFocus:!1}))}};function Kb(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 Rc(t){Be.start(t)}function Tc(){Be.stop()}function fg(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Gd(t){const e={[te.PREPARING]:"prepare",[te.VALIDATING]:"validate",[te.PUSHING]:"project",[te.SUCCESS]:"done"};if(t===te.ERROR){Be.timer&&clearInterval(Be.timer),Be.timer=null,fg(100,"Failed","Error occurred");return}const n=e[t];n&&Be.set(n)}function Yb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===Z.CODE_FILE):t.codeInfo?.codeType===Z.CODE_FILE}let $c=!1;function Mc(t){$c=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 Ks(t){Tc(),Mc(!1);const e=hp(t);e===De.COMMITTED?sg(t):e===De.PARTIAL?ag(t):e===De.UNCONFIRMED?lg(t):og(t)}async function Jb(){if(!or){console.error("No pending commit data");return}if($c){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=or;if(or=null,sr=Wb(),rg(),Mc(!0),Rc({withProvisioning:Yb(t)}),t.bundlePlan){const o=await eb(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Np(),s=await Qw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(s)}window.runThinkingPipeline=Sr;window.toggleStep=ib;window.toggleSection=nb;window.selectWorkflowStep=ut;window.copyCode=rb;window.retryWithDifferentModel=lb;window.openApiKeysModal=gc;window.closeApiKeysModal=$p;window.openComposerSettings=Tp;window.closeComposerSettings=Cw;window.walkthroughConnectAccount=kw;window.closeWalkthroughModal=Aw;window.openWalkthroughModal=Pw;window.advanceWalkthrough=mc;window.commitToFlutterFlow=Xw;function Zb(){y.isRunning||jt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Xb(){Tp();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Zb;window.openModelSelector=Xb;window.handlePromptImageSelect=cw;window.removePromptImage=uw;window.saveApiKeys=Tw;window.validateFlutterFlowConnection=yc;window.clearAllApiKeys=$w;window.toggleKeyVisibility=Bw;window.handleWelcomeVideoEnd=Hb;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=cb;window.updateFlutterFlowCredentialStatus=fb;window.openCommitConfirmModal=Ac;window.closeCommitConfirmModal=rg;window.closeCommitSuccessModal=qb;window.closeCommitTerminalModal=ug;window.finishProvisionedDeploy=zb;window.showCommitPartialModal=ag;window.showCommitUnconfirmedModal=lg;window.showCommitSuccessModal=sg;window.showCommitFailureModal=og;window.toggleCodePreview=Vb;window.confirmCommitToFlutterFlow=Jb;window.runRefinement=qp;window.regenerateFromPastedErrors=zp;window.clearErrorInput=ab;window.setFlutterFlowEndpoint=Sw;window.getFlutterFlowEndpoint=Ye;window.commitProgress=Be;window.openSignInModal=wo;window.closeSignInModal=Jp;window.handleMagicLinkRequest=vb;window.handleSignOut=yb;window.handleSendNewLink=bb;window.handleClearCache=Eb;window.handleDeleteAccount=Sb;window.closeDeleteUnavailableModal=xb;window.startCheckout=Lb;window.openCustomerPortal=Nb;window.openPricingModal=Ii;window.closePricingModal=ig;let cs=null,hg=null,pn={1:"pending",2:"pending",3:"pending"},qn=1,Pl=null,Lc=null;const So={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Qb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},eE={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function xo(){return y.runId+=1,y.runId}function ae(t){return t===void 0||t===y.runId}function pg(){y.runId+=1}function Nc(t){return document.getElementById(`pdot-${t}`)}const gg=window.matchMedia("(max-width: 920px)");function Kd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=gg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function tE(){Kd(),gg.addEventListener("change",Kd)}function nE(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Ys(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 Io(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){pn[t]=e;const n=Nc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=So[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 iE(){return[1,2,3].filter(t=>pn[t]==="done").length}function Ar(){const t=document.getElementById("pipeline-progress-fill");if(t)if(pn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${rE()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function rE(){const t=33.333333333333336,e=pn[qn];if(e==="active"&&Pl!==null){const n=(Date.now()-Pl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:iE()/3*100}function ko(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=pn[t],o=e||s==="done";if(n&&(n.textContent=o?eE[t]:Qb[t]),i&&(i.textContent=nE(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${So[t]}${a}`}}function sE(t){pn[t]==="pending"||pn[t]==="skipped"||(Lc=t,[1,2,3].forEach(e=>{const n=Nc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),ko(t))}function Oc(){Lc=null,[1,2,3].forEach(t=>{const e=Nc(t);e&&e.removeAttribute("aria-pressed")})}function mg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function oE(t,e,n){ae(n)&&mg(`${rn(t)} did not answer. Continuing on ${rn(e)}.`)}function Bc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function aE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function Cn(){Gn()}function lE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function cE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=cE;function uE(t,e){_p(t,document.getElementById("main-stage-container"),lE()),V0(document.getElementById("hero"),e)}window.addEventListener("hashchange",Cn);window.addEventListener("popstate",Cn);function Co(t={}){const{prompt:e=null,runId:n}=t;if(!ae(n))return;Fr(),Cn(),jt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),Io("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}hg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),pn={1:"pending",2:"pending",3:"pending"},Oc(),Bc(),mg(""),[1,2,3].forEach(a=>zn(a,"pending")),Ot(1,n),dE()}function Ot(t,e){ae(e)&&(qn=t,Pl=Date.now(),Oc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),ko(t),Ar())}function hn(t,e){ae(e)&&(zn(t,"done"),Lc===null&&ko(t,{done:!0}),Ar())}function vg(t,{stage:e=1,runId:n,retry:i=yg}={}){if(!ae(n))return;Po(),Fr(),Cn(),Io("failed"),jt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Oc(),ko(e),Ar();const o=mp(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=`${So[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>Ii()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Al}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Al}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Al(){pg(),ng(),y.isRunning=!1,Ys(!1),gn(),Io("settled"),Cn(),Po(),Fr(),Bc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),jt(!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 yg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),We=y.submittedImages.slice(),_n(),Bc(),Sr()}function dE(){Po(),cs=setInterval(()=>{const t=(Date.now()-hg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Ar()},250)}function Po(){cs&&(clearInterval(cs),cs=null)}let ar=null;function Fr(){ar&&(clearTimeout(ar),ar=null)}function Pi(){Po(),Fr(),Io("settled"),Ar();const t=document.getElementById("pipeline-progress-fill");ar=setTimeout(()=>{ar=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function ki(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function _g(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function fE(){return y_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function hE(t){return` -
    - ${ki(t.severity)} -
    -
    ${W(t.message)}
    - ${t.suggestion?`
    ${W(t.suggestion)}
    `:""} - ${W(t.source)} -
    -
    - `}function pE(t){return` -
  • -
    - ${W(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${W(t.detail)}

    `:""} -
    -
  • - `}function gE(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=>` -
    • - ${ki(u.severity)} - - ${W(u.message)} - ${u.suggestion?`${W(u.suggestion)}`:""} - -
    • - `).join("")} -
    - `:"",a=t.warnings.length?` -
    -

    ${ki("warning")} Bundle

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

    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=>` -
    1. - ${W(u.title)} - ${u.detail&&u.detail!==u.title?`${W(u.detail)}`:""} -
    2. - `).join("")} -
    -
    - `:"";e.innerHTML=` -
    -
    -

    ${W(t.title)}

    -

    ${W(t.summary)}

    -
    -
    Artifact${t.artifacts.length===1?"":"s"}
    ${t.artifacts.map(u=>W(u.artifactType||u.type||u.name)).join(" · ")}
    -
    Public API
    ${t.artifacts.flatMap(u=>u.publicApi||[]).map(W).join(" · ")||"No parameters returned"}
    -
    Manual Steps Required
    ${l||"None reported"}
    -
    Review
    ${W(t.status||"Not reported")}
    -
    - ${o} - ${a} -
    -
    - -
    - Is the generated code correct? -
    - - -
    - -
    -
    -
    - `}function mE(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(hE).join(""):`
    ${ki(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` -
  • ${W(l.name)}${l.version?` ${W(l.version)}`:""}${l.reason?`

    ${W(l.reason)}

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

    ${W(l.description)}

    `:""}
  • - `).join(""):'
  • No relationships for this file
  • ';return` -
    -
    - ${ki(e.status)} ${W(_g(e.status))} -

    ${W(e.artifactName)}

    - ${e.description?`

    ${W(e.description)}

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

    Code Review findings

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

    Manual FlutterFlow steps for this file

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

    Dependencies

    -
      ${r}
    -
    -
    -

    Deployment

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

    Public API

    -
    ${o}
    -
    -
    -

    Imports

    -
    ${s}
    -
    -
    -

    Relationships

    -
      ${a}
    -
    -
    - `}function vE(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=""),Yd();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&&Dc(o.dataset.artifactId)},Yd()),e&&e.classList.add("visible")}function Yd(){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")wg();else{const a=s.dataset.artifactId;a&&Dc(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 Rr(){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=fE(),o=wc();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")}gE(s),vE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` -`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=vp(a),!aE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=mE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Tr(t,e){const n=document.getElementById("main-stage-container"),i=q0(n),r=document.body.classList.contains("results-fullscreen");Fr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),jt(!0),y.selectedArtifactId||(y.selectedArtifactId=bi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Rr(),gn(),yE(),r||_p(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function yE(){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=""),Fl=!1}function Dc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Rr()}function wg(){y.resultsViewMode="summary",Rr()}function _E(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=wc(),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 Fl=!1;async function wE(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Fl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Fl=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 kc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function bE(){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 bg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function EE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function jt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(Cn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function Eg(){const t=H.isVerified&&!!H.email,e=de.tier||"free",n=t&&Ci(),i=!t||Dt(),s=n?"Checking…":i?Yl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Pc();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 SE(){Eg();const t=document.getElementById("credits-modal");t&&Je(t)}function xE(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ze(e)}function Sg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(Cn(),lc?.cancelTyping?.(),y.isRunning&&(pg(),ng(),y.isRunning=!1,Ys(!1),Pi(),y.artifactBundle?Rr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")jt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&jt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let Jd=!1;function jc(){const t=window.location.hash.replace(/^#/,"");Sg(t||"home",!1,Jd),Jd=!0}window.addEventListener("popstate",t=>{jc()});window.addEventListener("hashchange",()=>{jc()});window.copyResultsCode=_E;window.selectArtifact=Dc;window.selectResultsSummary=wg;window.submitResultsFeedback=wE;window.showErrorInputPanel=bE;window.hideErrorInputPanel=bg;window.setGenerationStageVisible=jt;window.switchView=Sg;window.selectPipelineStage=sE;window.editPipelinePrompt=Al;window.retryPipelineRun=yg;window.openCreditsModal=SE;window.closeCreditsModal=xE; diff --git a/dist/assets/index-DYbo9B-C.js b/dist/assets/index-DYbo9B-C.js new file mode 100644 index 0000000..12178ef --- /dev/null +++ b/dist/assets/index-DYbo9B-C.js @@ -0,0 +1,328 @@ +(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 E=typeof window<"u"?window:void 0,Be=typeof globalThis<"u"?globalThis:E,qe=Be?.navigator,F=Be?.document,we=Be?.location,Rl=Be?.fetch,ya=Be!=null&&Be.XMLHttpRequest&&"withCredentials"in new Be.XMLHttpRequest?Be.XMLHttpRequest:void 0,Gc=Be?.AbortController,Fg=Be?.CompressionStream,Je=qe?.userAgent;function Zd(){return!(!E||E.navigator.onLine===!1)}var Ri=typeof globalThis<"u"?globalThis:E;Ri&&typeof self>"u"&&(Ri.self=Ri),Ri&&typeof File>"u"&&(Ri.File=function(){});var N=E??{},oe={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Kc(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 ce(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){Kc(s,i,r,o,a,"next",l)}function a(l){Kc(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 Xd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var Yc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Jc(t){return typeof t=="string"||t}function Zc(t){return typeof t=="string"?t:void 0}var Ti,Rg=["$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"],Kt=(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})({}),Xc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Tg=["$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"],Mg=["token"],Qd="NativeGzipValidationError",_a=t=>t.length>=2&&t[0]===31&&t[1]===139,Qc=(t,e)=>t===Xc.GZipJS||e===Xc.GZipJS||e==="gzip",eu=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Nr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Qd,e},$g=(function(){var t=ce((function*(e,n){18>e.size&&Nr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());_a(i)&&i[2]===8||Nr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Ti)return Ti;Ti=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;Ti[c]=d>>>0}return Ti})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Nr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Nr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function wa(){return wa=ce((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=ce((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 $g(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),wa.apply(this,arguments)}var Lg=["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"],tu=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Lg.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Js=function(t){return t.trim()},ba=function(t){return t.replace(/^\$/,"")};function ef(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 tf=Object.prototype,nf=tf.hasOwnProperty,Zs=tf.toString,U=Array.isArray||function(t){return Zs.call(t)==="[object Array]"},Ue=t=>typeof t=="function",me=t=>t===Object(t)&&!U(t),rn=t=>{if(me(t)){for(var e in t)if(nf.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,ee=t=>Zs.call(t)=="[object String]",Ea=t=>ee(t)&&t.trim().length===0,et=t=>t===null,q=t=>C(t)||et(t),Ae=t=>Zs.call(t)=="[object Number]"&&t==t,Vt=t=>Ae(t)&&t>0,wt=t=>Zs.call(t)==="[object Boolean]",Ng=t=>t instanceof FormData,Og=t=>j(Tg,t),Bg=t=>j(Mg,t);function rf(t){return t===null||typeof t!="object"}function us(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Tl(t){return typeof Event<"u"&&sf(t,Event)}function sf(t,e){try{return t instanceof e}catch{return!1}}var Dg=[!0,"true",1,"1","yes"],Bo=t=>j(Dg,t),jg=[!1,"false",0,"0","no"];function Rt(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Ae(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),Rt(r||n,e,n,i))}class Ug{constructor(e){this.tt={},this.et=e.et,this.it=Rt(e.bucketSize,0,100,e.rt),this.nt=Rt(e.refillRate,0,this.it,e.rt),this.st=Rt(e.refillInterval,0,864e5,e.rt)}ot(e,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 lt="Mobile",ds="iOS",sn="Android",gi="Tablet",of=sn+" "+gi,af="iPad",lf="Apple",cf=lf+" Watch",Qi="Safari",mi="BlackBerry",uf="Samsung",df=uf+"Browser",ff=uf+" Internet",Hn="Chrome",Hg=Hn+" OS",hf=Hn+" "+ds,Ml="Internet Explorer",pf=Ml+" "+lt,$l="Opera",Wg=$l+" Mini",Ll="Edge",gf="Microsoft "+Ll,ui="Firefox",mf=ui+" "+ds,lr="Nintendo",cr="PlayStation",di="Xbox",vf=sn+" "+lt,yf=lt+" "+Qi,Wi="Windows",Sa=Wi+" Phone",nu="Nokia",xa="Ouya",_f="Generic",qg=_f+" "+lt.toLowerCase(),wf=_f+" "+gi.toLowerCase(),Ia="Konqueror",bf="Oculus Browser",fs="Vivaldi",Ef="Yandex",hs="Whale",ka="DuckDuckGo",Sf="Pale Moon",ps="Waterfox",er="Brave",xf="Google Search App",xe="(\\d+(\\.\\d+)?)",Do=new RegExp("Version/"+xe),zg=new RegExp(di,"i"),Vg=new RegExp(cr+" \\w+","i"),Gg=new RegExp(lr+" \\w+","i"),Nl=new RegExp(mi+"|PlayBook|BB10","i"),Kg={"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"},If=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?er:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?xf:j(t," OPR/")&&j(t,"Mini")?Wg:j(t," OPR/")?$l:Nl.test(t)?mi:j(t,"IE"+lt)||j(t,"WPDesktop")?pf:j(t,"OculusBrowser")?bf:j(t,df)?ff:j(t,Ll)||j(t,"Edg/")?gf:j(t,fs+"/")?fs:j(t,"YaBrowser/")?Ef:j(t,hs+"/")?hs:j(t,ka+"/")||j(t,"Ddg/")?ka:j(t,"FBIOS")?"Facebook "+lt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?hf:j(t,"CrMo")||j(t,Hn)?Hn:j(t,sn)&&j(t,Qi)?vf:j(t,"FxiOS")?mf:j(t.toLowerCase(),Ia.toLowerCase())?Ia:j(t,er+"/")?er:((s,o)=>o&&j(o,lf)||(function(a){return j(a,Qi)&&!j(a,Hn)&&!j(a,sn)})(s))(t,e)?j(t,lt)?yf:Qi:j(t,"PaleMoon/")?Sf:j(t,ps+"/")?ps:j(t,ui)?ui:j(t,"MSIE")||j(t,"Trident/")?Ml:j(t,"Gecko")?ui:"")},Yg={[pf]:[new RegExp("rv:"+xe)],[gf]:[new RegExp(Ll+"?\\/"+xe)],[Hn]:[new RegExp("("+Hn+"|CrMo)\\/"+xe)],[hf]:[new RegExp("CriOS\\/"+xe)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+xe)],[Qi]:[Do],[yf]:[Do],[$l]:[new RegExp("(Opera|OPR)\\/"+xe)],[ui]:[new RegExp(ui+"\\/"+xe)],[mf]:[new RegExp("FxiOS\\/"+xe)],[Ia]:[new RegExp("Konqueror[:/]?"+xe,"i")],[mi]:[new RegExp(mi+" "+xe),Do],[vf]:[new RegExp("android\\s"+xe,"i")],[ff]:[new RegExp(df+"\\/"+xe)],[bf]:[new RegExp("OculusBrowser\\/"+xe)],[fs]:[new RegExp(fs+"\\/"+xe)],[Ef]:[new RegExp("YaBrowser\\/"+xe)],[hs]:[new RegExp(hs+"\\/"+xe)],[er]:[new RegExp(er+"\\/"+xe)],[ka]:[new RegExp("(DuckDuckGo|Ddg)\\/"+xe)],[Sf]:[new RegExp("PaleMoon\\/"+xe)],[ps]:[new RegExp(ps+"\\/"+xe)],[xf]:[new RegExp("GSA\\/"+xe)],[Ml]:[new RegExp("(rv:|MSIE )"+xe)],Mozilla:[new RegExp("rv:"+xe)]},Jg=function(t,e,n,i){var r=If(t,e,n,i),s=Yg[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},iu=[[new RegExp(di+"; "+di+" (.*?)[);]","i"),t=>[di,t&&t[1]||""]],[new RegExp(lr,"i"),[lr,""]],[new RegExp(cr,"i"),[cr,""]],[Nl,[mi,""]],[new RegExp(Wi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Sa,""];if(new RegExp(lt).test(e)&&!/IEMobile\b/.test(e))return[Wi+" "+lt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Kg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Wi,i]}return[Wi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[ds,[t[3],t[4],t[5]||"0"].join(".")]:[ds,""]],[/(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("("+sn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+sn+")","i"),t=>t&&t[2]?[sn,[t[2],t[3],t[4]||"0"].join(".")]:[sn,""]],[/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/,[Hg,""]],[/Linux|debian/i,["Linux",""]]],ru=function(t){return Gg.test(t)?lr:Vg.test(t)?cr:zg.test(t)?di:new RegExp(xa,"i").test(t)?xa:new RegExp("("+Sa+"|WPDesktop)","i").test(t)?Sa:/iPad/.test(t)?af:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?cf:Nl.test(t)?mi:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(nu,"i").test(t)?nu:/(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(lt).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)?sn:of:new RegExp("(pda|"+lt+")","i").test(t)?qg:new RegExp(gi,"i").test(t)&&!new RegExp(gi+" pc","i").test(t)?wf:""},Zg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function su(t,e){return typeof(n=t)=="string"&&Zg.test(n)?t:e();var n}function wn(t){return t&&t.split("#")[0]}function Ol(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function ou(t,e,n){return kf.apply(this,arguments)}function kf(){return(kf=ce((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 Xg=t=>t instanceof Error,Cf={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}},Qg=Cf.info;function Pf(t){if(wt(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=>Pf(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function gs(t){var e=[];for(var n in t){var i=t[n];et(i)||C(i)||e.push({key:n,value:Pf(i)})}return e}function em(t,e){var n=Cf[t.level||"info"]||Qg,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),q(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),q(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:gs(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 Af(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 Ff(t,e,n,i){return{resourceLogs:[{resource:{attributes:gs(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let tm=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:em(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 ce((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return ce((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Kt.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=Ff(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(Kt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return ce((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Kt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Kt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Af(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Kt.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(Kt.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(Kt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return ce((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield ou(n,t):yield n}))()}flushWithTimeout(t){var e=this;return ce((function*(){var n=e.flush();yield ou(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 jo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function au(t){return String(t)+"000000"}function lu(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 nm=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=ce((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=lu(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(jo.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,jo)]+=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 ce((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:gs(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=au(Date.now()),n=new Map;for(var i of t.values()){var r,s=lu(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=gs((r=i.attributes)!==null&&r!==void 0?r:{}),l=au(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:jo})}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 Or,cu,Uo;function im(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Uo&&n.length===cu||(cu=n.length,Uo=n.reduce(((i,r)=>{Or||(Or={});var s=Or[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,Or[r]=[u,c];break}}return i}),{})),Uo}}class rm{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 ce((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 ce((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:im(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 vi="?";function Ca(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?vi:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Rf=(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]:vi,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},sm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,om=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,am=/\((\S*)(?::(\d+))(?::(\d+))\)/,lm=(t,e)=>{var n=sm.exec(t);if(n)return Ca(e,n[1],vi,+n[2],+n[3]);var i=om.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=am.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Rf(i[1]||vi,i[2]);return Ca(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},cm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,um=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dm=(t,e)=>{var n=cm.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=um.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]||vi,o=Rf(s,r);return Ca(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},uu=/\(error: (.*)\)/;class fm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=ee(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 us(e,"DOMException")}isDOMError(e){return us(e,"DOMError")}}class hm{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 sf(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 pm{constructor(){}match(e){return!!us(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 ee(e.message)&&e.message.length>0}pe(e){var n=e;if(ee(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 gm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class mm{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(gm);return r&&(n=r[1],i=r[2]),[n,i]}}var vm=["fatal","error","warning","log","info","debug"];function Tf(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 ym{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: "+Tf(e)}isSeverityLevel(e){return ee(e)&&!Ea(e)&&vm.indexOf(e)>=0}getStack(e){try{return ee(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ee(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(Xg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class _m{match(e){return Tl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Tf(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class wm{match(e){return rf(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 bm{match(e){return us(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 rf(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 ms="$message",vs="$timestamp",Em=new Set([ms,vs]),Ho={enabled:!0,max_bytes:32768};function ys(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Ho.enabled,max_bytes:xm(t.max_bytes,Ho.max_bytes)}:k({},Ho)}class Sm{constructor(e){this.Ke=[],this.Je=0,this.Ne=ys(e)}setConfig(e){this.Ne=ys(e),this.Xe()}add(e){var n=(function(r){var s;try{s=ef(r)}catch{return}try{var o=JSON.parse(s);if(!me(o))return;var a=o,l=a[ms],u=a[vs];return!ee(l)||l.trim().length===0||!ee(u)&&!Ae(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 xm(t,e){if(!Ae(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Mf=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(E&&(oe.DEBUG||E.POSTHOG_DEBUG||n)&&!C(E.console)&&E.console){for(var s=("__rrweb_original__"in E.console[r])?E.console[r].__rrweb_original__:E.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)=>Mf(t+" "+r,s)};return i},A=Mf("[PostHog.js]"),ve=A.createLogger,Im=ve("[ExternalScriptsLoader]"),Wo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Im.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)};N.__PosthogExtensions__=N.__PosthogExtensions__||{},N.__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)}},N.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);Wo(t,i,n)};oe.DEBUG=!1,oe.LIB_VERSION="1.415.7",oe.LIB_NAME="web";var $f="$people_distinct_id",ur="$device_id",qo="$device_model",qi="__alias",zi="__timers",Pa="$autocapture_disabled_server_side",Aa="$heatmaps_enabled_server_side",Fa="$exception_capture_enabled_server_side",Ra="$error_tracking_suppression_rules",Ta="$error_tracking_capture_extension_exceptions",Ma="$web_vitals_enabled_server_side",Bl="$dead_clicks_enabled_server_side",Dl="$product_tours_enabled_server_side",$a="$web_vitals_allowed_metrics",jn="$session_recording_remote_config",Lf="$replay_sample_rate",Nf="$replay_override_sampling",Of="$replay_override_linked_flag",Bf="$replay_override_url_trigger",Df="$replay_override_event_trigger",ai="$sesid",jl="$session_is_sampled",$n="$enabled_feature_flags",Vi="$active_feature_flags",Jr="$early_access_features",La="$feature_flag_details",Gi="$feature_flag_payloads",Zr="$feature_flag_request_id",_s="$minimal_flag_called_events",Pt="$override_feature_flags",Ln="$override_feature_flag_payloads",Gt="$stored_person_properties",Nn="$stored_group_properties",Na="$surveys",ws="$surveys_loaded_at",Oa="$surveys_activated",Xr="$surveys_activated_session",Qr="$surveys_activated_timestamps",Ki="ph_product_tours",Bn="$flag_call_reported",Yi="$flag_call_reported_session_id",es="$feature_flag_errors",tr="$feature_flag_evaluated_at",ft="$user_state",Ba="$client_session_props",Da="$capture_rate_limit",ja="$initial_campaign_params",Ua="$initial_referrer_info",bs="$initial_person_info",Es="$epp",Br="$posthog_cookieless",jf="$cookieless_mode",Uf="$sdk_debug_extensions_init_method",Hf="$sdk_debug_extensions_init_time_ms",Wf="$sdk_debug_recording_script_not_loaded",Ul="PostHog loadExternalDependency extension not found.",On="on_reject",Xt="always",ei="anonymous",Pn="identified",Ha="identified_only",Ss="visibilitychange",xs="beforeunload",si="$pageview",zo="$pageleave",Vo="$identify",du="$groupidentify";function Dr(t,e){U(t)&&t.forEach(e)}function ae(t,e){if(!q(t))if(U(t))t.forEach(e);else if(Ng(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)nf.call(t,n)&&e(t[n],n)}var ge=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 ts(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 fu=function(t){try{return t()}catch{return}},km=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 ae(t,(function(n,i){(ee(n)&&n.length>0||Ae(n))&&(e[i]=n)})),e},Cm=["herokuapp.com","vercel.app","netlify.app"];function Pm(t){var e=t?.hostname;if(!ee(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Cm)if(n===i)return!1;return!0}function be(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 Wa(t){return t.name==="ph_toolbar_internal"}var qf=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 Ae(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 Am{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 Fm}}var hu,zf=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};E&&!C(E.crypto)&&crypto.getRandomValues&&(zf=t=>crypto.getRandomValues(t));class Fm{nextUint32(){return this.R.length>this.O||(zf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Yt=()=>Rm().toString(),Rm=()=>(hu||(hu=new Am)).generate(),Mi="",Tm=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:qf,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(h,g){if(g===void 0&&(g=F),Mi)return Mi;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),b="dmn_chk_"+Yt();!Mi&&v--;){var w=m.slice(v).join("."),_=b+"=1;domain=."+w+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(b)&&(g.cookie=_+";max-age=0",Mi=w)}return Mi})(c);if(!f){var p=(h=>{var g=h.match(Tm);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}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}}},Go=null,de={N(){if(!et(Go))return Go;var t=!0;if(C(E))t=!1;else try{var e="__mplssupport__";de.F(e,"xyz"),de.P(e)!=='"xyz"'&&(t=!1),de.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Go=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return E?.localStorage.getItem(t)}catch(e){de.j(e)}return null},H(t){try{return JSON.parse(de.P(t))||{}}catch{}return null},F(t,e){try{return E?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){de.j(n)}return!1},q(t){try{E?.localStorage.removeItem(t)}catch(e){de.j(e)}}},Mm=[ur,"distinct_id",ai,jl,Es,bs,ft],jr={},$m={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>jr[t]||null,H:t=>jr[t]||null,F:(t,e)=>(jr[t]=e,!0),q(t){delete jr[t]}},An=null,Ie={N(){if(!et(An))return An;if(An=!0,C(E))An=!1;else try{var t="__support__";Ie.F(t,"xyz"),Ie.P(t)!=='"xyz"'&&(An=!1),Ie.q(t)}catch{An=!1}return An},j(t){A.error("sessionStorage error: ",t)},P(t){try{return E?.sessionStorage.getItem(t)}catch(e){Ie.j(e)}return null},H(t){try{return JSON.parse(Ie.P(t))||null}catch{}return null},F(t,e){try{return E?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){Ie.j(n)}return!1},q(t){try{E?.sessionStorage.removeItem(t)}catch(e){Ie.j(e)}}};class Lm{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===Xt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===On}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 Bo(e)?1:j(jg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?de:Qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Qt:de;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Bo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[qe?.doNotTrack,qe?.msDoNotTrack,N.doNotTrack].some((e=>Bo(e)))}}function Vf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Ue(i))return e;try{var r=i(e);return ee(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var Gf="__POSTHOG_TOOLBAR__",Nm=1,Om=3,Bm=11;function pu(t){return t instanceof Element&&(t.id===Gf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function bn(t){return!!t&&t.nodeType===Nm}function rt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Kf(t){return!!t&&t.nodeType===Om}function Yf(t){return!!t&&t.nodeType===Bm&&bn(t.host)}var Jf=1e3;function Wl(t){return t?Js(t).split(/\s+/):[]}function gu(t,e){var n=(function(i){var r,s=E==null||(r=E.location)==null?void 0:r.href;return C(s)?void 0:Vf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ks(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 Wl(e)}function Zf(t){return q(t)?null:Js(t).split(/(\s+)/).filter((e=>nr(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function dr(t){var e="";return za(t)&&!th(t)&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;Kf(n)&&n.textContent&&(e+=(i=Zf(n.textContent))!==null&&i!==void 0?i:"")})),Js(e)}function Ko(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ql=["a","button","form","input","select","textarea","label"];function qa(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 Xf(t){var e=t.parentNode;return!(!e||!bn(e))&&e}var Dm=[".ph-no-autocapture","[data-ph-no-autocapture]"],Qf=["next","previous","prev",">","<"],jm=[...Qf,"+","-","−","–"],mu=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,vu=[".ph-no-rageclick",".ph-no-capture"],Um=["","text","search","email","password","url","tel","number"];function yu(t,e){if(!E||zl(t))return!1;var n,i,r,s,o;if(wt(e)?(n=!!e&&vu,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:vu,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!bn(l))&&(!!rt(l,"textarea")||(rt(l,"input")?j(Um,(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=eh(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=Qf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,p=d.ariaLabel;return c.some((h=>mu(f,h)||mu(p,h)))}))})(i,a.map((l=>{var u;return{safeText:dr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!qa(a,n)}var zl=t=>!t||rt(t,"html")||!bn(t),eh=(t,e)=>{if(!E||zl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!rt(r,"body");)if(Yf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=Xf(r);if(!s)break;if(e||ql.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=E.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function za(t){for(var e=new Set,n=0,i=t;i.parentNode&&!rt(i,"body");i=i.parentNode){if(n++>=Jf||e.has(i))return!1;e.add(i);var r=ks(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(ks(t),"ph-include"))return!0;var s=t.type||"";if(ee(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!ee(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 th(t){return!!(rt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||rt(t,"select")||rt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var _u=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}))$"),wu=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Hm=[16,15,14,13],Wm=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),bu=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Eu=/[0-9A-Za-z_]/;function qm(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 nr(t,e){if(e===void 0&&(e=!0),q(t))return!1;if(ee(t)){t=Js(t);var n=e?_u.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(wu.lastIndex=0;s=wu.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Hm){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(_u.test(d)&&qm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Wm.test(t):(function(r){var s;for(bu.lastIndex=0;s=bu.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Eu.test(o)&&Eu.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Su(t){var e=dr(t);return nr(e=(e+" "+nh(t)).trim())?e:""}function nh(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=dr(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+nh(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function xu(t){return t.replace(/"|\\"/g,'\\"')}function zm(t){var e=t.attr__class;if(e)return U(e)?e:Wl(e)}var Ur=ve("[Dead Clicks]"),Vm=()=>!0,Gm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(Bl)),i=t.instance.config.capture_dead_clicks;return wt(i)?i:!!me(i)||n};class Iu{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({[Bl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=N.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Ur.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=N.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=me(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=N.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),Ur.info("starting...")}}else Ur.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Ur.info("stopping..."))}}var Yo=ve("[SegmentIntegration]"),ih="posthog-js";function rh(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,p,h,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,b=((d=c.exception)==null?void 0:d.values)||[],w=b.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=b[0])==null?void 0:f.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=b[0])==null?void 0:h.value)||c.message,$sentry_exception_type:(g=b[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 Km{constructor(e,n,i,r,s,o){this.name=ih,this.setupOnce=function(a){a(rh(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class ku{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=E?.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?Rt(a/o,0,1,A):1,p=o>1?Rt(l/o,0,1,A):1,h=u>1?Rt(c/u,0,1,A):1,g=u>1?Rt(d/u,0,1,A):1;r=ge(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Jo=["flags","surveys"],Ym={[$f]:{exposure:"hidden"},[qi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[zi]:{exposure:"hidden"},[Pa]:{exposure:"event"},[Aa]:{exposure:"hidden"},[Fa]:{exposure:"event"},[Ra]:{exposure:"hidden"},[Ta]:{exposure:"event"},[Ma]:{exposure:"event"},[Bl]:{exposure:"event"},[Dl]:{exposure:"hidden"},[$a]:{exposure:"event"},[jn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ai]:{exposure:"hidden"},[jl]:{exposure:"event"},[Lf]:{exposure:"event",shouldSkipFromEventProperties:t=>et(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"},[$n]:{exposure:"hidden",storageGroup:"flags"},[Vi]:{exposure:"hidden",storageGroup:"flags"},[Jr]:{exposure:"hidden"},[La]:{exposure:"hidden",storageGroup:"flags"},[Gi]:{exposure:"hidden",storageGroup:"flags"},[Zr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[_s]:{exposure:"hidden",storageGroup:"flags"},[Pt]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Gt]:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[Na]:{exposure:"hidden",storageGroup:"surveys"},[ws]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Oa]:{exposure:"event"},[Xr]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[Ki]:{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"},[Bn]:{exposure:"hidden"},[Yi]:{exposure:"hidden"},[es]:{exposure:"hidden"},[tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[Ba]:{exposure:"hidden"},[Da]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[Ua]:{exposure:"hidden"},[bs]:{exposure:"hidden"},[Es]:{exposure:"hidden"},[Nf]:{exposure:"event"},[Of]:{exposure:"event"},[Bf]:{exposure:"event"},[Df]:{exposure:"event"},[Uf]:{exposure:"event"},[Hf]:{exposure:"event"},[Wf]:{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"}},Jm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Fn=t=>{var e=Ym[t];if(e)return e;for(var n of Jm){var i=n[1];if(t.indexOf(n[0])===0)return i}},li=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return ef(t)}},Cs=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},yi=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," ")},fr=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},Ps=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},sh=(t,e)=>t>=e&&Zd(),oh=(t,e,n,i)=>{if(t===0){if(Zd()){var r=e+1;return r===n&&i(),r}return e}return 0},Hr="https?://(.*)",_i=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Zm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",..._i],hr="",Xm=["li_fat_id"];function ah(t,e,n){if(!F)return{};var i,r=e?[..._i,...n||[]]:[],s=lh(fr(F.URL,r,hr),t),o=(i={},ae(Xm,(function(a){var l=qf(a);i[a]=l||null})),i);return ge(o,s)}function lh(t,e){var n=Zm.concat(e||[]),i={};return ae(n,(function(r){var s=yi(t,r);i[r]=s||null})),i}function ch(t){var e=(function(s){return s?s.search(Hr+"google.([^/?]*)")===0?"google":s.search(Hr+"bing.com")===0?"bing":s.search(Hr+"yahoo.com")===0?"yahoo":s.search(Hr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!et(e)){i.$search_engine=e;var r=F?yi(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Cu(){return navigator.language||navigator.userLanguage}var As="$direct";function uh(){return F?.referrer||As}function dh(t,e,n){n===void 0&&(n=!1);var i=t?[..._i,...e||[]]:[],r=n?wn(we?.href):we?.href,s=r?.substring(0,1e3);return{r:uh().substring(0,1e3),u:s?fr(s,i,hr):void 0}}function fh(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?wn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==As?As:(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=lh(s);ge(o,l)}if(i){var u=ch(i);ge(o,u)}return o}function hh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Qm(){try{return new Date().getTimezoneOffset()}catch{return}}var ev={flags:tr,surveys:ws},tv=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ti="main";class Zo{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(),E){var r=()=>this.flush();be(E,"beforeunload",r,{capture:!1}),be(E,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Ae(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){tv.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=[...Mm,...o];return k({},de,{H(u){try{var c={};try{c=Qt.H(u)||{}}catch{}var d,f=JSON.parse(de.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];et(g)||g===""||(p[h]=g)}d=ge(f,p)}else d=ge(c,f);return de.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=de.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Qt.F(u,m,d,f,p,h)}catch(v){de.j(v)}return g},q(u,c){try{E?.localStorage.removeItem(u),Qt.q(u,c)}catch(d){de.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&de.N()?(n=de,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&Ie.N()?n=Ie:s==="memory"?n=$m: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 ae(this.props,((n,i)=>{var r=Fn(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=ge({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Jo){var n=de.H(this.Si(e));if(n&&!rn(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ge(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Fn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=ev[e];if(!i)return!1;var r=n[i],s=this.props[i];return Ae(r)&&Ae(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Fn(e))==null?void 0:n.storageGroup:void 0,r=i?de.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,ti))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,ti),Jo)){var s,o=i[r];(!rn(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(de,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ae(this.props,((i,r)=>{var s,o=(s=Fn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===ti)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ae(e,((r,s)=>{var o;i[s]=(o=Fn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===ti||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!==ti&&(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 Jo)de.q(this.Si(r));i?delete this.ci[ti]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(me(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ae(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(me(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ae(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||me(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=ah(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);rn(Hl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?ch(e):{})}update_referrer_info(){var e;this.register_once({$referrer:uh(),$referring_domain:F!=null&&F.referrer&&((e=Cs(F.referrer))==null?void 0:e.host)||As},void 0)}set_initial_person_info(){this.props[ja]||this.props[Ua]||this.register_once({[bs]:dh(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={};ae([Ua,ja],(r=>{var s=this.props[r];s&&ae(s,(function(o,a){e["$initial_"+ba(a)]=o}))}));var n=this.props[bs];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=fh(r,s),a={};return ae(o,(function(l,u){a["$initial_"+ba(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ge(e,i)}return e}safe_merge(e){return ae(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,p)=>f===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[zi]||{};i[e]=n,this.Pi(zi,i),this.save()}remove_event_timer(e){var n=this.props[zi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(zi,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=Fn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Fn(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&&Ue(n.then)&&n.then(void 0,(()=>{}))}}}}var He={GZipJS:"gzip-js",Base64:"base64"},$i={Activation:"events",Cancellation:"cancelEvents"},Xo={Popover:"popover",API:"api",Widget:"widget"},en={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Qo={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},Va={Popover:"popover",Inline:"inline"},nv={SHOWN:"product tour shown"},Pu={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Au=ve("[RateLimiter]");class iv{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=>{Au.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Au.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=(Ae(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")&&we!=null&&we.pathname)return""+((e=we.origin)!==null&&e!==void 0?e:"")+we.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 mn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void mn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return mn.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){mn.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||mn.warn("Failed to fetch remote config from PostHog."):mn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){mn.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){mn.error("Error loading feature flags",r)}}}var pt=Uint8Array,Qe=Uint16Array,wi=Uint32Array,Vl=new pt([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]),Gl=new pt([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]),Fu=new pt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),gh=function(t,e){for(var n=new Qe(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]},mh=gh(Vl,2),Ga=mh[1];mh[0][28]=258,Ga[258]=28;for(var Ru=gh(Gl,0)[1],vh=new Qe(32768),Ee=0;32768>Ee;++Ee){var ni=(43690&Ee)>>>1|(21845&Ee)<<1;vh[Ee]=((65280&(ni=(61680&(ni=(52428&ni)>>>2|(13107&ni)<<2))>>>4|(3855&ni)<<4))>>>8|(255&ni)<<8)>>>1}var ir=function(t,e,n){for(var i=t.length,r=0,s=new Qe(e);i>r;++r)++s[t[r]-1];var o,a=new Qe(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Qe(i),r=0;i>r;++r)o[r]=vh[a[t[r]-1]++]>>>15-t[r];return o},Vn=new pt(288);for(Ee=0;144>Ee;++Ee)Vn[Ee]=8;for(Ee=144;256>Ee;++Ee)Vn[Ee]=9;for(Ee=256;280>Ee;++Ee)Vn[Ee]=7;for(Ee=280;288>Ee;++Ee)Vn[Ee]=8;var Fs=new pt(32);for(Ee=0;32>Ee;++Ee)Fs[Ee]=5;var rv=ir(Vn,9),sv=ir(Fs,5),yh=function(t){return(t/8>>0)+(7&t&&1)},_h=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Qe?Qe:t instanceof wi?wi:pt)(n-e);return i.set(t.subarray(e,n)),i},qt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Li=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},ea=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 pt(0),0];if(r==1){var o=new pt(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 p=new Qe(f+1),h=Ka(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var b=s[i].s;if(e>=p[b])break;g+=v-(1<>>=m;g>0;){var w=s[i].s;e>p[w]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new pt(p),h]},Ka=function(t,e,n){return t.s==-1?Math.max(Ka(t.l,e,n+1),Ka(t.r,e,n+1)):e[t.s]=n},Tu=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Qe(++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]},Ni=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ya=function(t,e,n){var i=n.length,r=yh(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)},Mu=function(t,e,n,i,r,s,o,a,l,u,c){qt(e,c++,n),++r[256];for(var d=ea(r,15),f=d[0],p=d[1],h=ea(s,15),g=h[0],m=h[1],v=Tu(f),b=v[0],w=v[1],_=Tu(g),x=_[0],I=_[1],T=new Qe(19),S=0;b.length>S;++S)T[31&b[S]]++;for(S=0;x.length>S;++S)T[31&x[S]]++;for(var P=ea(T,7),R=P[0],L=P[1],$=19;$>4&&!R[Fu[$-1]];--$);var O,J,G,M,K=u+5<<3,ie=Ni(r,Vn)+Ni(s,Fs)+o,B=Ni(r,f)+Ni(s,g)+o+14+3*$+Ni(T,R)+(2*T[16]+3*T[17]+7*T[18]);if(ie>=K&&B>=K)return Ya(e,c,t.subarray(l,l+u));if(qt(e,c,1+(ie>B)),c+=2,ie>B){O=ir(f,p),J=f,G=ir(g,m),M=g;var Z=ir(R,L);for(qt(e,c,w-257),qt(e,c+5,I-1),qt(e,c+10,$-4),c+=14,S=0;$>S;++S)qt(e,c+3*S,R[Fu[S]]);c+=3*$;for(var se=[b,x],Ce=0;2>Ce;++Ce){var Q=se[Ce];for(S=0;Q.length>S;++S)qt(e,c,Z[ue=31&Q[S]]),c+=R[ue],ue>15&&(qt(e,c,Q[S]>>>5&127),c+=Q[S]>>>12)}}else O=rv,J=Vn,G=sv,M=Fs;for(S=0;a>S;++S)if(i[S]>255){var ue;Li(e,c,O[257+(ue=i[S]>>>18&31)]),c+=J[ue+257],ue>7&&(qt(e,c,i[S]>>>23&31),c+=Vl[ue]);var ye=31&i[S];Li(e,c,G[ye]),c+=M[ye],ye>3&&(Li(e,c,i[S]>>>5&8191),c+=Gl[ye])}else Li(e,c,O[i[S]]),c+=J[i[S]];return Li(e,c,O[256]),c+J[256]},ov=new wi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),av=(function(){for(var t=new wi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),ta=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function lv(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=av[255&p^f[h]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,p,h,g,m){var v=d.length,b=new pt(h+v+5*(1+Math.floor(v/7e3))+g),w=b.subarray(h,b.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=Ya(w,_,d.subarray(x,I)):(w[x]=!0,_=Ya(w,_,d.subarray(x,v)))}else{for(var T=ov[f-1],S=T>>>13,P=8191&T,R=(1<x;++x){var ue=G(x),ye=32767&x,je=$[ue];if(L[ye]=je,$[ue]=ye,x>=Ce){var St=v-x;if((B>7e3||se>24576)&&St>423){_=Mu(d,w,0,M,K,ie,Z,se,Q,x-Q,_),se=B=Z=0,Q=x;for(var _e=0;286>_e;++_e)K[_e]=0;for(_e=0;30>_e;++_e)ie[_e]=0}var tt=2,xt=0,Cn=P,Le=ye-je&32767;if(St>2&&ue==G(x-Le))for(var Re=Math.min(S,St)-1,Dt=Math.min(32767,x),Zn=Math.min(258,St);Dt>=Le&&--Cn&&ye!=je;){if(d[x+tt]==d[x+tt-Le]){for(var Ke=0;Zn>Ke&&d[x+Ke]==d[x+Ke-Le];++Ke);if(Ke>tt){if(tt=Ke,xt=Le,Ke>Re)break;var Xn=Math.min(Le,Ke-2),jt=0;for(_e=0;Xn>_e;++_e){var Ut=x-Le+_e+32768&32767,ut=Ut-L[Ut]+32768&32767;ut>jt&&(jt=ut,je=Ut)}}}Le+=(ye=je)-(je=L[ye])+32768&32767}if(xt){M[se++]=268435456|Ga[tt]<<18|Ru[xt];var Ht=31&Ga[tt],Ai=31&Ru[xt];Z+=Vl[Ht]+Gl[Ai],++K[257+Ht],++ie[Ai],Ce=x+tt,++B}else M[se++]=d[x],++K[d[x]]}}_=Mu(d,w,!0,M,K,ie,Z,se,Q,x-Q,_)}return _h(b,0,h+yh(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var p=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&ta(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),ta(u,c-8,n.d()),ta(u,c-4,i),u}var cv=!!ya||!!Rl,wh="text/plain",ns=!1,bh=(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:"")},Xs=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("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return ae(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},na=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===He.GZipJS){var i=lv((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new pt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new pt(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return _h(c,0,d)})(li(e)),{mtime:0});return{contentType:wh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===He.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(li(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:li(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=li(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Eh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Xs(t.url,{compression:He.Base64}),encodedBody:na(k({},t,{compression:He.Base64,Ji:void 0}))}:{url:bh(t.url,"compression"),encodedBody:na(k({},t,{compression:void 0,Ji:void 0}))};try{e=na(t)}catch(r){if(Qc(t.compression,yi(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&Qc(t.compression,yi(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?_a(new Uint8Array(n)):ArrayBuffer.isView(n)&&_a(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(ns=!0,i()):{url:t.url,encodedBody:e}},Sh=t=>{try{return Eh(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},uv=(function(){var t=ce((function*(e){var n=li(e.data),i=yield(function(s,o,a){return wa.apply(this,arguments)})(n,oe.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:wh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),dv=/Failed to fetch|NetworkError|Load failed/i,xh=t=>t?.name==="TypeError"&&dv.test(t?.message||""),Ih=t=>{var e=Sh(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ae(t.headers,(function(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Gc){var d=new Gc;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||xh(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;Rl(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(h){u&&clearTimeout(u.timeout),f(h)}}},Ja=t=>{try{var e,n=Eh(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(qe.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 Ja(k({},t,{data:d(u.slice(0,c))})),void Ja(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Ih(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},$u=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Xs(n===He.GZipJS?bh(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===He.GZipJS?{}:{compression:n}))},is=[];Rl&&is.push({transport:"fetch",method:Ih}),ya&&is.push({transport:"XHR",method(t){var e=Sh(t);if(e){var n=new ya,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ae(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)}}}),qe!=null&&qe.sendBeacon&&is.push({transport:"sendBeacon",method:Ja});var Za=3e3;class fv{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Rt(n?.flush_interval_ms||Za,250,5e3,A.createLogger("flush interval"),Za),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)&&ae(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 ae(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 hv=["retriesPerformedSoFar"];class pv{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(E)&&"onLine"in E.navigator&&(this.dr=E.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},be(E,"online",this.vr),be(E,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=Xd(e,hv);Vt(n)&&(i.url=Xs(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(E)||(this.vr&&(E.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(E.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 gv{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(){be(E,"scroll",this.yr,{capture:!0}),be(E,"scrollend",this.yr,{capture:!0}),be(E,"resize",this.yr)}scrollElement(){if(!this._r)return E?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=E?.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 E?e==="y"?E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop||0:E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var mv=t=>dh(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Lu{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({[Ba]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||mv,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Ba]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?fh(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 ae(Hl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+ba(i)]=n})),e}}class Kl{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 Oi=ve("[SessionId]");class Nu{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 Kl,this.Lr=(u,c)=>!(!Vt(u)||!Vt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Xt)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||Yt,this.Nr=i||Yt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Oi.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=Ie.H(this.jr),a=Ie.H(this.Br);o&&!a?this.Or=o:Ie.q(this.jr),Ie.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){Oi.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&&Ie.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&Ie.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?Ie.H(this.jr):null}Zr(e){var n=this.Pr;return!et(n)&&!et(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({[ai]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Vt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(ai):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!et(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({[ai]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Vt(e)?e:0,i=Vt(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[ai];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&&E&&(E.removeEventListener(xs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&Ie.q(this.Br)},be(E,xs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Xt)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=Vt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||Oi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),Oi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Oi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Vt(a)&&e&&!u?a:i,v=Vt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var b={noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(s,l,b))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var kh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&tu(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>tu(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Ch(){return(Ch=ce((function*(){var t=qe?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return ee(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 Rs=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 ia(t,e,n){return li({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Ph={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=>Rs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Rs(n,i))))),icontains:(t,e)=>e.map(qr).some((n=>t.map(qr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(qr).every((n=>t.map(qr).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 Ah(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||et(r))return!1;var s=[String(r)],o=Ph[i.operator];return!!o&&o(i.values,s)}))}var Xa="custom",Ou="i.posthog.com",vv=/^\/static\//;class yv{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":Xa),this.en[this.apiHost]}rn(e){if(vv.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=Ou+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Fh(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var te=ve("[Surveys]"),Rh="seenSurvey_",Th=t=>{try{var e=(n=>((i,r)=>""+Rh+(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){te.error("Failed to persist survey seen state",n)}},_v=[Xo.Popover,Xo.Widget,Xo.API],wv={ignoreConditions:!1,ignoreDelay:!1,displayType:Va.Popover},bv=ve("[PostHog ExternalIntegrations]"),Ev={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Sv{constructor(e){this._instance=e}ai(e,n){var i;(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return bv.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=N.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Ev[l],(()=>{var c;(c=N.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=N.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=N.__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 xv{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return ce((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&&Ue(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 Iv{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 Bu="extensionsRemoteConfig";class kv{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Iv(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(Bu,i);return this.un&&i(this.un),Wr(r)},this.vn=new xv(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(ur))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(ur);return typeof e=="string"?e:void 0}get library(){return{name:oe.LIB_NAME,version:oe.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 ce((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(Bu,e))}sendRequest(e,n){var i=this;return ce((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?Xs(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 rr={},ra=0,Ts=()=>{},Du='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Bi="Surveys module not available",ju="sanitize_properties is deprecated. Use before_send instead",Mh="Invalid value for property_denylist config: ",Cv=["token","distinct_id",jf],oi="posthog",$h=!cv&&Je?.indexOf("MSIE")===-1&&Je?.indexOf("Mozilla")===-1,sa=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:Pm(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Ts,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:we&&ee(we?.search)&&we.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:(E==null||(e=E.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:Ha,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Za},error_tracking:{},_onCapture:Ts},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:jm,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))},Pv=[["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 Pv){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=ge({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),ee(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(Mh+t.property_denylist)),s};class Av{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 nt{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===Xt||this.config.cookieless_mode===On&&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 Av,this.mn=!1,this.version=oe.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Kl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=sa(),this.SentryIntegration=Km,this.sentryIntegration=i=>(function(r,s){var o=rh(r,s);return{name:ih,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 gv(this),this.pageViewManager=new ku(this),this.rateLimiter=new iv(this),this.requestRouter=new yv(this),this.consent=new Lm(this),this.externalIntegrations=new Sv(this);var n=(e=nt.__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=ee(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=ee(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!==oi){var r,s=(r=rr[i])!==null&&r!==void 0?r:new nt;return s._init(e,n,i),rr[i]=s,rr[oi][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=ee(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=sa(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=sa(n.defaults),u=Uu(n),c=ge({},l,u,{name:i,token:a});me(l.rageclick)&&me(u.rageclick)&&(c.rageclick=ge({},l.rageclick,u.rageclick)),me(l.session_recording)&&me(u.session_recording)&&(c.session_recording=ge({},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:He.GZipJS;var d=this.En();if(this.persistence=new Zo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Zo(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&&Ie.N()){var f=Ie.H(this.bn);U(f)&&f.forEach((I=>{ee(I)&&this.yn.add(I)}))}else Ie.q(this.bn);var p=k({},this.persistence.props),h=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new fv((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new pv(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Nu(this),this.sessionPropsManager=new Lu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.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)),oe.DEBUG=oe.DEBUG||this.config.debug,oe.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p,s:h}),!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(),b=this.persistence.get_property(ft);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===ei)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Pn)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 w=this.config.get_device_id(Yt()),_=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(ft,n.bootstrap.isIdentifiedID?Pn:ei),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Br,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Yt());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ft,ei)}return be(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var S=I.config.segment;if(!S)return T();(function(P,R){var L=P.config.segment;if(!L)return R();var $=J=>{var G=()=>J.anonymousId()||Yt();P.config.get_device_id=G,J.id()&&(P.register({distinct_id:J.id(),$device_id:G()}),P.persistence.set_property(ft,Pn)),R()},O=L.user();"then"in O&&Ue(O.then)?O.then($):$(O)})(I,(()=>{S.register((P=>{typeof Promise<"u"&&Promise.resolve||Yo.warn("This browser does not have Promise support, and can not use the segment integration");var R=(L,$)=>{if(!$)return L;L.event.userId||L.event.anonymousId===P.get_distinct_id()||(Yo.info("No userId set, resetting PostHog"),P.reset()),L.event.userId&&L.event.userId!==P.get_distinct_id()&&(Yo.info("UserId set, identifying with PostHog"),P.identify(L.event.userId));var O=P.calculateEventProperties($,L.event.properties);return L.event.properties=Object.assign({},O,L.event.properties),L};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:L=>R(L,L.event.event),page:L=>R(L,si),identify:L=>R(L,Vo),screen:L=>R(L,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),Ue(this.config._onCapture)&&this.config._onCapture!==Ts&&(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 Ch.apply(this,arguments)})().then((I=>{I&&this.register({[qo]:I})})).catch(Ts),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=nt.__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)),Ue(this.featureFlags.onReloading)&&Ue(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({},nt.__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,Gm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Uf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Hf]: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,He.GZipJS)?He.GZipJS:j(r.supportedCompression,He.Base64)?He.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:Ha}),(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&&we!=null&&we.hostname){var e=we.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 ph(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()&&Dr(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(zo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(zo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?$h?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=He.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((b=>k({},b,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=$u(o.url,o.method,o.compression,o.timestampMode);var p=is.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var b=0;m.length>b;b++)if(m[b].transport===f)return m[b]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){xh(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===He.GZipJS&&Fg&&typeof Promise<"u"&&!ns?uv(o).then((m=>{g(m)})).catch((m=>{if(eu(m))return ns=!0,void g(k({},o,{compression:void 0,url:$u(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var b="name"in v?String(v.name):"";return eu(v)||b===Qd})(m)&&(ns=!0),g(o)})):h(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){ra++;try{var n,i=[],r=[],s=[];Dr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(Ue(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&&Ue(this[n])?s.push(a):r.push(a)}));var o=function(a,l){Dr(a,(function(u){try{if(U(u[0])){var c=l;ae(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{ra--}}push(e){if(ra>0&&U(e)&&ee(e[0])){var n=nt.prototype[e[0]];Ue(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)&&ee(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&&!ee(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,p=su(i?.uuid,Yt),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===si&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(_s)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,b,w,_=g?void 0:this.Vn(i?.$set_once,e!==du,e===Vo);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=$=>ee($)?$.slice(0,s):$,l=new Set,h=(function $(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var G;if(l.add(O),U(O))G=[],Dr(O,(K=>{G.push($(K))}));else{var M={};ae(O,((K,ie)=>{l.has(K)||(M[ie]=$(K))})),G=M}return G}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function($,O){O===void 0&&(O=[]);var J={},G=M=>{$[M]!==void 0&&(J[M]=$[M])};return Rg.forEach(G),O.forEach(G),J})(h.properties,Cv)),e===en.DISMISSED||e===en.SENT){var x=n?.[Qo.SURVEY_ID],I=n?.[Qo.SURVEY_ITERATION];Th({id:x,current_iteration:I}),h.$set=k({},h.$set,{[(v={id:x,current_iteration:I},b=e===en.SENT?"responded":"dismissed",w="$survey_"+b+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+b+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===en.SHOWN&&(h.$set=k({},h.$set,{[Qo.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===nv.SHOWN){var T=n?.[Pu.TOUR_TYPE];T&&(h.$set=k({},h.$set,{[Pu.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var S=k({},h.properties.$set,h.$set);if(rn(S)||this.setPersonPropertiesForFlags(S),!q(this.config.before_send)){var P=this.Pt(h);if(!P)return;(h=P).uuid=su(h.uuid,Yt)}this.dn.emit("eventCaptured",h);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),L={method:"POST",url:R,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"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(L):this.In.enqueue(L),h}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new kv(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[jf]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!ee(a.distinct_id)&&!Ae(a.distinct_id)||Ea(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,T,S){var P,R,L,$;if(S===void 0&&(S=!1),!Je)return{};var O,J=x?[..._i,...I||[]]:[],G=(function(Zn){for(var Ke=0;iu.length>Ke;Ke++){var Xn=iu[Ke],jt=Xn[1],Ut=Xn[0].exec(Zn),ut=Ut&&(Ue(jt)?jt(Ut,Zn):jt);if(ut)return ut}return["",""]})(Je),M=G[0],K=G[1],ie=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},B={};C(T)||(B.detectGoogleSearchApp=T);var Z={},se=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,Ce=(R=navigator)==null?void 0:R.maxTouchPoints,Q=E==null||(L=E.screen)==null?void 0:L.width,ue=E==null||($=E.screen)==null?void 0:$.height,ye=E?.devicePixelRatio;C(se)||(Z.userAgentDataPlatform=se),C(Ce)||(Z.maxTouchPoints=Ce),C(Q)||(Z.screenWidth=Q),C(ue)||(Z.screenHeight=ue),C(ye)||(Z.devicePixelRatio=ye);var je,St,_e,tt,xt,Cn,Le,Re,Dt=ge(Hl({$os:M,$os_version:K,$browser:If(Je,navigator.vendor,ie,B),$device:ru(Je),$device_type:(St=Je,_e=Z,Re=ru(St),Re===af||Re===of||Re==="Kobo"||Re==="Kindle Fire"||Re===wf?gi:Re===lr||Re===di||Re===cr||Re===xa?"Console":Re===cf?"Wearable":Re?lt:_e?.userAgentDataPlatform==="Android"&&((tt=_e?.maxTouchPoints)!==null&&tt!==void 0?tt:0)>0?600>Math.min((xt=_e?.screenWidth)!==null&&xt!==void 0?xt:0,(Cn=_e?.screenHeight)!==null&&Cn!==void 0?Cn:0)/((Le=_e?.devicePixelRatio)!==null&&Le!==void 0?Le:1)?lt:gi:"Desktop"),$timezone:hh(),$timezone_offset:Qm()}),{$current_url:fr(S?wn(we?.href):we?.href,J,hr),$host:we?.host,$pathname:we?.pathname,$raw_user_agent:Je.length>1e3?Je.substring(0,997)+"...":Je,$browser_version:Jg(Je,navigator.vendor,ie,B),$browser_language:Cu(),$browser_language_prefix:(je=Cu(),typeof je=="string"?je.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:oe.LIB_NAME,$lib_version:oe.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return oe.SDK_DIST_CHANNEL&&(Dt.$sdk_dist_channel=oe.SDK_DIST_CHANNEL),Dt})(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&&ge(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ge(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===Xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==si||s?e!==zo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=ge(a,u),e===si&&F&&(a.title=F.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}Je&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ae(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var b of this._n.slice())try{ge(v,b())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=ge({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ae(this.config.property_denylist,(function(x){delete a[x]})):A.error(Mh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(A.error(ju),a=w(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=ge({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(ju),a=l(a,"$set_once")),n&&(this.mn=!0),rn(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||!Ie.N())Ie.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?Ie.F(this.bn,n):Ie.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:Bi}),()=>{})}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:Bi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Bi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=wv),(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:Bi}}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:Bi})}Jn(e){return!e||Ea(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Br?(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(Ae(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(ur)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(qi)&&(this.unregister(qi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ft)||ei)===ei,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ft,Pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Vo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=ia(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ft,Pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=ia(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Bn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=ia(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=>ee(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(du,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var p,h=this.get_property(ur),g=this.get_property(qo),m=this.get_property(jn),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(p=this.persistence)==null||p.register({[jn]: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(ft,ei),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Xt)this.register_once({distinct_id:Br,$device_id:null},"");else{var b=this.config.get_device_id(Yt());this.register_once({distinct_id:b,$device_id:e?b:h},""),e||C(g)||this.register({[qo]: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 ce((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($f)?(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(qi,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(me(e)){var i,r,s,o,a,l,u,c,d,f,p,h;ge(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 Zo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);wt(m)&&(this.config.debug=m),wt(this.config.debug)&&(this.config.debug?(oe.DEBUG=!0,de.N()&&de.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(oe.DEBUG=!1,de.N()&&de.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){oe.LIB_NAME=e,oe.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:nt.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:oi;return n!==oi&&(n=oi+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ft))===Pn||((n=this.sessionPersistence)==null?void 0:n.get_property(ft))===Pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===Ha&&!this._isIdentified()&&rn(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[qi])&&((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!==On)}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!==Xt){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 Nu(this),this.pageViewManager=new ku(this),this.persistence&&(this.sessionPropsManager=new Lu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=nt.__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==On&&((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(Du)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Xt?(this.config.cookieless_mode===On&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===On&&(this.register({distinct_id:Br,$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(Du)}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===Xt||(this.config.cookieless_mode===On?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return qe?kh(qe,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(si,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(Ss,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),be(F,Ss,this.kn)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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&&!q(n[i]),l=r in n&&!q(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(q(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Bg),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),q(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Og(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!rn(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&&q(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=wt(e)&&!e,i=de.N()&&de.P("ph_debug")==="true";return!n&&(!!i||e)}}nt.__defaultExtensionClasses={},nt.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]]=km(t.prototype[e[n]])})(nt,["identify"]);class Hu{constructor(e){this.disabled=e===!1;var n=me(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 oa="$copy_autocapture",aa=ve("[AutoCapture]");function la(t,e){return e.length>t?e.slice(0,t)+"...":e}function Fv(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!bn(e));return e}function Rv(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!bn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!rt(f,"body")&&Jf>c.length;)if(Yf(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!bn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},b=!1,w=!1;if(ae(c,(S=>{var P=za(S);if(rt(S,"a")){var R=S.getAttribute("href");b=!!(P&&R&&nr(R))&&(u?wn(R):R)}j(ks(S),"ph-no-capture")&&(w=!0),m.push((function($,O,J,G,M){M===void 0&&(M=!1);var K=$.tagName.toLowerCase(),ie={tag_name:K};ql.indexOf(K)>-1&&!J&&(ie.$el_text=K.toLowerCase()==="a"||K.toLowerCase()==="button"?la(1024,Su($)):la(1024,dr($)));var B=ks($);B.length>0&&(ie.classes=B.filter((function(Q){return Q!==""}))),ae($.attributes,(function(Q){var ue;if((!th($)||["name","id","class","aria-label"].indexOf(Q.name)!==-1)&&(G==null||!G.includes(Q.name))&&!O&&nr(Q.value)&&(!ee(ue=Q.name)||ue.substring(0,10)!=="_ngcontent"&&ue.substring(0,7)!=="_nghost")){var ye=Q.value;Q.name==="class"&&(ye=Wl(ye).join(" ")),ie["attr__"+Q.name]=la(1024,Q.name==="href"&&M?wn(ye):ye)}}));for(var Z=1,se=1,Ce=$;Ce=Fv(Ce);)Z++,Ce.tagName===$.tagName&&se++;return ie.nth_child=Z,ie.nth_of_type=se,ie})(S,s,o,a,u));var L=(function($){if(!za($))return{};var O={};return ae($.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var G=J.name.replace("data-ph-capture-attribute-",""),M=J.value;G&&M&&nr(M)&&(O[G]=M)}})),O})(S);ge(v,L)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=rt(t,"a")||rt(t,"button")?Su(t):dr(t)),b){var _,x;m[0].attr__href=b;var I=(_=Cs(b))==null?void 0:_.host,T=E==null||(x=E.location)==null?void 0:x.host;I&&T&&I!==T&&(h=b)}return{props:ge({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((P=>{var R,L,$="";if(P.tag_name&&($+=P.tag_name),P.attr_class)for(var O of(P.attr_class.sort(),P.attr_class))$+="."+O.replace(/"/g,"");var J=k({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(L=P.nth_of_type)!==null&&L!==void 0?L:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),G={};return ts(J).sort(((M,K)=>M[0].localeCompare(K[0]))).forEach((M=>{var K=M[1];return G[xu(M[0].toString())]=xu(K.toString())})),($+=":")+ts(G).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(S){return S.map((P=>{var R,L,$={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(L=P.attr__href)==null?void 0:L.slice(0,2048),attr_class:zm(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return ts(P).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>$.attributes[O[0]]=O[1])),$}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var Di=ve("[ExceptionAutocapture]"),Wu=()=>{},Tv=ve("[TracingHeaders]"),Rn=ve("[Web Vitals]"),qu=9e5,zu="disabled",Vu="lazy_loading",ji="awaiting_config",zr="missing_config";ve("[SessionRecording]"),ve("[SessionRecording]");var Qa="[SessionRecording]",zt=ve(Qa),Mv=ve("[Heatmaps]");function ca(t){return me(t)&&"clientX"in t&&"clientY"in t&&Ae(t.clientX)&&Ae(t.clientY)}var Vr=ve("[Product Tours]"),ua=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Dl))},$v=["$set_once","$set"],It=ve("[SiteApps]"),Gu="Error while initializing PostHog app with config id ";function ii(t,e,n){if(q(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 Lv{constructor(e){this.ns=new Kl,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"||!ii(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=>ii(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&ii((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=>ii(u.text,n.text,n.text_matching||"exact")||ii(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;!q(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=>ii(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||Ah(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 Nv{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&&Ah(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===$i.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 Lv(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,$i.Activation),this.ks=this.Ps(e,$i.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,$i.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,$i.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&&(rn(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Ae(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=>Ae(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 Ov extends Nv{constructor(e){super(e)}Js(){return Oa}Ys(){return Xr}Ms(){return Qr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Qr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Qr)}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 Ae(r)&&r>0}ra(){return en.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 te}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Oa]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Xr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Xr)}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 Fh(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===en.SHOWN?"consume":"ignore":e===en.SHOWN?"persist":e===en.DISMISSED||e===en.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Gr="SDK is not enabled or survey functionality is not yet loaded",Ku="Disabled. Not loading surveys.",Bv=E!=null&&E.location?Ps(E.location.hash,"__posthog")||Ps(location.hash,"state"):null,Yu="_postHogToolbarParams",Ju=ve("[Toolbar]"),Zu=ve("[FeatureFlags]");class Dv{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||(Zu.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)||Zu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Xu=ve("[FeatureFlags]"),Tn=ve("[FeatureFlags]",{debugEnabled:!0}),da=`" failed. Feature flags didn't load in time.`,Qu="connection_error",ed=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},td=t=>{var e={};for(var n of ts(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},kt=ve("[Error tracking]"),nd="Refusing to render web experiment since the viewer is a likely bot",jv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Rs(e,t),not_regex:(t,e)=>!Rs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Oe{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Oe.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Oe.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);ee(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];Oe.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())Oe.aa(nd);else if(!this.Ne.disable_web_experiments){if(q(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Oe.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=Oe.getWindowLocation();if(e!=null&&e.search){var n=yi(e?.search,"__experiment_id"),i=yi(e?.search,"__experiment_variant");n&&i&&(Oe.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&&(Oe.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!q(e.conditions)&&Oe.da(e,n)&&Oe.va(e)}static da(e,n){var i;if(q(e.conditions)||q((i=e.conditions)==null?void 0:i.url))return!0;var r=Oe.getWindowLocation();if(r){var s,o,a,l=Vf(n,r.href);return(s=e.conditions)==null||!s.url||jv[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return E?.location}static va(e){var n;if(q(e.conditions)||q((n=e.conditions)==null?void 0:n.utm))return!0;var i=ah();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,h=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&h&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Oe.aa(nd):n!=="control"?i.forEach((r=>{if(r.selector){var s;Oe.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)}))}})):Oe.aa("Control variants leave the page unmodified.")}_is_bot(){return qe&&this._instance?kh(qe,this.Ne.custom_blocked_useragents):void 0}}var dt=ve("[Conversations]"),Mn="Conversations not available yet.",id="console",Lh="__posthogHandledLogsRequestError",fa=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Lh]=!0,n},rd=t=>!!t&&typeof t=="object"&&t[Lh]===!0,Qs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Xu,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 Dv(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 E&&be(E,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){E?.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=[],E?.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[Vi,Gi,Zr,Pt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa($n);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(tr);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($n))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Gi))!==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:Jc(f),variant:Zc(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(Pt),n=this.Oa(Ln);if(!n&&!e)return t||{};var i=ge({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],p=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Jc(i),variant:Zc(i),payload:Yc(e[n])}}))}getFlagVariants(){var t=this.Oa($n),e=this.Oa(Pt);if(!e)return t||{};for(var n=ge({},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(Gi),e=this.Oa(Ln);if(!e)return t||{};for(var n=ge({},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(Bn)}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(Gt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Nn),timezone:hh()};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({[es]:[Qu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?He.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Qu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[es]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(p,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return sh(this.Sa,3)}Ua(t){this.Sa=oh(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+da)}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(Zr)||void 0,u=this.Oa(tr)||void 0,c=this.Oa(Bn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Yi);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Bn]:c,[Yi]:n});else{var h,g,m,v,b,w,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Bn]:c},n?{[Yi]:n}:{}));var S=this.getFeatureFlagDetails(t),P=[...(h=this.Oa(es))!==null&&h!==void 0?h:[]];C(s)&&P.push("flag_missing");var R={$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(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),C(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var L,$=(w=S==null||(_=S.reason)==null?void 0:_.description)!==null&&w!==void 0?w:S==null||(x=S.reason)==null?void 0:x.code;$&&(R.$feature_flag_reason=$),S!=null&&(I=S.metadata)!=null&&I.id&&(R.$feature_flag_id=S.metadata.id),C(S?.original_variant)&&C(S?.original_enabled)||(R.$feature_flag_original_response=C(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(T=S.metadata)!=null&&T.original_payload&&(R.$feature_flag_original_payload=S==null||(L=S.metadata)==null?void 0:L.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[Bn]:c,[Yi]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Yc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+da)}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 ce((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"?He.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+da),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=Xu);var c=((I,T)=>{var S=I.flags;return S?k({},I,{featureFlags:Object.fromEntries(Object.keys(S).map((P=>{var R;return[P,(R=S[P].variant)!==null&&R!==void 0?R:S[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((P=>S[P].enabled)).filter((P=>{var R;return(R=S[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=S[P].metadata)==null?void 0:R.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,p=c.featureFlagPayloads;if(f){var h=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Vi]:f,[$n]:m,[_s]:!1}}var b=f,w=p,_=d;if(l!=null&&l.partialResponse)b=k({},s,b),w=k({},o,w),_=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)})));b=k({},s,Object.fromEntries(Object.entries(b).filter((I=>x.has(I[0]))))),w=k({},o,Object.fromEntries(Object.entries(w||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else b=k({},s,b),w=k({},o,w),_=k({},a,_);return k({[Vi]:Object.keys(td(b)),[$n]:b||{},[Gi]:w||{},[La]:_||{},[_s]:r.minimalFlagCalledEvents===!0},h?{[Zr]:h}:{},g?{[tr]: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([Pt,Ln]),this.Va(),void Tn.info("All overrides cleared");if(U(t))return this.F({[Pt]:ed(t)}),this.Va(),void Tn.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[Pt]=U(r)?ed(r):r),s&&(i[Ln]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([Pt,Ln]):r===!1?this.q(Pt):s===!1&&this.q(Ln),this.Va(),r===!1?Tn.info("Flag overrides cleared"):r&&Tn.info("Flag overrides set",{flags:r}),void(s===!1?Tn.info("Payload overrides cleared"):s&&Tn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[Pt]:t}),this.Va(),void Tn.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(Jr)||[]).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({[Vi]:Object.keys(td(o)),[$n]:o,[Gt]:k({},this.Oa(Gt)||{},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(Jr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return ce((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({[Jr]: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(Gt)||{},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({[Gt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Gt)||{});t.forEach((i=>{delete n[i]})),this.F({[Gt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Gt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(Nn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[Nn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Nn)||{};this.F({[Nn]:k({},e,{[t]:{}})})}else this.q(Nn)}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}}},Uv={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===ji||this.Ya===zr?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=zu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=E==null||(e=E.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 zt.error("started without valid sessionManager"),new Error(Qa+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Xt)throw new Error(Qa+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&be(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(jn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return E&&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),zt.info("starting")):(this.Ya=zu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ji&&this.Ya!==zr&&(this.Ya=Vu),N!=null&&(e=N.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=N.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return zt.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(jl),(e=this.Mr)==null||e.unregister(Lf)}uo(t,e){if(q(t))return null;var n,i=Ae(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(zt.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;q(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[jn]: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===ji&&(this.Ya=zr,zt.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):zt.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(jn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(jn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return zt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!q(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=N.__PosthogExtensions__)==null||!e.initSessionRecording)return zt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Wf]:!0});var r;if(this.Ja||(this.Ja=(r=N.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===zr||this.Ya===ji?void 0:(this.Ya=ji,zt.info("persisted remote config is stale, requesting fresh config before starting"),void new ph(this._instance).load());this.Ya=Vu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Of]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Nf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Bf:Df]:!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))}}},Hv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Hu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=me(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(E&&F){var t=n=>{n=n||E?.event;try{this.bo(n)}catch(i){aa.error("Failed to capture event",i)}};if(be(F,"submit",t,{capture:!0}),be(F,"change",t,{capture:!0}),be(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||E?.event;try{this.bo(n,oa)}catch(i){aa.error("Failed to capture copy/cut event",i)}};be(F,"copy",e,{capture:!0}),be(F,"cut",e,{capture:!0})}}}else aa.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;wt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Pa]: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[Pa],i=this.co,r=this.instance.Qi()&&!this.fo;if(et(i)&&!wt(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=Ko(t);Kf(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())&&yu(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===oa;if(i&&(function(d,f,p,h,g,m){var v;if(!E||zl(d)||p!=null&&p.url_allowlist&&!gu(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&gu(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>f.type===S)))return!1}var w=eh(d,h),_=w.parentIsUsefulElement,x=w.targetElementList;if(!(function(S,P){var R=P?.element_allowlist;if(C(R))return!0;var L,$=function(J){if(R.some((G=>J.tagName.toLowerCase()===G)))return{v:!0}};for(var O of S)if(L=$(O))return L.v;return!1})(x,p)||!qa(x,p?.css_selector_allowlist)||qa(x,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Dm))return!1;try{var I=E.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&&(ql.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Rv(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===oa){var l,u=Zf(E==null||(l=E.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 Ue(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(E==null||(e=E.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(){E&&E.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(E&&((e=E.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return Wu;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 Ue(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];Ue(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 Wu}})(E.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=E==null||(e=E.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(si,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};be(E,"popstate",t),this.wo=()=>{E&&E.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Aa]),this.rageclicks=new Hu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return me(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return q(this.Ne.capture_heatmaps)?q(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Mv.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Aa]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ca(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(){E&&F&&(this.Po=this.cr.bind(this),be(E,xs,this.Po),this.Ro=t=>this.ke(t||E?.event),be(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||E?.event),be(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Iu(this.instance,Vm,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),be(F,Ss,this.Oo),this.vo=!0)}Eo(){var t;E&&F&&(this.Po&&E.removeEventListener(xs,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.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&&bn(u)&&!rt(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:E)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=Xf(u)}return!1})(Ko(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"),!pu(t.target)&&ca(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&yu(Ko(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!pu(t.target)&&ca(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(E){var e=this.Ne.disable_capture_url_hashes?wn(E.location.href):E.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[..._i,...n||[]]:[],r=fr(e,i,hr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!rn(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Iu,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},q(n?.name)||q(n?.value))Rn.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=Ae(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 Rn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=N.__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 Rn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Ma]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=me(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return q(n)?((e=this._instance.persistence)==null?void 0:e.props[$a])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(me(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=me(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=me(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=me(this.Wo)&&Ae(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:qu;return t>0&&6e4>=t?qu:t}get isEnabled(){var t=we?.protocol;if(t!=="http:"&&t!=="https:")return Rn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=me(this.Wo)?this.Wo.web_vitals:wt(this.Wo)?this.Wo:void 0;return wt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Rn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=me(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=me(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Ma]:n}),this._instance.persistence.register({[$a]: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=N.__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?Rn.error("failed to load script",r):t()}))}Bo(t){var e=t||E?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?wn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[..._i,...i||[]]:[];return fr(n,r,hr)}Rn.error("Could not determine current URL")}}},Wv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(E&&this.isEnabled&&(n=N.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=N.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=N.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=N.__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){Di.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Fa]),this.Jo=new Ug(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:Di})),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 me(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?(Di.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Di.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({[Fa]: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)?Di.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 rm([new fm,new bm,new pm,new hm,new _m,new ym,new mm,new wm],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var p=uu.test(f)?f.replace(uu,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((b=>{return k({},b,{filename:b.filename||(w=v,w[w.length-1]||{}).filename,function:b.function||vi});var w}))})(u)}})("web:javascript",lm,dm)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(Ra))!==null&&e!==void 0?e:[],this.el=ys(this.il()),this.rl=new Sm(this.el)}onConfigChange(){this.el=ys(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,[Ta]:o})}}}get nl(){var t,e=!!this._instance.get_property(Ta),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(!ee(t)||t.trim().length===0)return void kt.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)=>Em.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&&kt.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[ms]:t,[vs]:new Date().toISOString()},i))}catch(s){kt.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 kt.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 kt.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 kt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&q(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 kt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void kt.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 kt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[ms]:t,[vs]:new Date().toISOString()})}sl(t){return me(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 ee(r)&&r.length>0&&n.$exception_types.push(r),ee(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=Ph[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 kt.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!q(t)&&U(t)}}},qv=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({[Dl]:!!e.productTours}),!ua(this._instance))return!this.vl&&q((n=this.Mr)==null?void 0:n.props[Ki])||Vr.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&&ua(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Vr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=N.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=N.__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[Ki];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(ua(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||Vr.warn(o):Vr.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({[Ki]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){q(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(Ki)}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)}}},Qs),zv={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=N._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var p=t.$set_once,h=t.$set;return{event:k({},Xd(t,$v),{properties:k({},t.properties,h?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(It.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)||(It.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,p=(m,v,b)=>{if(m!=null&&m[v]){var w=m[v];m[v]=b(w),c.push((()=>{m[v]=w}))}},h=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:h(v))).filter((v=>!et(v)));return p(u,"appendChild",(m=>function(v){var b=h(v);return b?m.call(this,b):v})),p(u,"insertBefore",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):v})),p(u,"replaceChild",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):b})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];var x=g(w);return w.length&&!x.length?void 0:v.apply(this,x)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,b){var w=h(b);return w?m.call(this,v,w):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&&(It.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,It.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){It.error(Gu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){It.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){It.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 It.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;N["__$$ph_site_app_"+u]=r._instance,(l=N.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return It.error(Gu+u,d)}))};for(var a of s.siteApps)o()}else It.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Vv={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=N.__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=N.__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=N.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Tv.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()}}},Gv=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 te.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(q(e))return te.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,te.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)te.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)te.info(Ku);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())te.info("Not loading surveys in cookieless mode without consent.");else{var t=N?.__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 te.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Ov(this._instance),te.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){te.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 te.info(Ku),t([]);var n,i=this._instance.get_property(Na);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?te.error(a):r.error||te.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&(Fh(p)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[Na]:c,[ws]: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(ws);return Ae(t)&&Date.now()-t>3e5}Bl(){return Ae(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Th(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){te.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!q(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);te.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(q(this._surveyManager))return{eligible:!1,reason:Gr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(q(this._surveyManager))return{eligible:!1,reason:Gr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(q(this._surveyManager))return te.warn("init was not called"),{visible:!1,disabledReason:Gr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return q(this._surveyManager)?(te.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Gr})):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(q(this._surveyManager))te.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(_v.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(te.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;te.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),te.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);te.warn("Survey element not found")}else te.warn("Surveys of type "+r.type+" cannot be rendered in the app");else te.warn("Survey not found")}}displaySurvey(t,e){var n;if(q(this._surveyManager))te.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!==Va.Popover&&e.initialResponses&&te.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 te.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==Va.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else te.warn("Survey not found")}}cancelPendingSurvey(t){q(this._surveyManager)?te.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Qs),Kv={toolbar:class{constructor(t){this.instance=t}Wl(t){N.ph_toolbar_state=t}Vl(){var t;return(t=N.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),Wa(this.instance.config)||!E||!F)return!1;t=t??E.location,n=n??E.history;try{if(!e){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}e=E?.localStorage}var i,r=Bv||Ps(t.hash,"__posthog")||Ps(t.hash,"state"),s=r?fu((()=>JSON.parse(atob(decodeURIComponent(r)))))||fu((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(Yu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=N.ph_load_toolbar||N.ph_load_editor;!q(e)&&Ue(e)?e(t,this.instance):Ju.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(Gf));if(!E||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(E.localStorage.setItem(Yu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=N.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Ju.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),be(E,"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)}}},Yv=k({experiments:Oe},Qs),Jv={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;q(e)||(wt(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||Wa(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=N?.__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 dt.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,dt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else dt.error("Cannot complete initialization: remote config is null")}eu(t,e){dt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():dt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!et(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Wa(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?q(this.Jl)||!this.Jl.token?"missing_token":N!=null&&N.__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 ce((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(dt.warn(Mn),null)}))()}getMessages(t,e){var n=this;return ce((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(dt.warn(Mn),null)}))()}markAsRead(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(dt.warn(Mn),null)}))()}getTickets(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(dt.warn(Mn),null)}))()}requestRestoreLink(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(dt.warn(Mn),null)}))()}restoreFromToken(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(dt.warn(Mn),null)}))()}restoreFromUrlToken(){var t=this;return ce((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(dt.warn(Mn),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()}}},Zv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ve("[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(rd)||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),E&&be(E,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=C(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(f=w?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=w?.["deployment.environment"])!==null&&h!==void 0?h:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,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 tm(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},id);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;!q(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){rd(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=N?.__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===Kt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Kt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.LIB_VERSION}}Ot(t){return new Promise((e=>{if(sh(this.Sa,3))e({kind:"fatal",error:fa(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:fa(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:fa(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=oh(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,oe.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,id,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ff(s,Af(n,oe.LIB_NAME,oe.LIB_VERSION),i,oe.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,q(r)||(e.sessionStartTimestamp=r),q(s)||(e.lastActivityTimestamp=s)}if(N!=null&&(t=N.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?wn(N.location.href):N.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Xv={metrics:class{constructor(t){this.rt=ve("[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 nm(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:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.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)}}},Qv=k({},Qs,Uv,Hv,Wv,qv,zv,Gv,Vv,Kv,Yv,Jv,Zv,Xv);nt.__defaultExtensionClasses=k({},Qv);var Nh=(function(){oe.SDK_DIST_CHANNEL="npm";var t=rr[oi]=new nt;return(function(){function e(){e.done||(e.done=!0,$h=!1,ae(rr,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():be(F,"DOMContentLoaded",e,{capture:!1}):E&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ey=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Ze=null,Ms=null,Oh="";const el=new Map;function Bh(t){return[...t.querySelectorAll(ey)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function ty(t){for(const n of document.body.children)n===t||n.tagName==="SCRIPT"||(el.set(n,{inert:n.inert,ariaHidden:n.getAttribute("aria-hidden")}),n.inert=!0,n.setAttribute("aria-hidden","true"));const e=document.activeElement;e&&e!==document.body&&!t.contains(e)&&e.blur()}function ny(){for(const[t,e]of el)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);el.clear()}function Dh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=Ze&&Ze!==n?Ze:null,r=Ms;if(i&&Ge(i,{restoreFocus:!1,force:!0}),Ze!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),Ms=a,Oh=document.body.style.overflow,ty(n),document.body.style.overflow="hidden"}Ze=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(Ze!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Bh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function Ge(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Dh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==Ze)return!0;ny(),document.body.style.overflow=Oh,Ze=null;const i=Ms;return Ms=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function iy(){return!!Ze}function sd(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 ry(t){if(!Dh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ge(t)}document.addEventListener("keydown",t=>{if(!Ze)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),ry(Ze);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Bh(Ze);if(!e.length){t.preventDefault(),(Ze.querySelector(".modal-content")||Ze).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 sy(){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 Yl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),oy=Object.freeze({free:2,professional:50,power:2e3}),ay="(contact us)",ly=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 ${ay}`])}),jh="CodeFile",Uh="GeneratedCode",cy={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function vn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tl(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function uy(t={},e=0){const n=tl(t.artifactType||t.type||jh),i=tl(t.artifactName||t.name||t.fileName||`${Uh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Hh(t={},e=0){const n=vn(t),i=n.artifactType||n.type||jh,r=n.artifactName||n.name||Uh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:tl(n.id)||uy({...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:Wh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:qh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:vn(n.metadata),codeType:n.codeType||cy[i]||"O"}}function Wh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=vn(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(vn(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function qh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=vn(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 nl(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 pr(t,e={}){const n=[],i=typeof t=="string"?nl(t):t,s=vn(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)=>Hh(d,f)),l=new Map(o.map((d,f)=>[vn(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=qh(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:Wh(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:vn(s.metadata)}}function bi(t){return pr(t).artifacts[0]||Hh()}function an(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Ei(t){return JSON.stringify(t,null,2)}function dy(t){return Ei({task:"architect",userRequest:String(t??"")})}function fy(t){const e=an(t);return e&&typeof e=="object"&&typeof e.task=="string"?Ei(e):Ei({task:"generate_bundle",bundleSpec:e})}function hy(t){return Ei({task:"review_bundle",generatedBundle:an(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 Jl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=an(e)),n}function py({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return Ei({task:"regenerate_artifact",artifactId:i,bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(r)})}function zh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Ei({task:"regenerate_bundle",bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(i??"")})}const od={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"},gy=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function st(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function my(t){return st(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||st(t.filterSummary)||st(t.filterResults):!1}function Vh(t,e=0){if(!st(t)||e>3)return null;if(my(t))return t;for(const n of gy){const i=t[n];if(st(i)){const r=Vh(i,e+1);if(r)return r}}return null}function $s(t){return Array.isArray(t)?t.some($s):st(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some($s):!1}function il(t){return Array.isArray(t)?t.some(il):st(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(il):!1}function Gh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function vy(t,e){if(st(t))for(const[n,i]of Object.entries(t)){if(!st(i))continue;const r=st(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>st(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Gh(n))}}function yy(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>st(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!$s(r))continue;const s=Gh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=st(o)?Object.entries(o).filter(([,l])=>$s(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function _y(t){return od[t]?od[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ad(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 wy(t){const e=Vh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);vy(e.filterSummary,n),yy(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=il(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function by(t,e){const n=wy(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(_y))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ad(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 ${ad(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 Ey(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ld(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Ey(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 Zl(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 cd(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 Sy(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=Zl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await cd(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await cd(c)),n[o]=u,a.type==="F"){const d=ld(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const r=new Set(ld(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 xy=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),ud={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Iy=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),ky=["Struct","Record"],Cy=[{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=>ha(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=>ha(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 { + const _P({required this.t}); + final double t; +} +class W extends StatefulWidget { + const W({this.value = 1.0}); + final double value; +}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>ha(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { + const W({this.textStyle}); + final TextStyle? textStyle; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { + const W({this.width}); + final double? width; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Ct(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function gr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Ay(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;rFy(t).usable);function Ty(t=""){const e=gr(t);return Ry.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function My(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=Py(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rdd(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function eo(t=""){return Array.from(gr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function $y(t="",e=""){return Xl(t,e)?.returnType||null}function fd(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 Ly(t,e){const n=eo(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>fd(l)===r)||n.length>1)return null;const[o]=n,a=`${fd(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 Ql(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Ny(t,e,n=""){const i=Xl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Zl(r,"A");if(s===i)return null;const o=`${Ql(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 Oy(t="",e=""){return Xl(t,e)!==null}function By(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Iy.has(i)?!1:!ky.some(s=>i.endsWith(s))||e.has(i))}function Dy(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=$y(t,e),r=By(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 jy(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(xy.has(t.artifactType)||n.push(Ct(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(Ct(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(Ct(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(Ct(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ty(r))n.push(Ct(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Oy(r,t.artifactName)&&n.push(Ct(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(eo(r)),o=Dy(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(Ct(t,"error",o));const a=Ny(i,r,t.artifactName);a&&n.push(Ct(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(Ct(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Ly(i,r);s&&n.push(Ct(t,"info",s))}return n}function Uy(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>eo(s.code||""))),i=e.flatMap(s=>jy(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:ud[s.artifactType]||ud.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const hd="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function pd(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Hy(t=""){const e=t.indexOf(hd);return e===-1?t:t.slice(e+hd.length).replace(/^\s*\n/,"")}const Wy=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function qy(t="",e=""){const n=Hy(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(pd).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=pd(s);return o===null||!i.has(o)?!0:!Wy.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const zy=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","flutter_web_plugins","integration_test","sky_engine"]);function Vy(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 Qy(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(p=>p.id)).map(p=>n.find(h=>h.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(p=>{const h=Xy(p),g=p.fixedCode||p.code||"",m=p.codeType||Jy[p.artifactType]||it.OTHER;g.trim()||s.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:h,content:g,type:m,path:p.deployPath||Zy(h,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,h)=>({entry:p,index:h})).filter(({entry:p})=>p.type===it.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],h={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +${m.content}`).join(` + +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=h}const u={...gd(t?.dependencies),...r.reduce((p,h)=>({...p,...gd(h.dependencies)}),{})},c={};r.forEach(p=>{ec(p.fixedCode||p.code||"").forEach(h=>{h in u||(c[h]="")})});const d={...c,...u},f=Qy(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=new Map){const n=[],i=[];for(const r of t)(e.has(r.path)?n:i).push(r);return{landed:n,notLanded:i}}function rl(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}function o_(t){return t?t.notLanded.length===0&&t.landed.length>0:!1}function a_(t,e,n){const i=rl(t,e),r=new Map(i);return r.set("pubspec.yaml",{content:n,type:"D",path:"pubspec.yaml"}),r}const md={pass:0,warning:1,fail:2},l_=["manualActions"];function ct(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tn(...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 At(t){return t==null?[]:Array.isArray(t)?t:[t]}function c_(t){const e=ct(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return vd(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?vd(Number(i[1])):null}function vd(t){return t>=0&&t<=100?t:null}function ht(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function tc(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 sl(...t){return t.filter(Boolean).reduce((e,n)=>md[n]>md[e]?n:e,"pass")}function Zh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ct(t),r=tn(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:tc(i.severity||i.status||i.level)||e,message:r,suggestion:tn(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function ol(t,e="review"){const n=ct(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>At(n[r]).map(o=>Zh(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=ct(t),r=tn(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:tn(i.detail,i.instructions,i.description),location:tn(i.location,i.flutterFlowPath,i.path),timing:tn(i.timing,i.phase)||"unspecified",artifactId:n,source:tn(i.source)||"Code Review"}:null}function al(t,e=null){const n=ct(t);return l_.flatMap(i=>At(n[i])).map((i,r)=>u_(i,r,e)).filter(Boolean)}function d_(t){let e=typeof t=="string"?nl(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ct(e);typeof n.content=="string"&&(e=nl(n.content)||e);const i=ct(e),r=ct(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(ht);return t.find(i=>{const r=ct(i);return[r.id,r.fileName,r.artifactName,r.name].map(ht).some(s=>s&&n.includes(s))})||null}function h_(t,e){return At(t?.metadata?.compatibility?.deployHints).find(r=>ht(r?.artifactId)===ht(e.id)||ht(r?.fileName)===ht(e.fileName))?.pathHint||""}function p_(t,e){return At(t?.relationships).filter(n=>ht(n?.from)===ht(e.id)||ht(n?.to)===ht(e.id))}function g_(t,e){return At(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ht(n.artifactId)===ht(e.id)).map(n=>Zh(n,"warning","Compatibility check")).filter(Boolean)}function m_(t,e,n,i){const r=f_(e,n),s=ct(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...ol(s),...g_(t,n)],l=al(s,n.id),u=tc(s.status||s.verdict||s.outcome||s.result),c=a.length?sl(...a.map(f=>f.severity)):null,d=sl(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?tn(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 y_({bundle:t,reviewResult:e}){const n=ct(t),i=At(n.artifacts),{root:r,rawText:s}=d_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ct).find(w=>Object.keys(w).length)||{},a=At(r.artifacts||r.files||r.reviews),l=i.map((w,_)=>m_(n,a,w,_)),u=ol(r),d=[...ol(o),...u],f=[...al(o),...al(r),...l.flatMap(w=>w.manualSteps)].filter((w,_,x)=>x.findIndex(I=>I.title===w.title&&I.artifactId===w.artifactId)===_),p=tc(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=sl(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??r.score??r.overallScore??s,m=c_(g),v=tn(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:h,score:m,artifactPresentations:l,manualSteps:f}),b=l.reduce((w,_)=>(w[_.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:At(n.deployOrder),relationships:At(n.relationships),warnings:At(n.warnings),compatibility:ct(n.metadata?.compatibility)}}const __="x-ff-api-key",yd="dr_",w_=/^[A-Za-z0-9_-]{1,120}$/;function b_(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`${yd}${t.randomUUID()}`;if(t&&typeof t.getRandomValues=="function"){const e=t.getRandomValues(new Uint8Array(16));return`${yd}${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}return null}function E_(t){return typeof t=="string"&&w_.test(t)}function S_(t,e){return`${String(t).replace(/\/deployCustomClasses$/,"")}/runStatus/${encodeURIComponent(e)}`}function x_(t){if(!t||typeof t!="object")return null;const{status:e}=t;return e!=="running"&&e!=="done"&&e!=="failed"?null:{status:e,phase:typeof t.phase=="string"?t.phase:"",message:typeof t.message=="string"?t.message:"",error:typeof t.error=="string"?t.error:null,deployed:Array.isArray(t.deployed)?t.deployed:[],dryRun:t.dryRun===!0}}const I_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function k_(t){return!t||!t.status?{definitive:null}:t.status==="done"?{definitive:"success",deployed:Array.isArray(t.deployed)?t.deployed:[]}:t.status==="failed"&&I_.has(t.phase)?{definitive:"failed",error:t.error||"The deploy failed before writing anything to FlutterFlow."}:{definitive:null}}async function C_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,timeoutMs:r=8e3}){if(!E_(e))return null;const s=i||globalThis.fetch;if(!s)return null;const o=new AbortController,a=setTimeout(()=>o.abort(),r);try{const l=await s(S_(t,e),{method:"GET",headers:{[__]:String(n||"")},signal:o.signal});if(!l.ok)return null;const u=await l.json();return x_(u)}catch{return null}finally{clearTimeout(a)}}async function P_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,budgetMs:r=12e3,intervalMs:s=2e3}){const o=Date.now()+r;let a=0;for(;Date.now()=2)return{definitive:null};const u=o-Date.now();if(u<=0)break;await new Promise(c=>setTimeout(c,Math.min(s,u)))}return{definitive:null}}const A_=/^\uFEFF/;function Ui(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function F_(t){const e=String(t??"").replace(A_,"");if(!e.trim())return"";const n=e.split(` +`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ui(n);{const c=ll(e);if(!c.error&&o.every(f=>wd(f,c.commentAndStringRanges)))return Ui(n)}if(r===1){const c=Ui(n.slice(0,s)),d=Ui(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 R_(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 Xh(t){const e=R_(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 Qh(t){return`${Ql(t)}.dart`}function T_(t){return Zl(t,"W")}const _d={"(":")","[":"]","{":"}"},M_={")":"(","]":"[","}":"{"},$_=/[A-Za-z0-9_]/;function ll(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]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!$_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(_d[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(M_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&_d[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function L_(t){return ll(String(t??"")).error}function wd(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 N_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],O_="MAGIC_LINK_SENT",B_="PLUS_ALIAS_REJECTED",D_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",to={allowlistedDomains:N_,successCode:O_,validationCode:B_,messageTemplate:D_},j_=new Set(to.allowlistedDomains),U_=to.successCode,H_=to.validationCode;function no(t){return typeof t=="string"?t.trim():""}function W_(t){const e=no(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 j_.has(r)?i.includes("+"):!1}function q_(t,e){return to.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ep(t){if(!W_(t))return null;const e=no(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return q_(e,i)}function ic(t){return!t||typeof t!="object"||Array.isArray(t)||t.success===!1||t.error?!1:t.code?t.code===U_:t.success===!0||typeof t.message=="string"}function tp(t,e){return t?.code===H_?t.message||ep(e)||"Please enter your primary email address.":ic(t)?`Check your email — we sent a link to ${no(e)}`:t?.message||"Something went wrong. Please try again."}const z_="ccc_auth_session",V_="ccc_subscription",G_=Object.freeze(["hasSeenWalkthrough"]);function K_(t){const e=[];for(const n of G_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function Y_(){return[z_,V_]}function J_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of Y_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function Z_(t){const e=t?.message||t?.error;return typeof e=="string"&&e.trim()?e.trim():"The server could not send the link."}function X_({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());if(!ic(o))throw new Error(Z_(o));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 Q_=/^dependencies\s*:\s*(?:#.*)?$/,e0=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function xr(t){const e=t.match(e0);return e?e[1]??e[2]??e[3]:null}function Ir(t){const e=t.trim();return e===""||e.startsWith("#")}function En(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function rc(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;sc&&/\s/.test(s[d-1]);)d-=1}return t[r]=s.slice(0,c)+oc(n)+s.slice(d),!0}return!1}function bd(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?oc(i):">=0.0.0"}`]}function r0(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(ap(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=sc(r);if(l){const u=o.flatMap(([c,d])=>bd(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(...bd(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function s0(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=io(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l),d=c&&!c.isScalar&&c.sourceKey===null&&c.version!==null;if(!c||!c.isScalar&&!d||!String(u||"").trim()){a.push(l);continue}if(d){i0(r,c,String(u).trim())?o.push({name:l,from:c.version,to:u}):a.push(l);continue}const f=" ".repeat(En(r[c.lineIndex]));r[c.lineIndex]=`${f}${l}: ${oc(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function cp(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),sc(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),ap(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 o0=">=3.0.0 <4.0.0";function cl(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 a0(t=""){const e=Jh(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Ed(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=cl(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=cl(s.version);continue}i.push(r)}return i}function l0(t){const e=new Set,n=new Set,i={},r={},s=Ed(io(t),i,e),o=Ed(t0(t,"dependency_overrides"),r,n),a=[...s,...o],l=new Set([...Object.keys(i),...e]),{sdk:u}=lp(t);return{sdkConstraint:cl(u)||o0,dependencies:i,dependencyOverrides:r,sdkPackages:[...e].sort(),sdkOverrides:[...n].sort(),availablePackages:l,unrepresentable:a,unrepresentableOverrides:o}}function c0(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 u0(t,e){const{sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o,availablePackages:a,unrepresentable:l,unrepresentableOverrides:u}=l0(e),c={sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o},d=[],f=[],p=[];for(const h of t){const{className:g,content:m}=h,v=ec(m),b=Jh(m).some(x=>x.startsWith("package:"));if(l.length>0&&b){const x=v.filter(T=>l.includes(T));let I;if(x.length>0)I=`${g} was not compiled before deploying: it imports or exports ${x.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`;else{const T=l.filter(P=>!u.includes(P)),S=[T.length>0?`your project's pubspec.yaml declares ${T.join(", ")} from a source that cannot be reproduced outside it`:null,u.length>0?`your project's dependency_overrides redirects ${u.join(", ")} to a source that cannot be reproduced outside it`:null].filter(Boolean).join(", and ");I=`${g} was not compiled before deploying: ${S}, and an entry like that can change what every package depending on it resolves to - including packages this class reaches transitively - so package resolution could not be matched exactly.`}f.push({className:g,reason:I});continue}const{unresolvableImports:w}=a0(m),_=v.filter(x=>!a.has(x));if(w.length>0||_.length>0){f.push({className:g,reason:c0(g,w,_)});continue}d.push({fileName:`${Ql(g)}.dart`,content:m})}return{manifest:c,sources:d,skipped:f,approximate:p}}function Sd(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=up(s);o&&r.push(o)}return{events:r,buffer:i}}function d0(t){const e=up(t);return e?[e]:[]}function up(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 Ne=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),dp=84e4,fp=1e4;function hp(t){return t?.unconfirmed===!0||t?.outcome===Ne.UNCONFIRMED?Ne.UNCONFIRMED:t?.partial===!0||t?.outcome===Ne.PARTIAL?Ne.PARTIAL:t?.success===!0?Ne.COMMITTED:Ne.FAILED}class We extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Ne.UNCONFIRMED}}function xd({httpStatus:t}={}){return new We(`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 f0(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}if(u.event==="result"){r=u;return}u.event===void 0&&typeof u.success=="boolean"&&(r=u)};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const p=Sd(o,c.decode(f,{stream:!0}));o=p.buffer,p.events.forEach(a)}}else{const u=Sd("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return d0(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 h0=new Set(["connected","workspace_init","workspace_ready","verifying"]);function pp(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?h0.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Id(t){if(t?.finalResultReceived){const e=hp(t);return e===Ne.FAILED&&!pp(t)?Ne.UNCONFIRMED:e}return t?.httpRejected&&typeof t.httpStatus=="number"&&t.httpStatus>=400&&t.httpStatus<500?Ne.FAILED:Ne.UNCONFIRMED}function p0(){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,p,h,g,m,v;function b(V,z){if(!i)return null;const D=i.createShader(V);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const V=b(i.VERTEX_SHADER,o),z=b(i.FRAGMENT_SHADER,a());if(V&&z&&(l=i.createProgram(),i.attachShader(l,V),i.attachShader(l,z),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),p=i.getUniformLocation(l,"parallax"),h=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function w(V){if(!V)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(V);if(z){let D=z[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const he=D.getContext("2d");he.fillStyle="rgb(9, 8, 7)";const Pe=String(he.fillStyle);he.fillStyle=V;const Te=String(he.fillStyle);if(Te===Pe)return null;const mt=/^#([0-9a-f]{6})$/i.exec(Te);if(mt){const vt=mt[1];return[parseInt(vt.slice(0,2),16)/255,parseInt(vt.slice(2,4),16)/255,parseInt(vt.slice(4,6),16)/255]}const Wt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Te);if(Wt)return[Number(Wt[1])/255,Number(Wt[2])/255,Number(Wt[3])/255]}catch{}return null}function _(){let V="";try{const z=getComputedStyle(document.documentElement);V=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return w(V)||[.56,.68,.88]}const x=_();let I=1920,T=1080,S=960,P=540,R=960,L=540,$=.66,O=0,J=-1e9,G=!1,M=0,K=0,ie=null,B=!1,Z=!1,se=!1;const Ce=64,Q=15.2;let ue=0,ye=0;const je=.0032,St=0,_e=.56,tt=.26,xt=.32,Cn=.16,Le=.349;let Re=St;function Dt(){const V=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!V.width||!z||!D)return;const he=Math.min(window.devicePixelRatio||1,2),Pe=Math.max(.2,Math.min(2,V.width/z*he)),Te=Math.max(2,Math.round(z*Pe)),mt=Math.max(2,Math.round(D*Pe));(Te!==t.width||mt!==t.height)&&(t.width=Te,t.height=mt,i&&i.viewport(0,0,Te,mt)),I=z,T=D,G||(S=R=I/2,P=L=T/2,G=!0)}function Zn(V){!l||!B||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,S,P),i.uniform1f(f,$),i.uniform1f(p,O),i.uniform2f(v,Math.cos(Re),Math.sin(Re)),i.uniform1f(h,V),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Ke(V,z,D){const he=Math.max(0,Math.min(1,(D-V)/(z-V)));return he*he*(3-2*he)}function Xn(V){if(!ie||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/I;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const he=Math.min(I,T),Pe=Math.max(64,Math.min(118,he/10)),Te=Pe*2.9,mt=2*Te*Te,Wt=Math.sin(V*.11)*7,vt=Math.cos(V*.09)*7-O,Mr=S+Wt,$r=P+vt,Fo=Te*Math.sqrt(2*Math.log(1/.06)),Fi=Fo+je*Fo*Fo+Pe,Ig=Math.floor((Mr-Fi)/Pe)-1,kg=Math.ceil((Mr+Fi)/Pe)+1,Cg=Math.floor(($r-Fi)/Pe)-1,Pg=Math.ceil(($r+Fi)/Pe)+1;for(let Ro=Cg;Ro<=Pg;Ro++){const Ag=(Ro+.5)*Pe;for(let To=Ig;To<=kg;To++){const Mo=(To+.5)*Pe-Mr,$o=Ag-$r,Lo=Math.sqrt(Mo*Mo+$o*$o)+1e-5;if(Lo>Fi)continue;const Lr=(-1+Math.sqrt(1+4*je*Lo))/(2*je),qc=Math.exp(-(Lr*Lr)/mt),zc=Ke(.06,.8,qc)*$*.26;if(zc<.004)continue;const gn=Pe/(1+2*je*Lr)*.26*(.32+1.1*qc),Vc=Lr/Lo,No=Mr+Mo*Vc,Oo=$r+$o*Vc;No<-gn*1.6||No>I+gn*1.6||Oo<-gn*1.6||Oo>T+gn*1.6||(z.globalAlpha=zc,z.save(),z.translate(No,Oo),z.rotate(Re),z.drawImage(ie,-gn,-gn,gn*2,gn*2),z.restore())}}z.globalAlpha=1}function jt(V){if(!Z)return;const z=K?Math.min(.05,(V-K)/1e3):.016;K=V;const he=V-J>2400?.6:1;$+=(he-$)*Math.min(1,z*3.2);const Pe=Math.min(.05,z);ue+=((R-S)*Ce-ue*Q)*Pe,ye+=((L-P)*Ce-ye*Q)*Pe,S+=ue*Pe,P+=ye*Pe,O=(window.scrollY||window.pageYOffset||0)*.55;const Te=V/1e3,mt=S/(I||1)-.5,Wt=P/(T||1)-.5;let vt=mt*(mt>=0?_e:tt)+Wt*(Wt>=0?xt:Cn);vt>Le?vt=Le:vt<-Le&&(vt=-Le),Re=St+vt-O*6e-4,Dt(),i?Zn(Te):Xn(Te),M=requestAnimationFrame(jt)}function Ut(V){if(!Z)return;const z=t.getBoundingClientRect();!z.width||!I||!T||(R=(V.clientX-z.left)/z.width*I,L=(V.clientY-z.top)/z.height*T,J=performance.now())}function ut(){Z||Ao||e.matches||n.matches||!se||document.hidden||(Z=!0,K=0,M=requestAnimationFrame(jt))}function Ht(){Z=!1,M&&(cancelAnimationFrame(M),M=0),K=0}function Ai(){e.matches?(Ht(),t.classList.remove("is-ready")):se&&ut()}function Qn(){n.matches?Ht():se&&ut()}function Uc(){document.hidden?Ht():se&&ut()}const Hc=new IntersectionObserver(V=>{se=V[0]?.isIntersecting||!1,se?ut():Ht()},{threshold:0});Hc.observe(t),window.addEventListener("pointermove",Ut,{passive:!0,capture:!0}),window.addEventListener("resize",Dt),e.addEventListener("change",Ai),n.addEventListener("change",Qn),document.addEventListener("visibilitychange",Uc);function xg(){const V=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(V&&window.Path2D){const he=Math.min(8.533333333333333,8.421052631578947);D.setTransform(he,0,0,he,he+(256-30*he)/2,-6.4*he),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(V),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const he=D.getImageData(0,0,256,256),Pe=he.data;for(let Te=3;Te{V.persisted?Ht():Wc()}),window.addEventListener("pageshow",V=>{V.persisted&&ut()}),{dispose:Wc,isRunning:()=>Z}}const g0=120;function m0(t,e,n){return tn?n:t}function pe(t,e,n){return m0((t-e)/(n-e),0,1)}function v0(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function pa(t){return 1-Math.pow(1-t,3)}function Ye(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 kd(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function re(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(pe(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=re(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),h=re(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ye}]),d=re(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ye},{t:10.6,v:0}]),p=re(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ye}]),o=re(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=re(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=pe(_,.45,2.2);a=x>0?-2.6*(1-kd(x)):0,g=re(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=pe(_,.67,2.42);f=I>0?-2.6*(1-kd(I)):0,s=1-.05*(Math.sin(pe(_,1.9,2.5)*Math.PI)+Math.sin(pe(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[re(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}]),re(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 w=x;const _=t-60,I=1-pe(_,12,14),T=x(pe(_,0,12)),S=x(pe(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(S[0]-T[0])*.6*I,a=(S[1]-T[1])*.6*I,p=(S[0]-T[0])*30*I,b=pe(_,0,.4)*I}else if(t<85.4){const _=t-74,x=re(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ye},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=re(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ye},{t:11.4,v:0}]),p=-l*.7,a=re(_,[{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=pe(_,0,5.6),I=pe(_,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,p=x*360*(1-I);const S=re(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:pa},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*S,d+=.16*S,l=-6*S,p+=6*S,s=1+.05*S,m=1+.9*S}else if(t<108.6){const _=t-96.4,x=pe(_,9.6,12.2);n=re(_,[{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(pe(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,h=1-.12*I,l=I*8,p=-I*8,o=.06*I,d=-.06*I,b=pe(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(pe(_,0,8)*Math.PI),I=1-pe(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(pe(_,0,6)*Math.PI),v=1+.1*Math.sin(pe(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=b,e}function y0(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=g0;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function p(M){const K=Math.min(1,Math.max(0,M.x))*c,ie=M.y*d;n.style.transform="translate3d("+K.toFixed(2)+"px,"+ie.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("+K.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,b=!1,w=!1,_=0;function x(){return w||a.matches||document.hidden||!e.offsetParent?!1:b}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){S();return}const K=g?(M-g)/1e3:0;g=M,h=(h+Math.min(K,.1))%l,_+=1,p(Hi(h))}function T(){v||w||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function S(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():S()}function R(){a.matches?(S(),p(Hi(0))):P()}function L(){f(),v&&p(Hi(h))}function $(){g=0,P()}const O=new IntersectionObserver(M=>{b=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});O.observe(e),window.addEventListener("resize",L),a.addEventListener("change",R),document.addEventListener("visibilitychange",$);function J(){w||(w=!0,S(),O.disconnect(),window.removeEventListener("resize",L),a.removeEventListener("change",R),document.removeEventListener("visibilitychange",$))}window.addEventListener("pagehide",M=>{M.persisted?S():J()}),window.addEventListener("pageshow",M=>{M.persisted&&P()});function G(M){h=(M%l+l)%l,p(Hi(h))}return f(),p(Hi(0)),P(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:G,dispose:J}}const _0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ln(t){const e=String(t||"").trim().match(_0);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function w0(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 E0(t){const e=ln(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ac(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 ln(o)?{min:o,minInclusive:!0,max:E0(o),maxInclusive:!1}:null}if(ln(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(!ln(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Cd(t,e){const n=ac(t);if(!n||!ln(e))return!1;if(n.min!==null){const i=Ls(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=Ls(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function S0(t,e){const n=ac(t);if(!n||!ln(e))return!1;if(n.max===null)return!0;const i=Ls(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ri(t){const e=ac(t);return e?e.min:null}const x0="https://pub.dev/api/packages/",I0=8e3;function k0(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||b0(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Cd(l.sdk,n)||i&&l.flutter&&!Cd(l.flutter,i)||(!s||Ls(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function C0(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${x0}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(I0)});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=k0(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 P0(t,e={}){const n=await Promise.all(t.map(i=>C0(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function A0(t,e={},n={}){const{resolveVersions:i=P0}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=lp(t),o={dartSdkFloor:ri(s.sdk),flutterSdkFloor:ri(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=io(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(zy.has(d)?c:u).push(d);continue}const h=ri(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:d,constraint:p.constraint});continue}if(S0(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(ri(h)){a.additions[f]=`^${ri(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${ri(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const F0={"&":"&","<":"<",">":">",'"':""","'":"'"};function cn(t){return String(t??"").replace(/[&<>"']/g,e=>F0[e])}function W(t){return t?cn(t).replace(/\n/g,"
    "):""}function on(t){return cn(t).replace(/\r?\n/g," ")}function ro(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 mp(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 R0(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 T0(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 M0(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 Si(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 Pd(t){return t=cn(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 vp(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=Si(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 cn(i)}}}function so(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=M0(o),u=vp(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+=`
    +

    + ${R0(l)} + ${cn(l)} +

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

    + ${T0(l)} + ${cn(l)} +

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

    ${Pd(a)}

    `)}return i+="
    ",` +
    +
    +
    + Live Audit Report +
    + ${i} +
    + `}const $0=5200,L0=73,N0=1600,O0=35,ga=new WeakMap;function Ad(t,e){return!!(t&&t.trim())&&!e}function B0({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=Array.from(document.querySelectorAll("#example-chips .chip")),o=document.getElementById("btn-add-images"),a=document.getElementById("prompt-image-input"),l=window.matchMedia("(prefers-reduced-motion: reduce)");let u=!1,c=!1,d=!1,f=!1,p=!1,h=null,g=null;const m=n.dataset.demoPrompt||"";function v(){return c||d||f||p}function b(){i.disabled=!Ad(n.value,v())}function w(){r&&(r.textContent=n.value)}function _(B){c=B,e.classList.toggle("is-busy",B),i.classList.toggle("is-busy",B),i.setAttribute("aria-label",B?"Generating":"Generate"),n.readOnly=B,s.forEach(Z=>{Z.disabled=B}),o&&(o.disabled=B),a&&(a.disabled=B),b()}async function x(){if(Ad(n.value,v())){_(!0);try{await t()}finally{_(!1)}}}function I(){f&&(f=!1,g&&(clearTimeout(g),g=null),e.classList.remove("is-demo-typing","is-demo-keying"),n.placeholder="Describe the widget or action you need",b())}function T(){if(l.matches||!m.trim())return;const B=window.location.hash.replace(/^#/,"");if(B&&B!=="home")return;f=!0,n.placeholder="",n.value="",w(),b(),e.classList.add("is-demo-typing");let Z=0;const se=(ue,ye)=>{Z+=ue,n.value=m.slice(0,Z),w(),e.classList.toggle("is-demo-keying",ye)},Ce=()=>{f&&(se(-1,!0),Z>0?g=setTimeout(Ce,O0):I())},Q=()=>{if(!f)return;const ue=Z+1B.classList.contains("is-active"))?.dataset.prompt||n.value,w(),R())}function $(){s.forEach(B=>{B.classList.remove("is-active"),B.setAttribute("aria-pressed","false")})}function O(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function J(B){const Z=B.dataset.prompt||"";if(I(),R(),s.forEach(Ce=>{const Q=Ce===B;Ce.classList.toggle("is-active",Q),Ce.setAttribute("aria-pressed",String(Q))}),l.matches||!Z){n.value=Z,w(),b(),O();return}n.value="",w(),d=!0,b(),e.classList.add("is-demo-typing","is-demo-keying");let se=0;h=setInterval(()=>{se+=1,n.value=Z.slice(0,se),w(),se>=Z.length?(R(),O()):b()},22)}s.forEach(B=>{B.setAttribute("aria-pressed","false"),B.addEventListener("click",()=>J(B))}),n.addEventListener("keydown",B=>{if((f||d)&&B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u){B.preventDefault();return}S(),L(),B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u&&(B.preventDefault(),x())}),n.addEventListener("beforeinput",()=>S()),n.addEventListener("input",()=>{I(),R(),$(),w(),b()}),n.addEventListener("compositionstart",()=>{u=!0}),n.addEventListener("compositionend",()=>{u=!1,b()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),i.addEventListener("click",x),n.addEventListener("pointerdown",()=>{S(),L(),$()}),n.addEventListener("focus",()=>S());const G=ga.get(e);G&&G.mql.removeEventListener("change",G.handler),l.addEventListener("change",P),ga.set(e,{mql:l,handler:P});function M(){K(),l.removeEventListener("change",P),ga.delete(e),document.removeEventListener("visibilitychange",ie)}function K(){S(),L()}function ie(){document.hidden&&K()}return document.addEventListener("visibilitychange",ie),w(),b(),T(),{setAttachmentsPending(B){p=!!B,b()},dispose:M,cancelTyping:K}}const mr=window.matchMedia("(prefers-reduced-motion: reduce)");let fi=null,Jt=null;const Ns=new Map;function yp(){for(const[t,e]of Ns)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Ns.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Gn(){if(yp(),fi){const t=fi;fi=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Jt&&(Jt.animation.cancel(),Jt.hero.classList.remove("is-exiting"),Jt.hero.style.cssText=Jt.style,Jt=null)}function D0(t){return(fi?.ghost||t)?.getBoundingClientRect()}function j0(t){yp(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",mr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Ns.delete(e))}Ns.set(e,i),e.addEventListener("animationend",i)})}function U0(t,e){if(!t||!e||mr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Jt={hero:t,animation:i,style:n},i.onfinish=()=>{Jt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Jt=null)}}function _p(t,e,n,{results:i=!1}={}){if(Gn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,j0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(mr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};fi=h,p.onfinish=()=>{fi===h&&(Gn(),s())}}window.addEventListener("resize",Gn);window.addEventListener("pagehide",Gn);document.addEventListener("visibilitychange",()=>{document.hidden&&Gn()});mr.addEventListener("change",()=>{mr.matches&&Gn()});const Fd="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",H0="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",W0="https://us.i.posthog.com";Nh.init(H0,{api_host:W0,person_profiles:"identified_only"});function Dn(t,e={}){try{Nh.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const Et="https://4tgke4.buildship.run",wp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Os="ccc_auth_session",ul="ccc_signin_return",q0=1800*1e3,Rd=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=Kn({isResolved:!0}),dl=Promise.resolve();const z0=`${Et}/service/runpipeline`,V0="bs_user_id",G0="bs_identity_token",K0=`${Et}/authUserCheck`;let yt={userId:null,token:null,status:null,resolved:!1};const Bs=oy,Ds="ccc_subscription",Td=3,Y0=new Set(["active","trialing","paid"]),js="google/gemini-3.7-flash",rs=["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"],J0={"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 nn(t){return J0[t]||t}const Z0=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 bp(t){return Z0.has(t)}const fl=4,ma=8*1024*1024,X0="https://4tgke4.buildship.run/service/runpipeline-image";let De=[];const Sn=[],Q0=3e4;let lc=null;function ew(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function tw(t,e){const n=new FormData;return n.append("file",t),(await fetch(X0,{method:"POST",body:n,signal:e})).json()}function nw(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 iw(t,e,n){const i=await ew(t,n);i&&De.includes(e)&&(e.dataUrl=i,yn());let r="";if(i)try{r=nw(await tw(t,n))}catch{r=""}return De.includes(e)?!i||!r?(De.splice(De.indexOf(e),1),yn(),"failed"):(e.url=r,yn(),"added"):"dropped"}function Ep(t){const e=Sn.indexOf(t);e>=0&&Sn.splice(e,1),xp()}function Sp(t){t.controller.abort(),Ep(t);const e=De.indexOf(t.slot);e>=0&&(De.splice(e,1),yn())}function xp(){lc?.setAttachmentsPending(Sn.length>0)}async function rw(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Se("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>ma);n.length&&Se(`Skipped ${n.length} image(s) over the ${(ma/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ma);if(!i.length)return;const r=fl-De.length,s=i.slice(0,r);if(i.length>r&&Se(`You can attach up to ${fl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};De.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Q0);return d.job=iw(u,c,d.controller.signal),Sn.push(d),d.job.finally(()=>{clearTimeout(f),Ep(d)}),d.job});yn(),xp();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Se(`${l} image(s) could not be uploaded and were not attached.`,"error")}function sw(t){if(y.isRunning){Se("Wait for the current generation to finish before removing images.","info");return}const e=De[t],n=Sn.find(i=>i.slot===e);if(n){Sp(n);return}De.splice(t,1),yn()}function yn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",De.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=De.length>=fl?"Image limit reached":"Add images"))}function cc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=bp(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(Sp),De=[],yn())}const Wn="ccc_usage",Ip="google/gemini-3.7-flash",kp="google/gemini-3.7-flash",Kr="google/gemini-3.7-flash",Ji={professional:11,power:49},hl={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"},ss={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 os={...ss};async function ow(){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(ss),...Object.values(pl),...Object.values(hl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:ss[a]&&(s[a]=ss[a]));os=s}catch{}finally{clearTimeout(e)}}const pl={"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 uc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&pl[s])return pl[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=hl[e];if(n)return n;const i=e.split("_")[0],r=hl[i];return r||"USD"}function Zi(t,e){const n=os[e]??os.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*os.USD)}}const _t="ccc_api_key_",Tt="ccc_session_api_key_",Nt="ccc_encryption_key",vr="ccc_encryption_key_scope",aw="ccc_keystore",Us="keys",yr="ccc_encryption_key_version";let gl=null,Hs=null,_r=!1,Ws=!1,Md=!1;class qs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function $d(){if(Md)return;Md=!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&&Se(t,"warning")}function Cp(){return localStorage.getItem(yr)||""}function ml(){return crypto.randomUUID?.()||Ap(crypto.getRandomValues(new Uint8Array(16)))}function lw(){const t=Cp();if(t)return t;const e=ml();return localStorage.setItem(yr,e),e}function xi(){gl=null,Hs=null,_r=!1,Ws=!1}window.addEventListener("storage",t=>{t.key===yr&&xi()});function cw(){return new Promise((t,e)=>{const n=indexedDB.open(aw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Us)||i.createObjectStore(Us)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function dc(t,e){const n=await cw();return new Promise((i,r)=>{const s=n.transaction(Us,t);let o;try{o=e(s.objectStore(Us))}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 uw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function dw(){const t=await dc("readonly",e=>e.get(Nt));return uw(t)?t:null}async function Pp(t){await dc("readwrite",e=>e.put(t,Nt))}async function fw(){xi();try{await dc("readwrite",t=>t.delete(Nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function hw(){const t=sessionStorage.getItem(Nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(e),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),e}async function Ld(t){const e=sessionStorage.getItem(Nt);if(e)return Ws=sessionStorage.getItem(vr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new qs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Nt,JSON.stringify(i)),sessionStorage.setItem(vr,"session"),Ws=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function pw(t){if(sessionStorage.getItem(vr)==="session"&&sessionStorage.getItem(Nt))return $d(),_r=!0,Ld(t);try{const e=await dw();if(e)return e;const n=await hw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),$d(),_r=!0,Ld(t)}}async function fc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=lw();Hs!==n&&xi();const i=gl||pw(e);gl=i,Hs=n;try{return await i}catch(r){throw xi(),r}}async function gw(t){const e=await fc(),n=Hs,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:Ap(o),keyVersion:n,sessionFallback:_r}}async function mw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await fc({allowSessionFallbackCreation:!1});if(_r&&!n&&!Ws)throw new qs;const r=vw(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 qs)throw i;return console.error("Decryption failed:",i),null}}function Ap(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let ke="",Mt="",sr=null,Od=0,ot="not-configured",gt=0,vl=0,yl=0,oo=0,Zt=0,un=0,Xe=null,$t=null,wr=null;function _w(){return vl+=1,vl}function ww(){return yl+=1,yl}function br(t,e,n){Xe=t?{projectId:t,key:e,generation:n}:null}function _l(t,e=ke){if(!t)return!1;const n=Xe;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function hc(t,e,n){if(!Mt||Xe&&Xe.projectId!==Mt)return;(t||[]).some(r=>(r.id||r.projectId)===Mt)?br(Mt,e,n):Xe&&br("",null,null)}function Fp({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===ke||r===ke}async function pc(){sessionStorage.getItem(Nt)&&await fc(),ke=await Me("flutterflow"),Mt=await Me("flutterflow_project_id"),kw(),pn(),ke?yc():(ot="not-configured",bt())}let Er=!1;function Rp(){const t=document.getElementById("api-keys-modal");Ve(t),vc(),ke&&co(ke)}function gc(){Er=!1,Rp()}function bw(){Er=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Rp()}let Bd=!1;function Dd(){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 jd(){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=nn(t.value),r=bp(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.`),cc()}function Tp(){if(Er=!1,Dd(),jd(),!Bd){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")),Dd(),jd()}),Bd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function Ew(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Mp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=Er;if(Er=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&mc(),Ve(i))}}let dn=1;function $p(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function ao(){const t=$p();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,ao())}function Sw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,ao(),Ve(t))}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Lp(){if(H.isVerified&&Ot()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,ao(),Ve(e))}}async function vc(){const t=document.getElementById("flutterflow-api-key-input");ke?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Iw()}function Iw(){Ud("flutterflow","flutterflow-key-status"),Ud("flutterflow_project_id","flutterflow-project-status")}function Ud(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ft(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function kw(){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"?Ft("flutterflow")&&Ft("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ft("flutterflow")||Ft("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)"):Ft(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)")}),pn()}async function Cw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==ke,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await Nd("flutterflow",n),n!==l&&!r&&as()}const s=n||ke;if(r){if(!lo(r)){Se("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}_l(r,s)?await Nd("flutterflow_project_id",r):(i?as():Xe=null,e.value="",s&&!($t&&$t.key===s&&$t.generation===gt)&&co(s))}else i&&as();await pc(),n&&await yc(),vc();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Mp()},1e3)}async function Pw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(yr,ml()),xi(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),await fw(),localStorage.setItem(yr,ml()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),Xe=null,$t=null,wr=null,await pc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),vc()}function lo(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Mt||"—"),!e)return;let r,s;if(!Ft("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 yc(){const t=ww(),e=++oo,n=gt,i=ke,r=await Me("flutterflow"),s=()=>Fp({seq:t,currentSeq:yl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Ft("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&hc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function as(){Mt="",Xe=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow_project_id")}function Aw(){gt+=1,$t=null,wr=null,as();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ft("flutterflow")?(ot="validating",co(ke)):ot="not-configured",bt()}function Fw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Rw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Fw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Tw(async n=>{const i=n.target.value.trim();i&&await co(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&$t?br(n,$t.key,$t.generation):br("",null,null)})}function Tw(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function co(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=_w(),r=++oo,s=gt,o=ke,a=()=>Fp({seq:i,currentSeq:vl,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};$t=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===ke&&(Ft("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;$t={key:t,generation:s};const f=t===ke,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,hc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Mt&&(e.value=Mt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===ke&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Mw(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 $w(){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 Lw(){y.bundleSpec=pr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function uo(){const t=bi(y.bundleSpec);y.artifactBundle=pr(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=Uy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=bi(y.artifactBundle).id}function fo(){const t=pr(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=pr({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Np(){const t=_c();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _c(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||bi(t)}function wc(){return _c().code||y.step2Result||""}async function Nw(){try{await pc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const ls={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Ow(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 In{constructor(e,n,i="main",r=ls.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=[ls.production,ls.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(wl(f?d.clone():d,fp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 xd({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(Ow(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 wl(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 bc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Bw(t,e=fp){const n=t.clone();let i;try{i=JSON.parse(await wl(t,e))}catch{let o="";try{o=await wl(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 ho(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 X={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Op=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Bp=/extends\s+State<\w+>/;function Dw(t,e=""){if(t==="pubspec.yaml")return X.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return X.OTHER;if(t==="custom_functions.dart")return X.FUNCTION;if(e){const n=Op.test(e),i=Bp.test(e);if(n||i)return X.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return X.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return X.FUNCTION}return X.CODE_FILE}function Dp(t,e){switch(e){case X.ACTION:return`lib/custom_code/actions/${t}`;case X.WIDGET:return`lib/custom_code/widgets/${t}`;case X.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case X.CODE_FILE:return`lib/custom_code/${t}`;case X.DEPENDENCIES:return"pubspec.yaml";case X.OTHER:return`lib/custom_code/${t}`;default:return t}}async function po(t,e=new Map){return Sy(t,e)}const bl=new Map,hi=new Map,pi=new Map;function Cr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){bl.delete(Cr(t))}function Xi(t,e,n){const i=Cr(t),r=hi.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?hi.delete(i):hi.set(i,r)}function jw(t,e){Xi(t,e,{uncertain:1})}function Uw(t){const e=Cr(t);pi.set(e,(pi.get(e)??0)+1)}function Hd(t){const e=Cr(t),n=(pi.get(e)??0)-1;n<=0?pi.delete(e):pi.set(e,n)}function bc(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 go(t,e,n=dp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Bw(s)})();return bc(r,n,(s,o)=>{i.stop=!0,Yn(t),Uw(t),r.then(()=>Hd(t),()=>Hd(t)),o(new We("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 Hw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=s_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function Ec(t,e,n,i,r="",s=dp){const o=r_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=b_();let l=!1;const u=u0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch(Fd,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 f0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await bc(g,s,(m,v)=>{p=!1,v(new We("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(Id(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Id(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Yn(t),jw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Xi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&pp(w)&&Xi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await P_({provisionEndpoint:Fd,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Xi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await Hw(t,o,m);throw o_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Yn(t),Xi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Sc(t,e={}){const n=Cr(t);let i=bl.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=cp(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=hi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&hi.delete(n)}!hi.has(n)&&!pi.has(n)&&bl.set(n,i)}const r=await A0(i.pubspecYaml,e),s=s0(i.pubspecYaml,r.overrides),o=r0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Ww(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===X.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=L_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===X.WIDGET){const o=Xh(t.content),a=T_(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=`${Qh(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 jp(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=F_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Xh(s)[0],c=u?Qh(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=X.CODE_FILE;switch(n){case"CustomAction":a=X.ACTION;break;case"CustomWidget":a=X.WIDGET;break;case"CustomFunction":a=X.FUNCTION;break;case"CustomClass":case"CodeFile":a=X.CODE_FILE;break}let l="";return a===X.WIDGET?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom widget code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===X.ACTION?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom action code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===X.FUNCTION&&(l=`// Automatic FlutterFlow imports +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:timeago/timeago.dart' as timeago; +import '/flutter_flow/lat_lng.dart'; +import '/flutter_flow/place.dart'; +import '/flutter_flow/uploaded_file.dart'; + +`),{content:qy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function qw(t){const e={};for(const n of ec(t))e[n]="";return e}function zw(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 Vw(t,e,n,i=new Set,r=""){const s=[],o=Op.test(e),a=Bp.test(e);return n===X.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function mo(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=>eo(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=Vw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=cp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function xc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(_l(n,e))return n;const i=++oo,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==ke||i<=un||(un=i,!s)?"":Xe&&Xe.projectId!==n&&_l(Xe.projectId,e)?Xe.projectId:((!Xe||Xe.projectId===n)&&br(n,e,r),n)}async function Gw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=X.WIDGET),i==="CustomAction"&&(i=X.ACTION),i==="CustomFunction"&&(i=X.FUNCTION),i==="CustomClass"&&(i=X.CODE_FILE),i==="CodeFile"&&(i=X.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await xc(o);if((o!==ke||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!lo(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||Dw(e,t),f=Dp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=mo(c);if(!p.valid)throw new Error(`Validation failed: +${p.errors.join(` +`)}`);const h=await Sc(u,r),g=h.yaml,m=await Ec(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await po(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await vo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Yn(u),$e.set("push");const x=await go(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||ho(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function vo(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 Kw(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=jp(t,{artifactType:n,artifactName:i,fileName:r}),u=qw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=sr||await xc(c);if((c!==ke||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Dp(l.fileName,l.codeType),functionName:l.codeType===X.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=mo(h);if(!g.valid)throw new Error(`File validation failed: +${g.errors.join(` +`)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),Y.setState(ne.PUSHING);const m=new In(c,p,"main",d),v=await Sc(m,u),b=v.yaml,w=await Ec(m,h,v.remoteFiles,`Provision ${i} custom class`,b);o=w.provisionSucceeded===!0;const _=await po(w.syncFileMap,w.remoteFiles),x=new Map(w.syncFileMap);x.set("pubspec.yaml",{content:b,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const I=await vo(x),T={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:b,file_map:_.fileMapContents,functions_map:_.functionsMapContents};Y.setProgress(1,h.size),Yn(m),$e.set("push");const S=await go(m,T);if(S.success){const P={...zw(l,s),projectId:p};return Y.setSuccess({...P,fileCount:h.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:w.unverified,approximate:w.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=S.errorMessage||ho(S.responseCode),R=new Error(P);throw R.errorMap=S.errorMap,R.remoteRefusal=!0,R}}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 We?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...l.finishDeploy?{finishDeploy:cg(l.finishDeploy,a,Y)}:{}}: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,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function Yw(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:ze(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ne.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===X.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=mo(s);if(!o.valid)throw new Error(`File validation failed: +${o.errors.join(` +`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=sr||await xc(a);if((a!==ke||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Sc(d,t.dependencies),p=f.yaml,h=await Ec(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await po(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await vo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Yn(d),$e.set("push");const w=await go(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||ho(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:cg(s.finishDeploy,r,Y)}:{}}: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 Jw(t,e=[]){const n=Jl("architect");try{return await Gs("architect",Ip,dy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function yo(t,e,n=[],i){const r=fy(t),s=Jl("generator",y.bundleSpec);try{return await Gs("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),tE(e,Kr,i);try{return await Gs("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 _o(t,e=null){const n={...Jl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Gs("review",kp,hy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function zs(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=` + + `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` + + `):i.innerHTML=` + + `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),zs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),zs(t,"completed"))}function Zw(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 Xw(t){at(parseInt(t.replace("step","")))}function at(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"),Jn();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 Qw(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 El(t){const e=Sl(t);console.log(`Step 1 (Prompt Architect): ${nn(Ip)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(kp)}`)}function Up(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function eb(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=bi(y.artifactBundle)?.id||null)}const Hp="results-replacement-error";function tb(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Hp);if(!r)return;const s=mp(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=`${So[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=()=>Ii(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Ic(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Ic(){const t=document.getElementById(Hp);t&&(t.hidden=!0)}function Wp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),eb(e),Pi(),Bt(!0),Tr(),y.resultsViewMode=e.resultsViewMode||"summary",Rr(),kn(),tb(t,{stage:n,runId:i,retry:r}),pn())}async function qp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=xo();kc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Up();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + + + Refining...`});try{Ic();const r=_c(),s=r.id,o=py({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."});Co({runId:e}),Lt(2,e),at(2),Fe(2,!0);const a=await yo(o,t,[],e);if(!le(e))return;y.step2Result=a,uo(),fn(2,e);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,e),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,fo(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=bi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=ro(r,{architect:2,generator:2,review:3});Wp(r,{previous:i,stage:s,runId:e,retry:qp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function kc(t,e,n){const i=`${Et}/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 nb(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function zp(){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){Se("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=xo();kc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + + Fixing…`);const s=Up();try{Ic();const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});bg(),Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=ro(o,{architect:2,generator:2,review:3});Wp(o,{previous:s,stage:a,runId:i,retry:zp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}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=De.slice();if(!t.trim()){Se("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=xo();try{if(await dl,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await kb()||!le(i)||(await wb(),!le(i)))return;const r=Sl(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),$w(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Ys(!0),El(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Co({prompt:t,runId:i}),sE(a,l),at(1),Lt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await Jw(t,u);if(!le(i))return;y.step1Result=c,Lw(),fn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=Si(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Lt(2,i),Fe(2,!0);const p=await yo(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,uo(),fn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=Si(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const m=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,fo(),fn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Pi();const b=so(y.step3Result);Tr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=ro(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():Dn("Pipeline Failed",{error:r.message,effectiveModel:Sl(document.getElementById("code-generator-model").value)}),at(s),Fe(s,!1),vg(r,{stage:s,runId:i}),zs(s,"error")}finally{le(i)&&(y.isRunning=!1,Ys(!1),pn())}}function ib(){const t=document.getElementById("code-generator-model").value,e=[js,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + +Current: ${t} + +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 rb(){const t=wc();if(!t){Se("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}if(y.artifactBundle?.artifacts?.length>1){await sb();return}const{artifactType:i,artifactName:r,fileName:s}=Np(),o=jp(t,{artifactType:i,artifactName:r,fileName:s}),a=Ww(o);if(!a.canProceed){Se(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Ac(o,a,null,null)}async function sb(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}const n=e_(y.artifactBundle);if(n.errors.length>0){Se(`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=mo(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Se(`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};Ac(o,s,n.dependencies,n)}function ob(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    +

    FlutterFlow Commit Failed

    +

    ${W(t.error)}

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

    Errors:

    +
      `;for(const[r,s]of e.entries()){const o=nc(s);n+=`
    • + ${W(r)}: ${W(o)} +
    • `}n+="
    "}n+="
    ",n+=`
    + +
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Vp(t.error,e)}))}async function Vp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=xo(),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[p,h]of e.entries()){const g=nc(h);s+=`File: ${p} +Error: ${g} + +`}else s+=`${t} +`;const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=ro(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),vg(s,{stage:o,runId:i,retry:()=>Vp(t,e)}),zs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function ab(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 Gp(t){try{const e=await fetch(`${Et}/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 lb(t){try{const n=await(await fetch(`${Et}/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 cb(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Wd(t,e){const n=Yp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,fe=Kn({isLoading:!0}),localStorage.setItem(Os,JSON.stringify({email:t,sessionToken:e})),i&&tg()}function Kp(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),localStorage.removeItem(Os),localStorage.removeItem(Ds)}function Yp(){try{const t=localStorage.getItem(Os);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(Os),{email:null,sessionToken:null}}}async function ub(){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 lb(e);Wd(n,i),Jp();const r=qd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){qd();const i=n.message||"Sign-in link invalid or expired.";Se(i,"error"),wo(),ci(i,"error")}}else{const{email:n,sessionToken:i}=Yp();if(n&&i){const r=await cb(i);r?Wd(r.email,r.sessionToken):Kp()}}Cc()}function db(){try{localStorage.setItem(ul,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function qd(){try{const t=localStorage.getItem(ul);if(localStorage.removeItem(ul),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>q0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function wo(){const t=document.getElementById("signin-modal");if(!t)return;db(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ci(""),Ve(t)}function Jp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function ci(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 fb(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=no(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"),ci("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ep(n);r&&ci(r,"error");try{const s=await Gp(n),o=ic(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ci(tp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ci("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function hb(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),J_({storage:window.localStorage,onIdentityChanged:Cc,onPlanChanged:Eo})}const pb=X_({sendLink:Gp,getEmail:()=>H.email||"",onState:gb});function gb(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=tp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function mb(){await pb()}function vb(){const t=K_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Se(`${e} Your run count, identity and stored keys are kept.`,"info")}function yb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function _b(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Cc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Ab(),Eo()}async function Zp(){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(K0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(V0,r.user_id),yt.token&&sessionStorage.setItem(G0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),_n()}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 va=null;function wb(t=5e3){return yt.resolved?Promise.resolve():(va||(va=Zp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([va,new Promise(e=>setTimeout(e,t))]))}function Xp(){const t=xn();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Pr(){const t=Xp();return t.month!==xn()?{count:0,month:xn()}:t}function bb(){const e={count:Pr().count+1,month:xn()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Ci(){return!!fe.isLoading}function Ot(){return!!fe.isResolved}function Eb(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(Bs,e)?e:null}function Sb(t){return t&&Object.entries(wp).find(([,e])=>e===t)?.[0]||null}function Yr(...t){return t.find(e=>e!=null&&e!=="")}function xb(...t){return t.find(e=>e&&typeof e=="object")||{}}function Ib(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=xb(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=Yr(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=Yr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=Eb(Yr(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=Y0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Sb(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Yr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function bo(){return Bs[fe.tier]??Bs.free}async function kb(){if(H.isVerified&&(!Ot()||Ci())&&(await eg({force:!0}),Eo()),H.isVerified&&!Ot())return Se("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Pr(),e=bo();if(t>=e)return Qp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Se(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function zd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Qp(t,e,n={}){Bt(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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){Se(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ii();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=fe.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",H.isVerified),u.classList.remove("hidden"),n.openModal&&Ii()}function Sl(t){return fe.tier==="free"&&rs.includes(t)?js:t}function Cb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=fe.tier,r=!(H.isVerified&&!Ot())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=rs.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&rs.includes(e.value)&&(e.value=js),e.disabled=!1,Rd.has(e)||(e.addEventListener("change",()=>{Ot()&&fe.tier==="free"&&rs.includes(e.value)&&(e.value=js,Ii()),El(e.value),cc()}),Rd.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(),El(e.value)}function Pc(){const t=H.isVerified&&!!H.email,e=t&&Ci(),n=!t||Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Yl,u=n?fe.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Xp(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Bs.free} generations used`}}Pb()}function Pb(){if(!(H.isVerified&&!!H.email))return;const e=Ci(),n=Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=n?fe.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Zi(Ji[a]??0,uc());h.textContent=`${S} / 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 S=Date.parse(fe.periodEnd||""),P=n&&a!=="free"&&!!fe.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Pc(),H.isVerified&&(Ci()||!Ot())){zd();return}const{count:t}=Pr(),e=bo();t>=e&&!y.isRunning&&!iy()?Qp(t,e):zd()}function Ab(){Pc()}async function eg(t={}){const e=t.force===!0;if(!H.isVerified||!H.sessionToken){fe=Kn({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const n=H.sessionToken,i=localStorage.getItem(Ds);if(!e&&i)try{const{data:r,email:s,ts:o,version:a}=JSON.parse(i);if(a===Td&&s===H.email&&Date.now()-o<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",i)}try{const s=await(await fetch(`${Et}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken,user_id:yt.userId})})).json();if(!H.isVerified||H.sessionToken!==n)return;if(s.error){if(["unauthorized","invalid session","expired session"].some(a=>String(s.error).toLowerCase().includes(a))){Kp(),Cc();return}fe=Kn({isResolved:!1,error:s.error});return}fe=Ib(s),localStorage.setItem(Ds,JSON.stringify({version:Td,data:fe,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function tg(){localStorage.removeItem(Ds)}async function Fb(t){if(!H.isVerified||!H.sessionToken){ig(),wo();return}if(!wp[t]){Se("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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:uc()})})).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"),Se("Could not start checkout. Please try again.","error")}}async function Rb(t){if(!H.isVerified||!H.sessionToken){wo();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Se("Could not open billing portal. Please try again.","error")}}const Vs=new Set;function ng(){Vs.forEach(t=>t.abort()),Vs.clear()}async function Gs(t,e,n,i={},r=[]){const o=new AbortController;Vs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(z0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Wn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=by(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),_n())}else bb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Vs.delete(o)}}let xl=!1;function Tb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),tg(),xl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Se("Checkout cancelled.","info")),e}function Mb(){if(!xl)return;xl=!1;const t=fe.tier!=="free";Se(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Eo(){const t=H.isVerified&&!!H.email,e=fe.tier,n=t&&Ci(),i=!t||Ot(),r=document.getElementById("subscription-tier-badge");if(r){const a=Yl,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"),$b(i?e:null),Cb(),cc(),_n(),Eg()}function $b(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 Lb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=ly[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 Il(){const t=uc(),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=Zi(Ji.professional,t)),n&&(n.textContent=Zi(Ji.power,t)),i&&(i.textContent=Zi(Ji.professional,t)),r&&(r.textContent=Zi(Ji.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ii(){Il();const t=document.getElementById("pricing-modal");t&&Ve(t),ow().then(()=>Il())}function ig(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Se(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()=>{sy(),Jb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Nb(),window.__heroField=p0(),window.__pipelineLogo=y0(),vE(),lc=B0({onSubmit:Sr}),dl=(async()=>{try{await ub(),Tb(),await eg()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await dl,Mb(),Eo(),Il(),Lb(),await Nw(),Rw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Lp(),Zp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(mc(),ao())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(dg(),$e.phaseId||Rc(),Gd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(Gd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,Tc()},1e3))}),jc()});function Nb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Ob(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Lp()}let or=null;async function kl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Od,n=++oo,i=()=>e===Od,r=gt;wr=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==ke)return kl();if(n>un&&(un=n,hc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),wr={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==ke)return kl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function Bb(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=wr;return!n||n.key!==ke||n.generation!==gt?null:e}function Ac(t,e,n,i=null){or={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,kl();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function rg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),or=null}function Db(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 sg(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function og(t){Tc(),ob(t);const e=t.remoteRefusal===!0;Fc(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 Fc(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(nc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function ag(t){Fc(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 lg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Cl=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Fc(t,{heading:e,title:n,guidance:i})}let Cl=null;function cg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function jb(){const t=Cl;if(!t||Mc)return;Cl=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);ug(),$c(!0),Rc();try{$e.set("package");const n=a_(t.fileMap,t.landed,t.serializedYaml),i=await po(n,new Map),r=await vo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),$e.set("push");const o=await go(e,s);if(o.success){Ks({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||ho(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ks({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function ug(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function Ub(){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 Vd={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}},Hb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function dg(){Un&&clearTimeout(Un),Un=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){dg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(sd(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Vd[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=Vd[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=Hb.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(Wb(e)),fg(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&&(sd(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function Wb(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 Rc(t){$e.start(t)}function Tc(){$e.stop()}function fg(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Gd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,fg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function qb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===X.CODE_FILE):t.codeInfo?.codeType===X.CODE_FILE}let Mc=!1;function $c(t){Mc=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 Ks(t){Tc(),$c(!1);const e=hp(t);e===Ne.COMMITTED?sg(t):e===Ne.PARTIAL?ag(t):e===Ne.UNCONFIRMED?lg(t):og(t)}async function zb(){if(!or){console.error("No pending commit data");return}if(Mc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=or;if(or=null,sr=Bb(),rg(),$c(!0),Rc({withProvisioning:qb(t)}),t.bundlePlan){const o=await Yw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Np(),s=await Kw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(s)}window.runThinkingPipeline=Sr;window.toggleStep=Xw;window.toggleSection=Zw;window.selectWorkflowStep=at;window.copyCode=Qw;window.retryWithDifferentModel=ib;window.openApiKeysModal=gc;window.closeApiKeysModal=Mp;window.openComposerSettings=Tp;window.closeComposerSettings=Ew;window.walkthroughConnectAccount=bw;window.closeWalkthroughModal=xw;window.openWalkthroughModal=Sw;window.advanceWalkthrough=mc;window.commitToFlutterFlow=Gw;function Vb(){y.isRunning||Bt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Gb(){Tp();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Vb;window.openModelSelector=Gb;window.handlePromptImageSelect=rw;window.removePromptImage=sw;window.saveApiKeys=Cw;window.validateFlutterFlowConnection=yc;window.clearAllApiKeys=Pw;window.toggleKeyVisibility=Mw;window.handleWelcomeVideoEnd=Ob;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=rb;window.updateFlutterFlowCredentialStatus=ab;window.openCommitConfirmModal=Ac;window.closeCommitConfirmModal=rg;window.closeCommitSuccessModal=Db;window.closeCommitTerminalModal=ug;window.finishProvisionedDeploy=jb;window.showCommitPartialModal=ag;window.showCommitUnconfirmedModal=lg;window.showCommitSuccessModal=sg;window.showCommitFailureModal=og;window.toggleCodePreview=Ub;window.confirmCommitToFlutterFlow=zb;window.runRefinement=qp;window.regenerateFromPastedErrors=zp;window.clearErrorInput=nb;window.setFlutterFlowEndpoint=yw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=wo;window.closeSignInModal=Jp;window.handleMagicLinkRequest=fb;window.handleSignOut=hb;window.handleSendNewLink=mb;window.handleClearCache=vb;window.handleDeleteAccount=yb;window.closeDeleteUnavailableModal=_b;window.startCheckout=Fb;window.openCustomerPortal=Rb;window.openPricingModal=Ii;window.closePricingModal=ig;let cs=null,hg=null,hn={1:"pending",2:"pending",3:"pending"},qn=1,Pl=null,Lc=null;const So={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Kb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Yb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function xo(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function pg(){y.runId+=1}function Nc(t){return document.getElementById(`pdot-${t}`)}const gg=window.matchMedia("(max-width: 920px)");function Kd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=gg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Jb(){Kd(),gg.addEventListener("change",Kd)}function Zb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Ys(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 Io(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){hn[t]=e;const n=Nc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=So[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 Xb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Ar(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${Qb()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function Qb(){const t=33.333333333333336,e=hn[qn];if(e==="active"&&Pl!==null){const n=(Date.now()-Pl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:Xb()/3*100}function ko(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?Yb[t]:Kb[t]),i&&(i.textContent=Zb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${So[t]}${a}`}}function eE(t){hn[t]==="pending"||hn[t]==="skipped"||(Lc=t,[1,2,3].forEach(e=>{const n=Nc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),ko(t))}function Oc(){Lc=null,[1,2,3].forEach(t=>{const e=Nc(t);e&&e.removeAttribute("aria-pressed")})}function mg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function tE(t,e,n){le(n)&&mg(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function Bc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function nE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Gn()}function iE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function rE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=rE;function sE(t,e){_p(t,document.getElementById("main-stage-container"),iE()),U0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function Co(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Fr(),kn(),Bt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),Io("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}hg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Oc(),Bc(),mg(""),[1,2,3].forEach(a=>zn(a,"pending")),Lt(1,n),oE()}function Lt(t,e){le(e)&&(qn=t,Pl=Date.now(),Oc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),ko(t),Ar())}function fn(t,e){le(e)&&(zn(t,"done"),Lc===null&&ko(t,{done:!0}),Ar())}function vg(t,{stage:e=1,runId:n,retry:i=yg}={}){if(!le(n))return;Po(),Fr(),kn(),Io("failed"),Bt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Oc(),ko(e),Ar();const o=mp(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=`${So[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>Ii()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Al}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Al}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Al(){pg(),ng(),y.isRunning=!1,Ys(!1),pn(),Io("settled"),kn(),Po(),Fr(),Bc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Bt(!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 yg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),Bc(),Sr()}function oE(){Po(),cs=setInterval(()=>{const t=(Date.now()-hg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Ar()},250)}function Po(){cs&&(clearInterval(cs),cs=null)}let ar=null;function Fr(){ar&&(clearTimeout(ar),ar=null)}function Pi(){Po(),Fr(),Io("settled"),Ar();const t=document.getElementById("pipeline-progress-fill");ar=setTimeout(()=>{ar=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function ki(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function _g(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function aE(){return y_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function lE(t){return` +
    + ${ki(t.severity)} +
    +
    ${W(t.message)}
    + ${t.suggestion?`
    ${W(t.suggestion)}
    `:""} + ${W(t.source)} +
    +
    + `}function cE(t){return` +
  • +
    + ${W(t.title)} + ${t.detail&&t.detail!==t.title?`

    ${W(t.detail)}

    `:""} +
    +
  • + `}function uE(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=>` +
    • + ${ki(u.severity)} + + ${W(u.message)} + ${u.suggestion?`${W(u.suggestion)}`:""} + +
    • + `).join("")} +
    + `:"",a=t.warnings.length?` +
    +

    ${ki("warning")} Bundle

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

    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=>` +
    1. + ${W(u.title)} + ${u.detail&&u.detail!==u.title?`${W(u.detail)}`:""} +
    2. + `).join("")} +
    +
    + `:"";e.innerHTML=` +
    +
    +

    ${W(t.title)}

    +

    ${W(t.summary)}

    +
    +
    Artifact${t.artifacts.length===1?"":"s"}
    ${t.artifacts.map(u=>W(u.artifactType||u.type||u.name)).join(" · ")}
    +
    Public API
    ${t.artifacts.flatMap(u=>u.publicApi||[]).map(W).join(" · ")||"No parameters returned"}
    +
    Manual Steps Required
    ${l||"None reported"}
    +
    Review
    ${W(t.status||"Not reported")}
    +
    + ${o} + ${a} +
    +
    + +
    + Is the generated code correct? +
    + + +
    + +
    +
    +
    + `}function dE(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(lE).join(""):`
    ${ki(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` +
  • ${W(l.name)}${l.version?` ${W(l.version)}`:""}${l.reason?`

    ${W(l.reason)}

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

    ${W(l.description)}

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

    ${W(e.artifactName)}

    + ${e.description?`

    ${W(e.description)}

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

    Code Review findings

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

    Manual FlutterFlow steps for this file

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

    Dependencies

    +
      ${r}
    +
    +
    +

    Deployment

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

    Public API

    +
    ${o}
    +
    +
    +

    Imports

    +
    ${s}
    +
    +
    +

    Relationships

    +
      ${a}
    +
    +
    + `}function fE(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=""),Yd();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&&Dc(o.dataset.artifactId)},Yd()),e&&e.classList.add("visible")}function Yd(){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")wg();else{const a=s.dataset.artifactId;a&&Dc(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 Rr(){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=aE(),o=wc();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")}uE(s),fE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` +`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=vp(a),!nE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=dE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Tr(t,e){const n=document.getElementById("main-stage-container"),i=D0(n),r=document.body.classList.contains("results-fullscreen");Fr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),Bt(!0),y.selectedArtifactId||(y.selectedArtifactId=bi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Rr(),pn(),hE(),r||_p(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function hE(){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=""),Fl=!1}function Dc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Rr()}function wg(){y.resultsViewMode="summary",Rr()}function pE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=wc(),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 Fl=!1;async function gE(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Fl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Fl=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 kc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function mE(){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 bg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function vE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function Bt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function Eg(){const t=H.isVerified&&!!H.email,e=fe.tier||"free",n=t&&Ci(),i=!t||Ot(),s=n?"Checking…":i?Yl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Pc();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 yE(){Eg();const t=document.getElementById("credits-modal");t&&Ve(t)}function _E(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function Sg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),lc?.cancelTyping?.(),y.isRunning&&(pg(),ng(),y.isRunning=!1,Ys(!1),Pi(),y.artifactBundle?Rr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")Bt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&Bt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let Jd=!1;function jc(){const t=window.location.hash.replace(/^#/,"");Sg(t||"home",!1,Jd),Jd=!0}window.addEventListener("popstate",t=>{jc()});window.addEventListener("hashchange",()=>{jc()});window.copyResultsCode=pE;window.selectArtifact=Dc;window.selectResultsSummary=wg;window.submitResultsFeedback=gE;window.showErrorInputPanel=mE;window.hideErrorInputPanel=bg;window.setGenerationStageVisible=Bt;window.switchView=Sg;window.selectPipelineStage=eE;window.editPipelinePrompt=Al;window.retryPipelineRun=yg;window.openCreditsModal=yE;window.closeCreditsModal=_E; diff --git a/dist/assets/index-DbG5mQ4q.css b/dist/assets/index-DbG5mQ4q.css deleted file mode 100644 index d6697c1..0000000 --- a/dist/assets/index-DbG5mQ4q.css +++ /dev/null @@ -1 +0,0 @@ -@font-face{font-family:Delight;src:url(/assets/Delight-VF-CnVpVuQk.ttf) format("truetype");font-weight:100 900;font-display:swap}:root{--bg: oklch(96.65% .0074 260.73);--surface: oklch(100% 0 0);--surface-translucent: oklch(100% 0 0 / .65);--surface-glass: oklch(100% 0 0 / .72);--surface-sunken: oklch(98.4% .004 260);--fg: oklch(20.77% .0398 265.75);--muted: oklch(48% .02 260);--muted-2: oklch(68% .018 260);--on-dark: oklch(100% 0 0);--border: oklch(90% .012 260);--border-strong: oklch(80% .02 260);--fill-hover: color-mix(in oklch, var(--fg) 5%, var(--surface));--fill-subtle: color-mix(in oklch, var(--fg) 6%, var(--surface));--fill-selected: color-mix(in oklch, var(--fg) 4%, var(--surface));--track: color-mix(in oklch, var(--fg) 7%, var(--surface));--avatar: oklch(88% .02 260);--accent: oklch(63% .22 32);--accent-soft: oklch(from var(--accent) l c h / .18);--accent-ring: oklch(from var(--accent) l c h / .45);--fx-ink: oklch(70% .13 250);--ok: oklch(52% .11 165);--ok-soft: oklch(52% .11 165 / .12);--warn: oklch(66% .13 70);--warn-soft: oklch(66% .13 70 / .14);--bad: oklch(55% .19 25);--bad-soft: oklch(55% .19 25 / .1);--disabled-bg: oklch(88% .015 260);--disabled-fg: oklch(58% .02 260);--font-display: "Delight", "Outfit", "DM Sans", system-ui, sans-serif;--font-body: "Delight", "Outfit", "DM Sans", system-ui, sans-serif;--font-mono: "DM Mono", ui-monospace, SFMono-Regular, Menlo, monospace;--fw-ui: 560;--fw-bold: 620;--fw-black: 700;--ls-display: -.04em;--ls-heading: -.03em;--ls-mono: .13em;--fs-display: 54px;--fs-h2: 28px;--fs-h3: 22px;--fs-h4: 18px;--fs-lead: 17px;--fs-body: 14.5px;--fs-small: 13.5px;--fs-caption: 12.5px;--fs-mono: 11.5px;--fs-micro: 10.5px;--lh-display: 1.04;--lh-heading: 1.15;--lh-body: 1.6;--radius-xl: 22px;--radius-lg: 20px;--radius-md: 16px;--radius-sm: 14px;--radius-control: 12px;--radius-nav: 11px;--radius-icon: 10px;--radius-chip: 999px;--radius-badge: 7px;--shadow-sm: 0 1px 2px oklch(20% .03 260 / .06);--shadow-md: 0 1px 2px oklch(20% .03 260 / .06), 0 18px 46px -22px oklch(20% .03 260 / .3);--shadow-control: 0 2px 6px oklch(20% .03 260 / .22);--shadow-composer: 0 0 0 3px var(--accent-soft), 0 1px 2px oklch(20% .03 260 / .06), 0 0 44px -8px oklch(63% .22 32 / .16), 0 20px 52px -20px oklch(63% .22 32 / .18);--blur-chrome: 14px;--ease: cubic-bezier(.2, 0, 0, 1);--ease-overshoot: cubic-bezier(.32, 1.38, .5, 1);--t-fast: .15s;--t-enter: .22s;--t-reveal: .5s;--t-progress: .7s;--t-ring: .9s;--t-morph: 1.12s;--touch: 44px;--control-h: 46px;--stage-w: 1920px;--stage-h: 1080px;--measure-prose: 62ch;--measure-lead: 68ch}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;transition-duration:.01ms!important;transition-delay:0ms!important;animation-duration:.01ms!important;animation-iteration-count:1!important}}:where(button,[role=button],input,select,textarea,a){-webkit-tap-highlight-color:transparent}:where(button,[role=button],.control-button,.icon-button){min-height:44px;border-radius:var(--radius-md, 12px);transition:color var(--motion-fast, .16s) ease,background-color var(--motion-fast, .16s) ease,border-color var(--motion-fast, .16s) ease,box-shadow var(--motion-fast, .16s) ease,transform var(--motion-fast, .16s) ease,opacity var(--motion-fast, .16s) ease}:where(.icon-button,.modal-close,button:has(>svg:only-child)){min-width:44px;min-height:44px;display:inline-flex;align-items:center;justify-content:center}:where(button,[role=button],input,select,textarea,a[href]):focus-visible{outline:3px solid color-mix(in srgb,var(--accent, #3b82f6) 45%,transparent);outline-offset:2px}:where(button,[role=button]):active:not(:disabled){transform:scale(.98)}:where(button,[role=button]):disabled,:where(button,[role=button])[aria-disabled=true]{cursor:not-allowed;opacity:.5;box-shadow:none}:where(button,[role=button])[aria-busy=true]{cursor:progress;pointer-events:none}:where(button,[role=button])[aria-busy=true]:after{content:"";width:1em;height:1em;margin-inline-start:.55em;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:shared-control-spin .7s linear infinite}:where(input,select,textarea,.control-field){min-height:44px;border:1px solid var(--border, #dfe3ea);border-radius:var(--radius-md, 12px);background:var(--surface-sunken, #f8fafc)}:where(.badge,.sb-section-badge,.results-file-count,.pm-popular-badge){display:inline-flex;align-items:center;border-radius:999px;font-weight:600}:where(.panel,.results-panel,.pm-card){border:1px solid var(--border, #dfe3ea);border-radius:var(--radius-lg, 16px);background:var(--surface, #fff)}.modal-overlay{overflow:auto;overscroll-behavior:contain;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left))}.modal-overlay.open .modal-content{transform:scale(1) translateY(0)!important}.modal-overlay[aria-hidden=true]{pointer-events:none}.modal-overlay[aria-busy=true]{cursor:progress}.modal-content{width:min(100%,680px);max-height:calc(100dvh - 32px)!important;overflow:auto!important;overscroll-behavior:contain}.modal-content>:is(.border-t,.wt-footer){position:sticky;bottom:0;z-index:2;background:#fff}.modal-content>:is(.border-b,.pm-header){position:sticky;top:0;z-index:2;background:#fff}@media(max-width:480px),(max-height:600px){.modal-overlay{align-items:flex-start;padding:8px}.modal-content{max-height:calc(100dvh - 16px)!important;border-radius:14px}}@media(hover:hover){:where(button,[role=button]):hover:not(:disabled):not([aria-disabled=true]){filter:brightness(.97)}}@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}@keyframes shared-control-spin{to{transform:rotate(360deg)}}.hero-field{position:absolute;inset:0;overflow:hidden;z-index:-2;pointer-events:none}.fx-grid{position:absolute;inset:0;width:100%;height:100%;display:block;z-index:-2;pointer-events:none;opacity:0;transition:opacity var(--t-reveal) var(--ease)}.fx-grid.is-ready{opacity:1}.fx-mask{position:absolute;z-index:-1;pointer-events:none;background:var(--bg);filter:blur(46px)}.fx-mask-hero{left:50%;top:50%;width:980px;height:520px;transform:translate(-50%,-54%)}.fx-mask-top{left:-48px;right:-48px;top:-48px;height:132px}.fx-mask-bottom{left:-48px;right:-48px;bottom:-48px;height:132px}@media(max-width:920px){.fx-mask{filter:blur(36px)}.fx-mask-hero{width:92%;height:62%;top:50%;transform:translate(-50%,-50%)}.fx-mask-top{height:104px}.fx-mask-bottom{height:124px}}@media(prefers-reduced-motion:reduce){.hero-field,.fx-grid,.fx-mask{display:none}}.pipeline-glyph.logo-loop{position:relative;width:100%;height:88px;margin:0 0 24px;overflow:hidden;pointer-events:none;color:var(--muted)}.loop-mark,.loop-shadow{position:absolute}.loop-mark{left:0;top:50%;width:52px;height:52px;margin:-26px 0 0;will-change:transform}.loop-piece{position:absolute;inset:0;display:block;will-change:transform,opacity}.loop-piece svg{display:block;width:100%;height:100%;overflow:visible}.loop-halo{position:absolute;left:50%;top:50%;width:74px;height:74px;margin:-37px 0 0 -37px;border-radius:50%;background:radial-gradient(circle,color-mix(in oklch,var(--accent) 60%,transparent),transparent 64%);filter:blur(5px);opacity:.09;will-change:transform,opacity}.loop-shadow{left:var(--mark-c, 26px);bottom:13px;width:46px;height:6px;margin-left:-23px;border-radius:50%;background:color-mix(in oklch,var(--fg) 26%,transparent);opacity:0;will-change:transform,opacity}@media(max-width:920px){.pipeline-glyph.logo-loop{height:66px;margin-bottom:16px}.loop-mark{width:40px;height:40px;margin:-20px 0 0}.loop-halo{width:58px;height:58px;margin:-29px 0 0 -29px}.loop-shadow{bottom:6px}}.shell-frame{display:flex;justify-content:center;align-items:flex-start;width:100%}.shell-stage{position:relative;flex:none;width:1920px;height:1080px;overflow:hidden;background:var(--bg);transform-origin:top center;transform:scale(var(--fit,1));margin-bottom:calc(1080px * (var(--fit,1) - 1));isolation:isolate}.shell-stage .topbar{position:absolute;inset:0 0 auto;height:88px;padding:0 40px;background:transparent;border:0}.shell-stage .brand{width:246px;max-width:calc(100% - 140px);min-height:44px}.shell-stage .brand-mark{display:block;width:100%;height:auto;overflow:visible}.shell-stage .topbar-account{gap:10px}.shell-stage .topbar{gap:0}.shell-stage .topbar-credits{height:32px;min-height:32px;padding:0 10px 0 8px;gap:5px}.shell-stage .topbar-credits{display:inline-flex}.shell-stage .topbar-plan{text-transform:uppercase}.shell-stage .topbar-plan{height:22px;min-height:22px;padding:0 8px;border-radius:6px;cursor:pointer}.shell-stage .topbar-avatar{width:32px;height:32px;min-height:32px;min-width:32px}.shell-stage .viewport{position:static;top:auto;min-height:0}.shell-stage .view-home{min-height:1080px;transform:none;transition:none}.shell-stage .hero-field{z-index:-1}.glow{position:absolute;left:50%;top:55%;width:1360px;height:760px;transform:translate(-50%,-50%);background:radial-gradient(ellipse at 28% 46%,oklch(from var(--bg) calc(l - .07) calc(c + .035) h / .42),transparent 62%),radial-gradient(ellipse at 72% 56%,oklch(from var(--accent) l c h / .09),transparent 58%);filter:blur(64px);pointer-events:none}.shell-stage .hero{position:absolute;left:50%;top:50%;transform:translate(-50%,-52%);width:1280px;padding:0;flex:none;z-index:1}.shell-stage #hero.is-exiting{display:flex!important;pointer-events:none}.shell-stage .headline{font-size:80px;line-height:1.05}.shell-stage .sub{margin-top:28px;font-size:20px}.shell-stage .composer{margin-top:46px;width:760px;height:148px;flex:none}.shell-stage .composer .field,.shell-stage .composer .ghost{left:23px;right:23px;top:19px;width:auto;height:58px;min-height:0;font-size:18px;line-height:1.5}.shell-stage .composer .field{overflow-y:auto;box-shadow:none}.shell-stage .composer .ghost .suggest{color:var(--muted)}.shell-stage .composer .tools{left:15px;bottom:12px}.shell-stage .icon-btn,.shell-stage .send{width:44px;height:44px;min-width:44px;min-height:44px}.shell-stage .send{right:15px;bottom:15px}.shell-stage .send:disabled{opacity:1}.shell-stage .composer .tab-hint{right:74px;bottom:13px;min-height:44px;margin:-4px -6px}.shell-stage .chips{max-width:none}.shell-stage .chip{min-height:44px;background:#ffffffb3}.composer.is-pointer-focus{outline:none}#generation-stage{position:absolute;inset:164px auto auto 50%;width:1420px;transform:translate(-50%);padding:0;background:transparent;opacity:1;transition:none}#generation-stage.is-active,body.results-fullscreen #generation-stage{display:block}#generation-stage.is-active #main-stage-container{opacity:1;pointer-events:auto}#main-stage-container[data-morphing],#main-stage-container[data-morphing] *{visibility:hidden!important}#main-stage-container{position:relative;inset:auto;display:grid;grid-template-columns:310px minmax(0,1fr);width:100%;height:auto;min-height:590px;border:2px solid oklch(from var(--accent) l c h / .85);border-radius:20px;background:var(--surface);box-shadow:var(--shadow-composer);overflow:hidden}#main-stage{min-width:0;padding:0;display:grid;grid-template-columns:minmax(0,1fr);grid-template-areas:"stack";overflow:visible}#main-stage>*{grid-area:stack}#main-stage-container .pipeline-prompt-recap{grid-area:auto;padding:30px}#main-stage-container .pipeline-prompt-text{margin:12px 0 32px;font-size:17px;line-height:1.5}#pipeline-progress{grid-area:stack;height:auto;padding:0;overflow:visible;align-self:center}#pipeline-progress.visible{display:block}#pipeline-progress .pipeline-view{display:block;padding:48px 64px}#pipeline-stage-nav{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%)}#pipeline-stage-nav:focus-within,#pipeline-stage-nav.is-open{position:relative;width:auto;height:auto;margin:20px 0 0;clip-path:none}#progress-stage-count{position:relative;min-height:0;padding:0;border:0;border-radius:0;font:inherit;line-height:normal;color:inherit;background:none;text-align:left}#progress-stage-count:after{content:"";position:absolute;inset:-15px 0}#progress-elapsed{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}.composer-morph{background:var(--surface);border:2px solid oklch(from var(--accent) l c h / .85);border-radius:20px;box-shadow:var(--shadow-composer)}.panel-in{animation:fidelity-rise .5s var(--ease) both}@keyframes fidelity-rise{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}body.results-fullscreen #generation-stage{inset:104px 40px auto;width:auto;transform:none}body.results-fullscreen #main-stage-container{height:936px;min-height:0}body.results-fullscreen #main-stage{height:100%;min-height:0;grid-template-rows:1fr}body.results-fullscreen .pipeline-prompt-edit{margin-bottom:10px}#results-view{min-width:0;min-height:0;height:100%;padding:40px 48px;overflow:hidden}#results-view.visible{display:flex;flex-direction:column}#results-view .results-header{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%)}#bundle-strip{flex:none;gap:10px;margin:0 0 22px;padding:0 0 14px;border:0;border-bottom:1px solid var(--border);background:transparent;overflow-x:auto}#bundle-strip.visible{display:flex;align-items:center}#artifact-tabs{display:flex;gap:10px;flex:none;width:auto;padding:0}#bundle-strip .results-summary-tab{flex:none;min-height:38px;padding:0 13px;border-radius:9px;font:700 13px var(--font-display)}#bundle-strip .artifact-tab{min-width:172px;max-width:260px;padding:8px 11px;border-radius:9px;background:var(--surface)}#bundle-strip .artifact-tab-name{font:700 13px var(--font-display)}#bundle-strip .artifact-tab-meta{font:11px var(--font-mono);margin-top:3px}#bundle-strip .artifact-tab.active{border-color:var(--fg);box-shadow:inset 0 0 0 1px var(--fg)}#bundle-strip .artifact-tab-status.status-pass{color:var(--ok);background:var(--ok-soft)}#bundle-strip .artifact-tab-status.status-warning{color:var(--warn);background:var(--warn-soft)}#bundle-strip .artifact-tab-status.status-fail{color:var(--bad);background:var(--bad-soft)}#results-summary-detail{flex:1;min-height:0;max-height:none;padding:16px 4px;overflow:auto;border:0;background:transparent}#results-summary-detail .review-summary{display:flex;align-items:flex-start;justify-content:space-between;gap:32px;padding:0;border:0;background:none;box-shadow:none}#results-summary-detail .review-summary-copy{flex:1;min-width:0}.summary-heading{font:500 28px/1.2 var(--font-display);margin:0 0 16px;letter-spacing:normal}#results-summary-detail .review-summary-text{max-width:var(--measure-prose);font-size:14px;line-height:1.6;color:var(--muted)}.summary-spec{margin-top:24px;display:grid;gap:16px}.summary-spec>div{display:flex;gap:20px;justify-content:space-between;border-top:1px solid var(--border);padding-top:12px;font-size:14px}.summary-spec dt{color:var(--muted)}.summary-spec dd{text-align:right;overflow-wrap:anywhere}.summary-spec .summary-manual-callout{padding:0;margin:0;border:0;background:none;color:var(--fg);text-align:left}.summary-spec .summary-manual-callout ol{padding-left:1.4em;display:grid;gap:4px}.summary-spec .summary-manual-callout li{display:list-item;font-size:14px;font-weight:400}.summary-spec .summary-manual-callout li strong{font-weight:400}#results-summary-detail .review-score-column{width:184px;flex:none}#results-summary-detail .review-score{min-height:164px;padding:18px 16px;border-radius:12px;background:var(--surface-sunken)}#results-summary-detail .review-score strong{font:700 58px/.95 var(--font-display);margin-top:3px;letter-spacing:-.05em}#results-summary-detail .review-score-feedback{font-size:11px}#results-summary-detail .review-score-pass{color:var(--ok);border-color:var(--ok-soft)}#results-summary-detail .review-score-warning{color:var(--warn);border-color:var(--warn-soft)}#results-summary-detail .review-score-fail{color:var(--bad);border-color:var(--bad-soft)}#results-summary-detail .review-score-label{font:700 11px/1 var(--font-mono)}#results-summary-detail .review-score-status{font:800 11px/1 var(--font-mono);letter-spacing:.08em}#results-summary-detail .review-score-feedback{font-weight:600;color:var(--muted);line-height:normal}#results-summary-detail .feedback-btn{width:36px;height:36px;min-width:36px;min-height:36px;border-radius:8px}#results-summary-detail .feedback-btn svg{width:16px;height:16px}#results-view .flutterflow-deploy-icon{display:block;width:18px;height:18px;filter:none;mix-blend-mode:normal}#results-view .results-action-bar{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;flex:none;margin:20px 0 0;padding:12px 0 0;border-top:1px solid var(--border);background:transparent}#results-view .results-action{display:contents}#results-view .results-action-scope{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}#results-view .results-action-bar .btn-header-action{min-height:44px;padding:9px 16px;border:1px solid var(--border);border-radius:12px;font:600 12.5px var(--font-display);letter-spacing:-.01em;background:var(--surface);color:var(--fg);box-shadow:none}#results-view .results-action-bar .btn-deploy-results{background:var(--fg);color:var(--surface);border-color:var(--fg);box-shadow:0 2px 8px -2px oklch(from var(--accent) l c h / .4)}#results-view .results-action-bar .btn-error-regen{border-color:color-mix(in oklch,var(--warn) 45%,var(--surface));color:oklch(from var(--warn) 48% c h)}#artifact-results-split{flex:1;min-height:0;gap:22px;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr)}#artifact-results-split .results-panel{min-width:0;min-height:0;border:1px solid var(--border);border-radius:14px;overflow:hidden}#artifact-results-split .panel-body{min-height:0;overflow:auto}#artifact-results-split .panel-code-wrap{height:100%;min-height:0;background:var(--surface-sunken)}#results-code-output{color:var(--fg);background:var(--surface-sunken);font:12px/1.8 var(--font-mono);white-space:pre-wrap;overflow-wrap:anywhere}#results-code-output .hljs-keyword,#results-code-output .hljs-meta{color:oklch(from var(--accent) 46% calc(c*.7) h)!important}#results-code-output .hljs-string{color:var(--fg)!important}#results-code-output .hljs-comment{color:var(--muted)!important;font-style:normal}#results-code-output .hljs-number,#results-code-output .hljs-type,#results-code-output .hljs-built_in,#results-code-output .hljs-title{color:oklch(from var(--fg) 45% c h)!important}.code-line{display:block;min-height:1.8em}.code-line.is-in{animation:code-land .52s var(--ease) both;animation-delay:var(--d)}@keyframes code-land{0%{opacity:0;transform:translateY(6px);background:var(--accent-soft)}42%{opacity:1;transform:translateY(0);background:var(--accent-soft)}to{opacity:1;transform:none;background:transparent}}body[data-shell-view=account] .shell-stage,body[data-shell-view=plans] .shell-stage{width:100%;height:auto;min-height:100vh;transform:none;margin:0;overflow:visible}body[data-shell-view=account] .viewport,body[data-shell-view=plans] .viewport{padding-top:88px}@media(max-width:920px){.shell-frame{display:block}.shell-stage{display:flex;flex-direction:column;width:100%;height:auto;min-height:100svh;transform:none;margin:0}.shell-stage .topbar{position:relative;flex:none;height:64px;padding:0 20px}.shell-stage .topbar-credits{height:30px;min-height:30px;padding:0 9px 0 7px;font-size:12px}.shell-stage .topbar-avatar{width:30px;height:30px;min-width:30px;min-height:30px}.shell-stage .viewport,.shell-stage .view-home{flex:1;display:flex;flex-direction:column;min-height:0}.shell-stage .hero{position:relative;left:auto;top:auto;transform:none;width:100%;padding:24px 20px 32px;flex:1}.shell-stage .headline{font-size:clamp(34px,6.8vw,56px);line-height:1.08;letter-spacing:-.03em;text-wrap:balance}.shell-stage .sub{margin-top:18px;font-size:16px;max-width:34ch}.shell-stage .composer{margin-top:32px;width:100%;max-width:520px;height:148px;border-radius:16px}.shell-stage .composer .field,.shell-stage .composer .ghost{left:18px;right:18px;top:16px;height:94px;font-size:16px;line-height:1.45}.shell-stage .composer .tools{left:10px;bottom:12px}.shell-stage .send{right:10px;bottom:10px}.shell-stage .composer .tab-hint{right:63px;bottom:12px}.shell-stage .chips{max-width:520px}.shell-stage .chips .chip{height:auto;padding-block:10px}.glow{width:140vw;height:60vh;top:48%;filter:blur(40px)}#generation-stage,body.results-fullscreen #generation-stage{position:relative;inset:auto;width:100%;transform:none;padding:28px 20px;flex:1}#main-stage-container,body.results-fullscreen #main-stage-container{grid-template-columns:minmax(0,1fr);min-height:0;height:auto;border-radius:18px}#main-stage-container .pipeline-prompt-recap{padding:22px;border-right:0;border-top:1px solid var(--border)}#main-stage-container .pipeline-prompt-text{margin:8px 0 20px;font-size:15px;max-height:100px}body.results-fullscreen .pipeline-prompt-edit{margin-bottom:0}#pipeline-progress .pipeline-view{padding:34px 24px;min-height:300px}#results-view{height:auto;padding:22px;overflow:visible}#results-summary-detail .review-summary{flex-direction:column;gap:22px}#results-summary-detail .review-score-column{width:100%}#results-summary-detail{overflow:visible}.summary-spec>div{flex-wrap:wrap;gap:6px}#results-view .results-action-bar,#artifact-results-split{grid-template-columns:1fr}#results-code-output{height:260px}body[data-shell-view=account] .viewport,body[data-shell-view=plans] .viewport{padding-top:0}}@media(prefers-reduced-motion:reduce){.panel-in,.code-line.is-in{animation:none}} diff --git a/dist/index.html b/dist/index.html index a3abf75..be0cc03 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2857,14 +2857,10 @@ color: transparent; } .composer .ghost .typed { color: transparent; } - .composer .ghost .suggest { - color: oklch(80% 0.012 260); - opacity: 0; - transition: opacity var(--t-fast) var(--ease); - } - .composer.has-suggest .ghost .suggest { opacity: 1; } /* Demo caret (prototype): a real text cursor — hard blink on a 1.05s cadence - with a soft brand afterglow. Shown while a chip fills the prompt. */ + with a soft brand afterglow. Shown while the hero demo or a chip writes + the prompt; held solid while characters land (is-demo-keying), so it + only blinks while the field is idle, like a real cursor. */ @keyframes caret-blink { 0%,45% { opacity:1; } 46%,100% { opacity:0; } } .composer.is-demo-typing .ghost .typed::after { content:""; display:inline-block; width:2px; height:1.05em; margin-right:-2px; vertical-align:-.15em; @@ -2872,40 +2868,7 @@ box-shadow:0 0 7px 1px oklch(from var(--accent) l c h / .5); animation:caret-blink 1.05s step-end infinite; } - .composer .tab-hint { - position: absolute; - right: 64px; - bottom: 22px; - display: inline-flex; - align-items: center; - gap: 6px; - padding: 4px 6px; - border: 0; - background: transparent; - border-radius: 6px; - cursor: pointer; - font-family: var(--font-mono); - font-size: 11px; - letter-spacing: 0.02em; - color: var(--muted); - opacity: 0; - transform: translateY(2px); - transition: opacity var(--t-fast) var(--ease), transform var(--t-fast) var(--ease); - pointer-events: none; - } - .composer .tab-hint kbd { - font: inherit; - padding: 1px 6px; - border: 1px solid var(--border); - border-bottom-width: 2px; - border-radius: 5px; - background: var(--surface); - color: var(--fg); - } - .composer.has-suggest .tab-hint { opacity: 1; transform: none; pointer-events: auto; } - .composer .tab-hint[hidden] { display: none; } - .composer .tab-hint:hover { color: var(--fg); background: oklch(96% 0.01 260); } - .composer .tab-hint:hover kbd { border-color: oklch(80% 0.02 260); } + .composer.is-demo-keying .ghost .typed::after { animation: none; } .composer:focus-within { border-color: var(--accent); box-shadow: @@ -3310,8 +3273,8 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - - + +
    @@ -3350,10 +3313,8 @@

    FlutterFlow custom code.
    - - - - + +
    + +
    `,t.appendChild(r)}),e&&(e.textContent=De.length>=fl?"Image limit reached":"Add images"))}function cc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=bp(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(Sp),De=[],yn())}const Wn="ccc_usage",Ip="google/gemini-3.7-flash",kp="google/gemini-3.7-flash",Kr="google/gemini-3.7-flash",Ji={professional:11,power:49},hl={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"},ss={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 os={...ss};async function ow(){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(ss),...Object.values(pl),...Object.values(hl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:ss[a]&&(s[a]=ss[a]));os=s}catch{}finally{clearTimeout(e)}}const pl={"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 uc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&pl[s])return pl[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=hl[e];if(n)return n;const i=e.split("_")[0],r=hl[i];return r||"USD"}function Zi(t,e){const n=os[e]??os.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*os.USD)}}const _t="ccc_api_key_",Tt="ccc_session_api_key_",Nt="ccc_encryption_key",vr="ccc_encryption_key_scope",aw="ccc_keystore",Us="keys",yr="ccc_encryption_key_version";let gl=null,Hs=null,_r=!1,Ws=!1,Md=!1;class qs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function $d(){if(Md)return;Md=!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&&Se(t,"warning")}function Cp(){return localStorage.getItem(yr)||""}function ml(){return crypto.randomUUID?.()||Ap(crypto.getRandomValues(new Uint8Array(16)))}function lw(){const t=Cp();if(t)return t;const e=ml();return localStorage.setItem(yr,e),e}function xi(){gl=null,Hs=null,_r=!1,Ws=!1}window.addEventListener("storage",t=>{t.key===yr&&xi()});function cw(){return new Promise((t,e)=>{const n=indexedDB.open(aw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Us)||i.createObjectStore(Us)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function dc(t,e){const n=await cw();return new Promise((i,r)=>{const s=n.transaction(Us,t);let o;try{o=e(s.objectStore(Us))}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 uw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function dw(){const t=await dc("readonly",e=>e.get(Nt));return uw(t)?t:null}async function Pp(t){await dc("readwrite",e=>e.put(t,Nt))}async function fw(){xi();try{await dc("readwrite",t=>t.delete(Nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function hw(){const t=sessionStorage.getItem(Nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(e),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),e}async function Ld(t){const e=sessionStorage.getItem(Nt);if(e)return Ws=sessionStorage.getItem(vr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new qs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Nt,JSON.stringify(i)),sessionStorage.setItem(vr,"session"),Ws=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function pw(t){if(sessionStorage.getItem(vr)==="session"&&sessionStorage.getItem(Nt))return $d(),_r=!0,Ld(t);try{const e=await dw();if(e)return e;const n=await hw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),$d(),_r=!0,Ld(t)}}async function fc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=lw();Hs!==n&&xi();const i=gl||pw(e);gl=i,Hs=n;try{return await i}catch(r){throw xi(),r}}async function gw(t){const e=await fc(),n=Hs,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:Ap(o),keyVersion:n,sessionFallback:_r}}async function mw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await fc({allowSessionFallbackCreation:!1});if(_r&&!n&&!Ws)throw new qs;const r=vw(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 qs)throw i;return console.error("Decryption failed:",i),null}}function Ap(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let ke="",Mt="",sr=null,Od=0,ot="not-configured",gt=0,vl=0,yl=0,oo=0,Zt=0,un=0,Xe=null,$t=null,wr=null;function _w(){return vl+=1,vl}function ww(){return yl+=1,yl}function br(t,e,n){Xe=t?{projectId:t,key:e,generation:n}:null}function _l(t,e=ke){if(!t)return!1;const n=Xe;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function hc(t,e,n){if(!Mt||Xe&&Xe.projectId!==Mt)return;(t||[]).some(r=>(r.id||r.projectId)===Mt)?br(Mt,e,n):Xe&&br("",null,null)}function Fp({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===ke||r===ke}async function pc(){sessionStorage.getItem(Nt)&&await fc(),ke=await Me("flutterflow"),Mt=await Me("flutterflow_project_id"),kw(),pn(),ke?yc():(ot="not-configured",bt())}let Er=!1;function Rp(){const t=document.getElementById("api-keys-modal");Ve(t),vc(),ke&&co(ke)}function gc(){Er=!1,Rp()}function bw(){Er=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Rp()}let Bd=!1;function Dd(){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 jd(){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=nn(t.value),r=bp(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.`),cc()}function Tp(){if(Er=!1,Dd(),jd(),!Bd){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")),Dd(),jd()}),Bd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function Ew(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Mp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=Er;if(Er=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&mc(),Ve(i))}}let dn=1;function $p(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function ao(){const t=$p();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,ao())}function Sw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,ao(),Ve(t))}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Lp(){if(H.isVerified&&Ot()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,ao(),Ve(e))}}async function vc(){const t=document.getElementById("flutterflow-api-key-input");ke?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Iw()}function Iw(){Ud("flutterflow","flutterflow-key-status"),Ud("flutterflow_project_id","flutterflow-project-status")}function Ud(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ft(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function kw(){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"?Ft("flutterflow")&&Ft("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ft("flutterflow")||Ft("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)"):Ft(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)")}),pn()}async function Cw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==ke,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await Nd("flutterflow",n),n!==l&&!r&&as()}const s=n||ke;if(r){if(!lo(r)){Se("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}_l(r,s)?await Nd("flutterflow_project_id",r):(i?as():Xe=null,e.value="",s&&!($t&&$t.key===s&&$t.generation===gt)&&co(s))}else i&&as();await pc(),n&&await yc(),vc();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Mp()},1e3)}async function Pw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(yr,ml()),xi(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),await fw(),localStorage.setItem(yr,ml()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),Xe=null,$t=null,wr=null,await pc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),vc()}function lo(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Mt||"—"),!e)return;let r,s;if(!Ft("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 yc(){const t=ww(),e=++oo,n=gt,i=ke,r=await Me("flutterflow"),s=()=>Fp({seq:t,currentSeq:yl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Ft("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&hc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function as(){Mt="",Xe=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow_project_id")}function Aw(){gt+=1,$t=null,wr=null,as();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ft("flutterflow")?(ot="validating",co(ke)):ot="not-configured",bt()}function Fw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Rw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Fw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Tw(async n=>{const i=n.target.value.trim();i&&await co(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&$t?br(n,$t.key,$t.generation):br("",null,null)})}function Tw(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function co(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=_w(),r=++oo,s=gt,o=ke,a=()=>Fp({seq:i,currentSeq:vl,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};$t=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===ke&&(Ft("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;$t={key:t,generation:s};const f=t===ke,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,hc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Mt&&(e.value=Mt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===ke&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Mw(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const T0=5200,M0=73,$0=1600,L0=35,ga=new WeakMap;function Ad(t,e){return!!(t&&t.trim())&&!e}function N0({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=Array.from(document.querySelectorAll("#example-chips .chip")),o=document.getElementById("btn-add-images"),a=document.getElementById("prompt-image-input"),l=window.matchMedia("(prefers-reduced-motion: reduce)");let u=!1,c=!1,d=!1,f=!1,p=!1,h=null,g=null;const m=n.dataset.demoPrompt||"";function v(){return c||d||f||p}function b(){i.disabled=!Ad(n.value,v())}function w(){r&&(r.textContent=n.value)}function _(B){c=B,e.classList.toggle("is-busy",B),i.classList.toggle("is-busy",B),i.setAttribute("aria-label",B?"Generating":"Generate"),n.readOnly=B,s.forEach(Z=>{Z.disabled=B}),o&&(o.disabled=B),a&&(a.disabled=B),b()}async function x(){if(Ad(n.value,v())){_(!0);try{await t()}finally{_(!1)}}}function I(){f&&(f=!1,g&&(clearTimeout(g),g=null),e.classList.remove("is-demo-typing","is-demo-keying"),n.placeholder="Describe the widget or action you need",b())}function T(){if(l.matches||!m.trim())return;const B=window.location.hash.replace(/^#/,"");if(B&&B!=="home")return;f=!0,n.placeholder="",n.value="",w(),b(),e.classList.add("is-demo-typing");let Z=0;const se=(ue,ye)=>{Z+=ue,n.value=m.slice(0,Z),w(),e.classList.toggle("is-demo-keying",ye)},Ce=()=>{f&&(se(-1,!0),Z>0?g=setTimeout(Ce,L0):I())},Q=()=>{if(!f)return;const ue=Z+1B.classList.contains("is-active"))?.dataset.prompt||n.value,w(),R())}function $(){s.forEach(B=>{B.classList.remove("is-active"),B.setAttribute("aria-pressed","false")})}function O(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function J(B){const Z=B.dataset.prompt||"";if(I(),R(),s.forEach(Ce=>{const Q=Ce===B;Ce.classList.toggle("is-active",Q),Ce.setAttribute("aria-pressed",String(Q))}),l.matches||!Z){n.value=Z,w(),b(),O();return}n.value="",w(),d=!0,b(),e.classList.add("is-demo-typing","is-demo-keying");let se=0;h=setInterval(()=>{se+=1,n.value=Z.slice(0,se),w(),se>=Z.length?(R(),O()):b()},22)}s.forEach(B=>{B.setAttribute("aria-pressed","false"),B.addEventListener("click",()=>J(B))}),n.addEventListener("keydown",B=>{if((f||d)&&B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u){B.preventDefault();return}S(),L(),B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u&&(B.preventDefault(),x())}),n.addEventListener("beforeinput",()=>S()),n.addEventListener("input",()=>{I(),R(),$(),w(),b()}),n.addEventListener("compositionstart",()=>{u=!0}),n.addEventListener("compositionend",()=>{u=!1,b()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),i.addEventListener("click",x),n.addEventListener("pointerdown",()=>{S(),L(),$()}),n.addEventListener("focus",()=>S());const G=ga.get(e);G&&G.mql.removeEventListener("change",G.handler),l.addEventListener("change",P),ga.set(e,{mql:l,handler:P});function M(){K(),l.removeEventListener("change",P),ga.delete(e),document.removeEventListener("visibilitychange",ie)}function K(){S(),L()}function ie(){document.hidden&&K()}return document.addEventListener("visibilitychange",ie),w(),b(),T(),{setAttachmentsPending(B){p=!!B,b()},dispose:M,cancelTyping:K}}const mr=window.matchMedia("(prefers-reduced-motion: reduce)");let fi=null,Jt=null;const Ns=new Map;function yp(){for(const[t,e]of Ns)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Ns.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Gn(){if(yp(),fi){const t=fi;fi=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Jt&&(Jt.animation.cancel(),Jt.hero.classList.remove("is-exiting"),Jt.hero.style.cssText=Jt.style,Jt=null)}function O0(t){return(fi?.ghost||t)?.getBoundingClientRect()}function B0(t){yp(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",mr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Ns.delete(e))}Ns.set(e,i),e.addEventListener("animationend",i)})}function D0(t,e){if(!t||!e||mr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Jt={hero:t,animation:i,style:n},i.onfinish=()=>{Jt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Jt=null)}}function _p(t,e,n,{results:i=!1}={}){if(Gn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,B0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(mr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};fi=h,p.onfinish=()=>{fi===h&&(Gn(),s())}}window.addEventListener("resize",Gn);window.addEventListener("pagehide",Gn);document.addEventListener("visibilitychange",()=>{document.hidden&&Gn()});mr.addEventListener("change",()=>{mr.matches&&Gn()});const Fd="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",j0="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",U0="https://us.i.posthog.com";Nh.init(j0,{api_host:U0,person_profiles:"identified_only"});function Dn(t,e={}){try{Nh.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const Et="https://4tgke4.buildship.run",wp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Os="ccc_auth_session",ul="ccc_signin_return",H0=1800*1e3,Rd=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=Kn({isResolved:!0}),dl=Promise.resolve();const W0=`${Et}/service/runpipeline`,q0="bs_user_id",z0="bs_identity_token",V0=`${Et}/authUserCheck`;let yt={userId:null,token:null,status:null,resolved:!1};const Bs=ry,Ds="ccc_subscription",Td=3,G0=new Set(["active","trialing","paid"]),js="google/gemini-3.7-flash",rs=["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"],K0={"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 nn(t){return K0[t]||t}const Y0=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 bp(t){return Y0.has(t)}const fl=4,ma=8*1024*1024,J0="https://4tgke4.buildship.run/service/runpipeline-image";let De=[];const Sn=[],Z0=3e4;let lc=null;function X0(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function Q0(t,e){const n=new FormData;return n.append("file",t),(await fetch(J0,{method:"POST",body:n,signal:e})).json()}function ew(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 tw(t,e,n){const i=await X0(t,n);i&&De.includes(e)&&(e.dataUrl=i,yn());let r="";if(i)try{r=ew(await Q0(t,n))}catch{r=""}return De.includes(e)?!i||!r?(De.splice(De.indexOf(e),1),yn(),"failed"):(e.url=r,yn(),"added"):"dropped"}function Ep(t){const e=Sn.indexOf(t);e>=0&&Sn.splice(e,1),xp()}function Sp(t){t.controller.abort(),Ep(t);const e=De.indexOf(t.slot);e>=0&&(De.splice(e,1),yn())}function xp(){lc?.setAttachmentsPending(Sn.length>0)}async function nw(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Se("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>ma);n.length&&Se(`Skipped ${n.length} image(s) over the ${(ma/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ma);if(!i.length)return;const r=fl-De.length,s=i.slice(0,r);if(i.length>r&&Se(`You can attach up to ${fl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};De.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Z0);return d.job=tw(u,c,d.controller.signal),Sn.push(d),d.job.finally(()=>{clearTimeout(f),Ep(d)}),d.job});yn(),xp();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Se(`${l} image(s) could not be uploaded and were not attached.`,"error")}function iw(t){if(y.isRunning){Se("Wait for the current generation to finish before removing images.","info");return}const e=De[t],n=Sn.find(i=>i.slot===e);if(n){Sp(n);return}De.splice(t,1),yn()}function yn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",De.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=De.length>=fl?"Image limit reached":"Add images"))}function cc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=bp(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(Sp),De=[],yn())}const Wn="ccc_usage",Ip="google/gemini-3.7-flash",kp="google/gemini-3.7-flash",Kr="google/gemini-3.7-flash",Ji={professional:11,power:49},hl={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"},ss={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 os={...ss};async function rw(){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(ss),...Object.values(pl),...Object.values(hl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:ss[a]&&(s[a]=ss[a]));os=s}catch{}finally{clearTimeout(e)}}const pl={"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 uc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&pl[s])return pl[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=hl[e];if(n)return n;const i=e.split("_")[0],r=hl[i];return r||"USD"}function Zi(t,e){const n=os[e]??os.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*os.USD)}}const _t="ccc_api_key_",Tt="ccc_session_api_key_",Nt="ccc_encryption_key",vr="ccc_encryption_key_scope",sw="ccc_keystore",Us="keys",yr="ccc_encryption_key_version";let gl=null,Hs=null,_r=!1,Ws=!1,Md=!1;class qs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function $d(){if(Md)return;Md=!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&&Se(t,"warning")}function Cp(){return localStorage.getItem(yr)||""}function ml(){return crypto.randomUUID?.()||Ap(crypto.getRandomValues(new Uint8Array(16)))}function ow(){const t=Cp();if(t)return t;const e=ml();return localStorage.setItem(yr,e),e}function xi(){gl=null,Hs=null,_r=!1,Ws=!1}window.addEventListener("storage",t=>{t.key===yr&&xi()});function aw(){return new Promise((t,e)=>{const n=indexedDB.open(sw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Us)||i.createObjectStore(Us)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function dc(t,e){const n=await aw();return new Promise((i,r)=>{const s=n.transaction(Us,t);let o;try{o=e(s.objectStore(Us))}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 lw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function cw(){const t=await dc("readonly",e=>e.get(Nt));return lw(t)?t:null}async function Pp(t){await dc("readwrite",e=>e.put(t,Nt))}async function uw(){xi();try{await dc("readwrite",t=>t.delete(Nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function dw(){const t=sessionStorage.getItem(Nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(e),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),e}async function Ld(t){const e=sessionStorage.getItem(Nt);if(e)return Ws=sessionStorage.getItem(vr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new qs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Nt,JSON.stringify(i)),sessionStorage.setItem(vr,"session"),Ws=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function fw(t){if(sessionStorage.getItem(vr)==="session"&&sessionStorage.getItem(Nt))return $d(),_r=!0,Ld(t);try{const e=await cw();if(e)return e;const n=await dw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),$d(),_r=!0,Ld(t)}}async function fc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=ow();Hs!==n&&xi();const i=gl||fw(e);gl=i,Hs=n;try{return await i}catch(r){throw xi(),r}}async function hw(t){const e=await fc(),n=Hs,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:Ap(o),keyVersion:n,sessionFallback:_r}}async function pw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await fc({allowSessionFallbackCreation:!1});if(_r&&!n&&!Ws)throw new qs;const r=gw(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 qs)throw i;return console.error("Decryption failed:",i),null}}function Ap(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let ke="",Mt="",sr=null,Od=0,ot="not-configured",gt=0,vl=0,yl=0,oo=0,Zt=0,un=0,Ze=null,$t=null,wr=null;function vw(){return vl+=1,vl}function yw(){return yl+=1,yl}function br(t,e,n){Ze=t?{projectId:t,key:e,generation:n}:null}function _l(t,e=ke){if(!t)return!1;const n=Ze;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function hc(t,e,n){if(!Mt||Ze&&Ze.projectId!==Mt)return;(t||[]).some(r=>(r.id||r.projectId)===Mt)?br(Mt,e,n):Ze&&br("",null,null)}function Fp({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===ke||r===ke}async function pc(){sessionStorage.getItem(Nt)&&await fc(),ke=await Me("flutterflow"),Mt=await Me("flutterflow_project_id"),xw(),pn(),ke?yc():(ot="not-configured",bt())}let Er=!1;function Rp(){const t=document.getElementById("api-keys-modal");Ve(t),vc(),ke&&co(ke)}function gc(){Er=!1,Rp()}function _w(){Er=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Rp()}let Bd=!1;function Dd(){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 jd(){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=nn(t.value),r=bp(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.`),cc()}function Tp(){if(Er=!1,Dd(),jd(),!Bd){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")),Dd(),jd()}),Bd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function ww(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Mp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=Er;if(Er=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&mc(),Ve(i))}}let dn=1;function $p(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function ao(){const t=$p();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,ao())}function bw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,ao(),Ve(t))}function Ew(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Lp(){if(H.isVerified&&Ot()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,ao(),Ve(e))}}async function vc(){const t=document.getElementById("flutterflow-api-key-input");ke?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Sw()}function Sw(){Ud("flutterflow","flutterflow-key-status"),Ud("flutterflow_project_id","flutterflow-project-status")}function Ud(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ft(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function xw(){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"?Ft("flutterflow")&&Ft("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ft("flutterflow")||Ft("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)"):Ft(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)")}),pn()}async function Iw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==ke,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await Nd("flutterflow",n),n!==l&&!r&&as()}const s=n||ke;if(r){if(!lo(r)){Se("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}_l(r,s)?await Nd("flutterflow_project_id",r):(i?as():Ze=null,e.value="",s&&!($t&&$t.key===s&&$t.generation===gt)&&co(s))}else i&&as();await pc(),n&&await yc(),vc();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Mp()},1e3)}async function kw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(yr,ml()),xi(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),await uw(),localStorage.setItem(yr,ml()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),Ze=null,$t=null,wr=null,await pc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),vc()}function lo(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Mt||"—"),!e)return;let r,s;if(!Ft("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 yc(){const t=yw(),e=++oo,n=gt,i=ke,r=await Me("flutterflow"),s=()=>Fp({seq:t,currentSeq:yl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Ft("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&hc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function as(){Mt="",Ze=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow_project_id")}function Cw(){gt+=1,$t=null,wr=null,as();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ft("flutterflow")?(ot="validating",co(ke)):ot="not-configured",bt()}function Pw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Aw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Pw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Fw(async n=>{const i=n.target.value.trim();i&&await co(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&$t?br(n,$t.key,$t.generation):br("",null,null)})}function Fw(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function co(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=vw(),r=++oo,s=gt,o=ke,a=()=>Fp({seq:i,currentSeq:vl,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};$t=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===ke&&(Ft("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;$t={key:t,generation:s};const f=t===ke,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,hc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Mt&&(e.value=Mt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===ke&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Rw(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 $w(){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 Lw(){y.bundleSpec=pr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function uo(){const t=bi(y.bundleSpec);y.artifactBundle=pr(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=Uy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=bi(y.artifactBundle).id}function fo(){const t=pr(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=pr({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Np(){const t=_c();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _c(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||bi(t)}function wc(){return _c().code||y.step2Result||""}async function Nw(){try{await pc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const ls={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Ow(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 In{constructor(e,n,i="main",r=ls.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=[ls.production,ls.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(wl(f?d.clone():d,fp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 xd({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(Ow(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 wl(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 bc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Bw(t,e=fp){const n=t.clone();let i;try{i=JSON.parse(await wl(t,e))}catch{let o="";try{o=await wl(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 ho(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 X={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Op=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Bp=/extends\s+State<\w+>/;function Dw(t,e=""){if(t==="pubspec.yaml")return X.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return X.OTHER;if(t==="custom_functions.dart")return X.FUNCTION;if(e){const n=Op.test(e),i=Bp.test(e);if(n||i)return X.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return X.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return X.FUNCTION}return X.CODE_FILE}function Dp(t,e){switch(e){case X.ACTION:return`lib/custom_code/actions/${t}`;case X.WIDGET:return`lib/custom_code/widgets/${t}`;case X.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case X.CODE_FILE:return`lib/custom_code/${t}`;case X.DEPENDENCIES:return"pubspec.yaml";case X.OTHER:return`lib/custom_code/${t}`;default:return t}}async function po(t,e=new Map){return Sy(t,e)}const bl=new Map,hi=new Map,pi=new Map;function Cr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){bl.delete(Cr(t))}function Xi(t,e,n){const i=Cr(t),r=hi.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?hi.delete(i):hi.set(i,r)}function jw(t,e){Xi(t,e,{uncertain:1})}function Uw(t){const e=Cr(t);pi.set(e,(pi.get(e)??0)+1)}function Hd(t){const e=Cr(t),n=(pi.get(e)??0)-1;n<=0?pi.delete(e):pi.set(e,n)}function bc(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 go(t,e,n=dp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Bw(s)})();return bc(r,n,(s,o)=>{i.stop=!0,Yn(t),Uw(t),r.then(()=>Hd(t),()=>Hd(t)),o(new We("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 Hw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=s_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function Ec(t,e,n,i,r="",s=dp){const o=r_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=b_();let l=!1;const u=u0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch(Fd,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 f0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await bc(g,s,(m,v)=>{p=!1,v(new We("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(Id(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Id(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Yn(t),jw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Xi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&pp(w)&&Xi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await P_({provisionEndpoint:Fd,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Xi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await Hw(t,o,m);throw o_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Yn(t),Xi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Sc(t,e={}){const n=Cr(t);let i=bl.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=cp(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=hi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&hi.delete(n)}!hi.has(n)&&!pi.has(n)&&bl.set(n,i)}const r=await A0(i.pubspecYaml,e),s=s0(i.pubspecYaml,r.overrides),o=r0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Ww(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===X.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=L_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===X.WIDGET){const o=Xh(t.content),a=T_(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=`${Qh(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 jp(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=F_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Xh(s)[0],c=u?Qh(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=X.CODE_FILE;switch(n){case"CustomAction":a=X.ACTION;break;case"CustomWidget":a=X.WIDGET;break;case"CustomFunction":a=X.FUNCTION;break;case"CustomClass":case"CodeFile":a=X.CODE_FILE;break}let l="";return a===X.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 Tw(){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 Mw(){y.bundleSpec=pr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function uo(){const t=bi(y.bundleSpec);y.artifactBundle=pr(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=Dy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=bi(y.artifactBundle).id}function fo(){const t=pr(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=pr({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Np(){const t=_c();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _c(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||bi(t)}function wc(){return _c().code||y.step2Result||""}async function $w(){try{await pc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const ls={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Lw(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 In{constructor(e,n,i="main",r=ls.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=[ls.production,ls.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(wl(f?d.clone():d,fp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 xd({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(Lw(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 wl(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 bc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Nw(t,e=fp){const n=t.clone();let i;try{i=JSON.parse(await wl(t,e))}catch{let o="";try{o=await wl(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 ho(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 X={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Op=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Bp=/extends\s+State<\w+>/;function Ow(t,e=""){if(t==="pubspec.yaml")return X.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return X.OTHER;if(t==="custom_functions.dart")return X.FUNCTION;if(e){const n=Op.test(e),i=Bp.test(e);if(n||i)return X.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return X.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return X.FUNCTION}return X.CODE_FILE}function Dp(t,e){switch(e){case X.ACTION:return`lib/custom_code/actions/${t}`;case X.WIDGET:return`lib/custom_code/widgets/${t}`;case X.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case X.CODE_FILE:return`lib/custom_code/${t}`;case X.DEPENDENCIES:return"pubspec.yaml";case X.OTHER:return`lib/custom_code/${t}`;default:return t}}async function po(t,e=new Map){return by(t,e)}const bl=new Map,hi=new Map,pi=new Map;function Cr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){bl.delete(Cr(t))}function Xi(t,e,n){const i=Cr(t),r=hi.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?hi.delete(i):hi.set(i,r)}function Bw(t,e){Xi(t,e,{uncertain:1})}function Dw(t){const e=Cr(t);pi.set(e,(pi.get(e)??0)+1)}function Hd(t){const e=Cr(t),n=(pi.get(e)??0)-1;n<=0?pi.delete(e):pi.set(e,n)}function bc(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 go(t,e,n=dp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Nw(s)})();return bc(r,n,(s,o)=>{i.stop=!0,Yn(t),Dw(t),r.then(()=>Hd(t),()=>Hd(t)),o(new We("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 jw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=i_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function Ec(t,e,n,i,r="",s=dp){const o=n_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=__();let l=!1;const u=l0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch(Fd,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 u0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await bc(g,s,(m,v)=>{p=!1,v(new We("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(Id(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Id(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Yn(t),Bw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Xi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&pp(w)&&Xi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await k_({provisionEndpoint:Fd,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Xi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await jw(t,o,m);throw r_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Yn(t),Xi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Sc(t,e={}){const n=Cr(t);let i=bl.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=cp(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=hi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&hi.delete(n)}!hi.has(n)&&!pi.has(n)&&bl.set(n,i)}const r=await C0(i.pubspecYaml,e),s=i0(i.pubspecYaml,r.overrides),o=n0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Uw(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===X.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=M_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===X.WIDGET){const o=Xh(t.content),a=F_(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=`${Qh(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 jp(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=Xh(s)[0],c=u?Qh(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=X.CODE_FILE;switch(n){case"CustomAction":a=X.ACTION;break;case"CustomWidget":a=X.WIDGET;break;case"CustomFunction":a=X.FUNCTION;break;case"CustomClass":case"CodeFile":a=X.CODE_FILE;break}let l="";return a===X.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -114,15 +114,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:qy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function qw(t){const e={};for(const n of ec(t))e[n]="";return e}function zw(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 Vw(t,e,n,i=new Set,r=""){const s=[],o=Op.test(e),a=Bp.test(e);return n===X.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function mo(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=>eo(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=Vw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=cp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function xc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(_l(n,e))return n;const i=++oo,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==ke||i<=un||(un=i,!s)?"":Xe&&Xe.projectId!==n&&_l(Xe.projectId,e)?Xe.projectId:((!Xe||Xe.projectId===n)&&br(n,e,r),n)}async function Gw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=X.WIDGET),i==="CustomAction"&&(i=X.ACTION),i==="CustomFunction"&&(i=X.FUNCTION),i==="CustomClass"&&(i=X.CODE_FILE),i==="CodeFile"&&(i=X.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await xc(o);if((o!==ke||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!lo(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||Dw(e,t),f=Dp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=mo(c);if(!p.valid)throw new Error(`Validation failed: +`),{content:Hy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Hw(t){const e={};for(const n of ec(t))e[n]="";return e}function Ww(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 qw(t,e,n,i=new Set,r=""){const s=[],o=Op.test(e),a=Bp.test(e);return n===X.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function mo(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=>eo(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=qw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=cp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function xc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(_l(n,e))return n;const i=++oo,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==ke||i<=un||(un=i,!s)?"":Ze&&Ze.projectId!==n&&_l(Ze.projectId,e)?Ze.projectId:((!Ze||Ze.projectId===n)&&br(n,e,r),n)}async function zw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=X.WIDGET),i==="CustomAction"&&(i=X.ACTION),i==="CustomFunction"&&(i=X.FUNCTION),i==="CustomClass"&&(i=X.CODE_FILE),i==="CodeFile"&&(i=X.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await xc(o);if((o!==ke||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!lo(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||Ow(e,t),f=Dp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=mo(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const h=await Sc(u,r),g=h.yaml,m=await Ec(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await po(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await vo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Yn(u),$e.set("push");const x=await go(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||ho(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function vo(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 Kw(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=jp(t,{artifactType:n,artifactName:i,fileName:r}),u=qw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=sr||await xc(c);if((c!==ke||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Dp(l.fileName,l.codeType),functionName:l.codeType===X.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=mo(h);if(!g.valid)throw new Error(`File validation failed: +`)}`);const h=await Sc(u,r),g=h.yaml,m=await Ec(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await po(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await vo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Yn(u),$e.set("push");const x=await go(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||ho(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function vo(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 Vw(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=jp(t,{artifactType:n,artifactName:i,fileName:r}),u=Hw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=sr||await xc(c);if((c!==ke||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Dp(l.fileName,l.codeType),functionName:l.codeType===X.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=mo(h);if(!g.valid)throw new Error(`File validation failed: ${g.errors.join(` -`)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),Y.setState(ne.PUSHING);const m=new In(c,p,"main",d),v=await Sc(m,u),b=v.yaml,w=await Ec(m,h,v.remoteFiles,`Provision ${i} custom class`,b);o=w.provisionSucceeded===!0;const _=await po(w.syncFileMap,w.remoteFiles),x=new Map(w.syncFileMap);x.set("pubspec.yaml",{content:b,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const I=await vo(x),T={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:b,file_map:_.fileMapContents,functions_map:_.functionsMapContents};Y.setProgress(1,h.size),Yn(m),$e.set("push");const S=await go(m,T);if(S.success){const P={...zw(l,s),projectId:p};return Y.setSuccess({...P,fileCount:h.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:w.unverified,approximate:w.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=S.errorMessage||ho(S.responseCode),R=new Error(P);throw R.errorMap=S.errorMap,R.remoteRefusal=!0,R}}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 We?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...l.finishDeploy?{finishDeploy:cg(l.finishDeploy,a,Y)}:{}}: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,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function Yw(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:ze(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ne.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),Y.setState(ne.PUSHING);const m=new In(c,p,"main",d),v=await Sc(m,u),b=v.yaml,w=await Ec(m,h,v.remoteFiles,`Provision ${i} custom class`,b);o=w.provisionSucceeded===!0;const _=await po(w.syncFileMap,w.remoteFiles),x=new Map(w.syncFileMap);x.set("pubspec.yaml",{content:b,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const I=await vo(x),T={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:b,file_map:_.fileMapContents,functions_map:_.functionsMapContents};Y.setProgress(1,h.size),Yn(m),$e.set("push");const S=await go(m,T);if(S.success){const P={...Ww(l,s),projectId:p};return Y.setSuccess({...P,fileCount:h.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:w.unverified,approximate:w.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=S.errorMessage||ho(S.responseCode),R=new Error(P);throw R.errorMap=S.errorMap,R.remoteRefusal=!0,R}}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 We?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...l.finishDeploy?{finishDeploy:lg(l.finishDeploy,a,Y)}:{}}: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,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function Gw(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:ze(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ne.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===X.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=mo(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=sr||await xc(a);if((a!==ke||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Sc(d,t.dependencies),p=f.yaml,h=await Ec(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await po(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await vo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Yn(d),$e.set("push");const w=await go(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||ho(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:cg(s.finishDeploy,r,Y)}:{}}: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 Jw(t,e=[]){const n=Jl("architect");try{return await Gs("architect",Ip,dy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function yo(t,e,n=[],i){const r=fy(t),s=Jl("generator",y.bundleSpec);try{return await Gs("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),tE(e,Kr,i);try{return await Gs("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 _o(t,e=null){const n={...Jl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Gs("review",kp,hy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function zs(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=` +`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=sr||await xc(a);if((a!==ke||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Sc(d,t.dependencies),p=f.yaml,h=await Ec(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await po(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await vo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Yn(d),$e.set("push");const w=await go(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||ho(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:lg(s.finishDeploy,r,Y)}:{}}: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 Kw(t,e=[]){const n=Jl("architect");try{return await Gs("architect",Ip,cy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function yo(t,e,n=[],i){const r=uy(t),s=Jl("generator",y.bundleSpec);try{return await Gs("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),eE(e,Kr,i);try{return await Gs("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 _o(t,e=null){const n={...Jl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Gs("review",kp,dy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function zs(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=` @@ -130,12 +130,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),zs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),zs(t,"completed"))}function Zw(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 Xw(t){at(parseInt(t.replace("step","")))}function at(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"),Jn();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 Qw(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 El(t){const e=Sl(t);console.log(`Step 1 (Prompt Architect): ${nn(Ip)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(kp)}`)}function Up(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function eb(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=bi(y.artifactBundle)?.id||null)}const Hp="results-replacement-error";function tb(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Hp);if(!r)return;const s=mp(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=`${So[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=()=>Ii(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Ic(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Ic(){const t=document.getElementById(Hp);t&&(t.hidden=!0)}function Wp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),eb(e),Pi(),Bt(!0),Tr(),y.resultsViewMode=e.resultsViewMode||"summary",Rr(),kn(),tb(t,{stage:n,runId:i,retry:r}),pn())}async function qp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=xo();kc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Up();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),zs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),zs(t,"completed"))}function Yw(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 Jw(t){at(parseInt(t.replace("step","")))}function at(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"),Jn();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 Zw(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 El(t){const e=Sl(t);console.log(`Step 1 (Prompt Architect): ${nn(Ip)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(kp)}`)}function Up(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function Xw(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=bi(y.artifactBundle)?.id||null)}const Hp="results-replacement-error";function Qw(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Hp);if(!r)return;const s=mp(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=`${So[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=()=>Ii(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Ic(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Ic(){const t=document.getElementById(Hp);t&&(t.hidden=!0)}function Wp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),Xw(e),Pi(),Bt(!0),Tr(),y.resultsViewMode=e.resultsViewMode||"summary",Rr(),kn(),Qw(t,{stage:n,runId:i,retry:r}),pn())}async function qp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=xo();kc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Up();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{Ic();const r=_c(),s=r.id,o=py({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."});Co({runId:e}),Lt(2,e),at(2),Fe(2,!0);const a=await yo(o,t,[],e);if(!le(e))return;y.step2Result=a,uo(),fn(2,e);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,e),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,fo(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=bi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=ro(r,{architect:2,generator:2,review:3});Wp(r,{previous:i,stage:s,runId:e,retry:qp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function kc(t,e,n){const i=`${Et}/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 nb(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function zp(){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){Se("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=xo();kc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{Ic();const r=_c(),s=r.id,o=fy({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."});Co({runId:e}),Lt(2,e),at(2),Fe(2,!0);const a=await yo(o,t,[],e);if(!le(e))return;y.step2Result=a,uo(),fn(2,e);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,e),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,fo(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=bi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=ro(r,{architect:2,generator:2,review:3});Wp(r,{previous:i,stage:s,runId:e,retry:qp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function kc(t,e,n){const i=`${Et}/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 eb(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function zp(){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){Se("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=xo();kc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Up();try{Ic();const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});bg(),Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=ro(o,{architect:2,generator:2,review:3});Wp(o,{previous:s,stage:a,runId:i,retry:zp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}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=De.slice();if(!t.trim()){Se("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=xo();try{if(await dl,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await kb()||!le(i)||(await wb(),!le(i)))return;const r=Sl(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),$w(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Ys(!0),El(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Co({prompt:t,runId:i}),sE(a,l),at(1),Lt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await Jw(t,u);if(!le(i))return;y.step1Result=c,Lw(),fn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=Si(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Lt(2,i),Fe(2,!0);const p=await yo(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,uo(),fn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=Si(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const m=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,fo(),fn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Pi();const b=so(y.step3Result);Tr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=ro(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():Dn("Pipeline Failed",{error:r.message,effectiveModel:Sl(document.getElementById("code-generator-model").value)}),at(s),Fe(s,!1),vg(r,{stage:s,runId:i}),zs(s,"error")}finally{le(i)&&(y.isRunning=!1,Ys(!1),pn())}}function ib(){const t=document.getElementById("code-generator-model").value,e=[js,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Up();try{Ic();const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});wg(),Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=ro(o,{architect:2,generator:2,review:3});Wp(o,{previous:s,stage:a,runId:i,retry:zp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}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=De.slice();if(!t.trim()){Se("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=xo();try{if(await dl,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await xb(t)||!le(i)||(await yb(),!le(i)))return;const r=Sl(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),Tw(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Ys(!0),El(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Co({prompt:t,runId:i}),rE(a,l),at(1),Lt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await Kw(t,u);if(!le(i))return;y.step1Result=c,Mw(),fn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=Si(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Lt(2,i),Fe(2,!0);const p=await yo(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,uo(),fn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=Si(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const m=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,fo(),fn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Pi();const b=so(y.step3Result);Tr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=ro(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():Dn("Pipeline Failed",{error:r.message,effectiveModel:Sl(document.getElementById("code-generator-model").value)}),at(s),Fe(s,!1),mg(r,{stage:s,runId:i}),zs(s,"error")}finally{le(i)&&(y.isRunning=!1,Ys(!1),pn())}}function tb(){const t=document.getElementById("code-generator-model").value,e=[js,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -143,10 +143,10 @@ 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 rb(){const t=wc();if(!t){Se("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}if(y.artifactBundle?.artifacts?.length>1){await sb();return}const{artifactType:i,artifactName:r,fileName:s}=Np(),o=jp(t,{artifactType:i,artifactName:r,fileName:s}),a=Ww(o);if(!a.canProceed){Se(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Ac(o,a,null,null)}async function sb(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}const n=e_(y.artifactBundle);if(n.errors.length>0){Se(`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=mo(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Se(`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],Sr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],Sr())}async function nb(){const t=wc();if(!t){Se("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}if(y.artifactBundle?.artifacts?.length>1){await ib();return}const{artifactType:i,artifactName:r,fileName:s}=Np(),o=jp(t,{artifactType:i,artifactName:r,fileName:s}),a=Uw(o);if(!a.canProceed){Se(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Ac(o,a,null,null)}async function ib(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}const n=Xy(y.artifactBundle);if(n.errors.length>0){Se(`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=mo(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Se(`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};Ac(o,s,n.dependencies,n)}function ob(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};Ac(o,s,n.dependencies,n)}function rb(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

    FlutterFlow Commit Failed

    ${W(t.error)}

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

    Errors:

    @@ -167,8 +167,8 @@ ${a.content}`).join(` Error: ${g} `}else s+=`${t} -`;const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=ro(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),vg(s,{stage:o,runId:i,retry:()=>Vp(t,e)}),zs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function ab(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 Gp(t){try{const e=await fetch(`${Et}/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 lb(t){try{const n=await(await fetch(`${Et}/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 cb(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Wd(t,e){const n=Yp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,fe=Kn({isLoading:!0}),localStorage.setItem(Os,JSON.stringify({email:t,sessionToken:e})),i&&tg()}function Kp(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),localStorage.removeItem(Os),localStorage.removeItem(Ds)}function Yp(){try{const t=localStorage.getItem(Os);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(Os),{email:null,sessionToken:null}}}async function ub(){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 lb(e);Wd(n,i),Jp();const r=qd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){qd();const i=n.message||"Sign-in link invalid or expired.";Se(i,"error"),wo(),ci(i,"error")}}else{const{email:n,sessionToken:i}=Yp();if(n&&i){const r=await cb(i);r?Wd(r.email,r.sessionToken):Kp()}}Cc()}function db(){try{localStorage.setItem(ul,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function qd(){try{const t=localStorage.getItem(ul);if(localStorage.removeItem(ul),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>q0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function wo(){const t=document.getElementById("signin-modal");if(!t)return;db(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ci(""),Ve(t)}function Jp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function ci(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 fb(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=no(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"),ci("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ep(n);r&&ci(r,"error");try{const s=await Gp(n),o=ic(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ci(tp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ci("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function hb(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),J_({storage:window.localStorage,onIdentityChanged:Cc,onPlanChanged:Eo})}const pb=X_({sendLink:Gp,getEmail:()=>H.email||"",onState:gb});function gb(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=tp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function mb(){await pb()}function vb(){const t=K_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Se(`${e} Your run count, identity and stored keys are kept.`,"info")}function yb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function _b(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Cc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Ab(),Eo()}async function Zp(){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(K0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(V0,r.user_id),yt.token&&sessionStorage.setItem(G0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),_n()}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 va=null;function wb(t=5e3){return yt.resolved?Promise.resolve():(va||(va=Zp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([va,new Promise(e=>setTimeout(e,t))]))}function Xp(){const t=xn();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Pr(){const t=Xp();return t.month!==xn()?{count:0,month:xn()}:t}function bb(){const e={count:Pr().count+1,month:xn()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Ci(){return!!fe.isLoading}function Ot(){return!!fe.isResolved}function Eb(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(Bs,e)?e:null}function Sb(t){return t&&Object.entries(wp).find(([,e])=>e===t)?.[0]||null}function Yr(...t){return t.find(e=>e!=null&&e!=="")}function xb(...t){return t.find(e=>e&&typeof e=="object")||{}}function Ib(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=xb(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=Yr(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=Yr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=Eb(Yr(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=Y0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Sb(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Yr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function bo(){return Bs[fe.tier]??Bs.free}async function kb(){if(H.isVerified&&(!Ot()||Ci())&&(await eg({force:!0}),Eo()),H.isVerified&&!Ot())return Se("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Pr(),e=bo();if(t>=e)return Qp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Se(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function zd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Qp(t,e,n={}){Bt(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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){Se(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ii();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=fe.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",H.isVerified),u.classList.remove("hidden"),n.openModal&&Ii()}function Sl(t){return fe.tier==="free"&&rs.includes(t)?js:t}function Cb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=fe.tier,r=!(H.isVerified&&!Ot())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=rs.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&rs.includes(e.value)&&(e.value=js),e.disabled=!1,Rd.has(e)||(e.addEventListener("change",()=>{Ot()&&fe.tier==="free"&&rs.includes(e.value)&&(e.value=js,Ii()),El(e.value),cc()}),Rd.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(),El(e.value)}function Pc(){const t=H.isVerified&&!!H.email,e=t&&Ci(),n=!t||Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Yl,u=n?fe.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Xp(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Bs.free} generations used`}}Pb()}function Pb(){if(!(H.isVerified&&!!H.email))return;const e=Ci(),n=Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=n?fe.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Zi(Ji[a]??0,uc());h.textContent=`${S} / 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 S=Date.parse(fe.periodEnd||""),P=n&&a!=="free"&&!!fe.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Pc(),H.isVerified&&(Ci()||!Ot())){zd();return}const{count:t}=Pr(),e=bo();t>=e&&!y.isRunning&&!iy()?Qp(t,e):zd()}function Ab(){Pc()}async function eg(t={}){const e=t.force===!0;if(!H.isVerified||!H.sessionToken){fe=Kn({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const n=H.sessionToken,i=localStorage.getItem(Ds);if(!e&&i)try{const{data:r,email:s,ts:o,version:a}=JSON.parse(i);if(a===Td&&s===H.email&&Date.now()-o<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",i)}try{const s=await(await fetch(`${Et}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken,user_id:yt.userId})})).json();if(!H.isVerified||H.sessionToken!==n)return;if(s.error){if(["unauthorized","invalid session","expired session"].some(a=>String(s.error).toLowerCase().includes(a))){Kp(),Cc();return}fe=Kn({isResolved:!1,error:s.error});return}fe=Ib(s),localStorage.setItem(Ds,JSON.stringify({version:Td,data:fe,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function tg(){localStorage.removeItem(Ds)}async function Fb(t){if(!H.isVerified||!H.sessionToken){ig(),wo();return}if(!wp[t]){Se("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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:uc()})})).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"),Se("Could not start checkout. Please try again.","error")}}async function Rb(t){if(!H.isVerified||!H.sessionToken){wo();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Se("Could not open billing portal. Please try again.","error")}}const Vs=new Set;function ng(){Vs.forEach(t=>t.abort()),Vs.clear()}async function Gs(t,e,n,i={},r=[]){const o=new AbortController;Vs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(z0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Wn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=by(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),_n())}else bb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Vs.delete(o)}}let xl=!1;function Tb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),tg(),xl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Se("Checkout cancelled.","info")),e}function Mb(){if(!xl)return;xl=!1;const t=fe.tier!=="free";Se(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Eo(){const t=H.isVerified&&!!H.email,e=fe.tier,n=t&&Ci(),i=!t||Ot(),r=document.getElementById("subscription-tier-badge");if(r){const a=Yl,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"),$b(i?e:null),Cb(),cc(),_n(),Eg()}function $b(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 Lb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=ly[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 Il(){const t=uc(),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=Zi(Ji.professional,t)),n&&(n.textContent=Zi(Ji.power,t)),i&&(i.textContent=Zi(Ji.professional,t)),r&&(r.textContent=Zi(Ji.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ii(){Il();const t=document.getElementById("pricing-modal");t&&Ve(t),ow().then(()=>Il())}function ig(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Se(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()=>{sy(),Jb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Nb(),window.__heroField=p0(),window.__pipelineLogo=y0(),vE(),lc=B0({onSubmit:Sr}),dl=(async()=>{try{await ub(),Tb(),await eg()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await dl,Mb(),Eo(),Il(),Lb(),await Nw(),Rw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Lp(),Zp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(mc(),ao())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(dg(),$e.phaseId||Rc(),Gd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(Gd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,Tc()},1e3))}),jc()});function Nb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Ob(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Lp()}let or=null;async function kl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Od,n=++oo,i=()=>e===Od,r=gt;wr=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==ke)return kl();if(n>un&&(un=n,hc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),wr={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==ke)return kl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function Bb(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=wr;return!n||n.key!==ke||n.generation!==gt?null:e}function Ac(t,e,n,i=null){or={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,kl();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function rg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),or=null}function Db(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 sg(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function og(t){Tc(),ob(t);const e=t.remoteRefusal===!0;Fc(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 Fc(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(nc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function ag(t){Fc(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 lg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Cl=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Fc(t,{heading:e,title:n,guidance:i})}let Cl=null;function cg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function jb(){const t=Cl;if(!t||Mc)return;Cl=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);ug(),$c(!0),Rc();try{$e.set("package");const n=a_(t.fileMap,t.landed,t.serializedYaml),i=await po(n,new Map),r=await vo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),$e.set("push");const o=await go(e,s);if(o.success){Ks({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||ho(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ks({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function ug(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function Ub(){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 Vd={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}},Hb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function dg(){Un&&clearTimeout(Un),Un=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){dg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(sd(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Vd[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=Vd[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=Hb.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(Wb(e)),fg(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&&(sd(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function Wb(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 Rc(t){$e.start(t)}function Tc(){$e.stop()}function fg(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Gd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,fg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function qb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===X.CODE_FILE):t.codeInfo?.codeType===X.CODE_FILE}let Mc=!1;function $c(t){Mc=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 Ks(t){Tc(),$c(!1);const e=hp(t);e===Ne.COMMITTED?sg(t):e===Ne.PARTIAL?ag(t):e===Ne.UNCONFIRMED?lg(t):og(t)}async function zb(){if(!or){console.error("No pending commit data");return}if(Mc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=or;if(or=null,sr=Bb(),rg(),$c(!0),Rc({withProvisioning:qb(t)}),t.bundlePlan){const o=await Yw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Np(),s=await Kw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(s)}window.runThinkingPipeline=Sr;window.toggleStep=Xw;window.toggleSection=Zw;window.selectWorkflowStep=at;window.copyCode=Qw;window.retryWithDifferentModel=ib;window.openApiKeysModal=gc;window.closeApiKeysModal=Mp;window.openComposerSettings=Tp;window.closeComposerSettings=Ew;window.walkthroughConnectAccount=bw;window.closeWalkthroughModal=xw;window.openWalkthroughModal=Sw;window.advanceWalkthrough=mc;window.commitToFlutterFlow=Gw;function Vb(){y.isRunning||Bt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Gb(){Tp();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Vb;window.openModelSelector=Gb;window.handlePromptImageSelect=rw;window.removePromptImage=sw;window.saveApiKeys=Cw;window.validateFlutterFlowConnection=yc;window.clearAllApiKeys=Pw;window.toggleKeyVisibility=Mw;window.handleWelcomeVideoEnd=Ob;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=rb;window.updateFlutterFlowCredentialStatus=ab;window.openCommitConfirmModal=Ac;window.closeCommitConfirmModal=rg;window.closeCommitSuccessModal=Db;window.closeCommitTerminalModal=ug;window.finishProvisionedDeploy=jb;window.showCommitPartialModal=ag;window.showCommitUnconfirmedModal=lg;window.showCommitSuccessModal=sg;window.showCommitFailureModal=og;window.toggleCodePreview=Ub;window.confirmCommitToFlutterFlow=zb;window.runRefinement=qp;window.regenerateFromPastedErrors=zp;window.clearErrorInput=nb;window.setFlutterFlowEndpoint=yw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=wo;window.closeSignInModal=Jp;window.handleMagicLinkRequest=fb;window.handleSignOut=hb;window.handleSendNewLink=mb;window.handleClearCache=vb;window.handleDeleteAccount=yb;window.closeDeleteUnavailableModal=_b;window.startCheckout=Fb;window.openCustomerPortal=Rb;window.openPricingModal=Ii;window.closePricingModal=ig;let cs=null,hg=null,hn={1:"pending",2:"pending",3:"pending"},qn=1,Pl=null,Lc=null;const So={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Kb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Yb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function xo(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function pg(){y.runId+=1}function Nc(t){return document.getElementById(`pdot-${t}`)}const gg=window.matchMedia("(max-width: 920px)");function Kd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=gg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Jb(){Kd(),gg.addEventListener("change",Kd)}function Zb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Ys(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 Io(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){hn[t]=e;const n=Nc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=So[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 Xb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Ar(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${Qb()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function Qb(){const t=33.333333333333336,e=hn[qn];if(e==="active"&&Pl!==null){const n=(Date.now()-Pl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:Xb()/3*100}function ko(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?Yb[t]:Kb[t]),i&&(i.textContent=Zb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${So[t]}${a}`}}function eE(t){hn[t]==="pending"||hn[t]==="skipped"||(Lc=t,[1,2,3].forEach(e=>{const n=Nc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),ko(t))}function Oc(){Lc=null,[1,2,3].forEach(t=>{const e=Nc(t);e&&e.removeAttribute("aria-pressed")})}function mg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function tE(t,e,n){le(n)&&mg(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function Bc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function nE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Gn()}function iE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function rE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=rE;function sE(t,e){_p(t,document.getElementById("main-stage-container"),iE()),U0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function Co(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Fr(),kn(),Bt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),Io("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}hg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Oc(),Bc(),mg(""),[1,2,3].forEach(a=>zn(a,"pending")),Lt(1,n),oE()}function Lt(t,e){le(e)&&(qn=t,Pl=Date.now(),Oc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),ko(t),Ar())}function fn(t,e){le(e)&&(zn(t,"done"),Lc===null&&ko(t,{done:!0}),Ar())}function vg(t,{stage:e=1,runId:n,retry:i=yg}={}){if(!le(n))return;Po(),Fr(),kn(),Io("failed"),Bt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Oc(),ko(e),Ar();const o=mp(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=`${So[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>Ii()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Al}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Al}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Al(){pg(),ng(),y.isRunning=!1,Ys(!1),pn(),Io("settled"),kn(),Po(),Fr(),Bc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Bt(!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 yg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),Bc(),Sr()}function oE(){Po(),cs=setInterval(()=>{const t=(Date.now()-hg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Ar()},250)}function Po(){cs&&(clearInterval(cs),cs=null)}let ar=null;function Fr(){ar&&(clearTimeout(ar),ar=null)}function Pi(){Po(),Fr(),Io("settled"),Ar();const t=document.getElementById("pipeline-progress-fill");ar=setTimeout(()=>{ar=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function ki(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function _g(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function aE(){return y_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function lE(t){return` +`;const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=ro(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),mg(s,{stage:o,runId:i,retry:()=>Vp(t,e)}),zs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function sb(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 Gp(t){try{const e=await fetch(`${Et}/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 ob(t){try{const n=await(await fetch(`${Et}/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 ab(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Wd(t,e){const n=Yp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,fe=Kn({isLoading:!0}),localStorage.setItem(Os,JSON.stringify({email:t,sessionToken:e})),i&&eg()}function Kp(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),localStorage.removeItem(Os),localStorage.removeItem(Ds)}function Yp(){try{const t=localStorage.getItem(Os);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(Os),{email:null,sessionToken:null}}}async function lb(){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 ob(e);Wd(n,i),Jp();const r=qd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){qd();const i=n.message||"Sign-in link invalid or expired.";Se(i,"error"),wo(),ci(i,"error")}}else{const{email:n,sessionToken:i}=Yp();if(n&&i){const r=await ab(i);r?Wd(r.email,r.sessionToken):Kp()}}Cc()}function cb(){try{localStorage.setItem(ul,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function qd(){try{const t=localStorage.getItem(ul);if(localStorage.removeItem(ul),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>H0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function wo(){const t=document.getElementById("signin-modal");if(!t)return;cb(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ci(""),Ve(t)}function Jp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function ci(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 ub(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=no(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"),ci("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ep(n);r&&ci(r,"error");try{const s=await Gp(n),o=ic(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ci(tp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ci("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function db(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),K_({storage:window.localStorage,onIdentityChanged:Cc,onPlanChanged:Eo})}const fb=J_({sendLink:Gp,getEmail:()=>H.email||"",onState:hb});function hb(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=tp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function pb(){await fb()}function gb(){const t=V_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Se(`${e} Your run count, identity and stored keys are kept.`,"info")}function mb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function vb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Cc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Pb(),Eo()}async function Zp(){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(V0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(q0,r.user_id),yt.token&&sessionStorage.setItem(z0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),_n()}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 va=null;function yb(t=5e3){return yt.resolved?Promise.resolve():(va||(va=Zp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([va,new Promise(e=>setTimeout(e,t))]))}function Xp(){const t=xn();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Pr(){const t=Xp();return t.month!==xn()?{count:0,month:xn()}:t}function _b(){const e={count:Pr().count+1,month:xn()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Ci(){return!!fe.isLoading}function Ot(){return!!fe.isResolved}function wb(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(Bs,e)?e:null}function bb(t){return t&&Object.entries(wp).find(([,e])=>e===t)?.[0]||null}function Yr(...t){return t.find(e=>e!=null&&e!=="")}function Eb(...t){return t.find(e=>e&&typeof e=="object")||{}}function Sb(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=Eb(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=Yr(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=Yr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=wb(Yr(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=G0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||bb(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Yr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function bo(){return Bs[fe.tier]??Bs.free}async function xb(t){if(H.isVerified&&(!Ot()||Ci())&&(await Qp({force:!0}),Eo()),H.isVerified&&!Ot())return Se("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:e}=Pr(),n=bo();if(e>=n)return Ib(e,n,{openModal:!0,prompt:t}),!1;const i=Math.floor(n*.8);if(e>=i){const r=n-e;Se(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function zd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ib(t,e,n={}){Bt(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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){Se(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ii();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=fe.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");if(d&&d.classList.toggle("hidden",H.isVerified),n.prompt!=null){y.submittedPrompt=n.prompt;const f=document.getElementById("pipeline-submitted-prompt");f&&(f.textContent=n.prompt)}u.classList.remove("hidden"),n.openModal&&Ii()}function Sl(t){return fe.tier==="free"&&rs.includes(t)?js:t}function kb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=fe.tier,r=!(H.isVerified&&!Ot())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=rs.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&rs.includes(e.value)&&(e.value=js),e.disabled=!1,Rd.has(e)||(e.addEventListener("change",()=>{Ot()&&fe.tier==="free"&&rs.includes(e.value)&&(e.value=js,Ii()),El(e.value),cc()}),Rd.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(),El(e.value)}function Pc(){const t=H.isVerified&&!!H.email,e=t&&Ci(),n=!t||Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Yl,u=n?fe.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Xp(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Bs.free} generations used`}}Cb()}function Cb(){if(!(H.isVerified&&!!H.email))return;const e=Ci(),n=Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=n?fe.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Zi(Ji[a]??0,uc());h.textContent=`${S} / 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 S=Date.parse(fe.periodEnd||""),P=n&&a!=="free"&&!!fe.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Pc(),H.isVerified&&(Ci()||!Ot())){zd();return}const{count:t}=Pr();tString(s.error).toLowerCase().includes(a))){Kp(),Cc();return}fe=Kn({isResolved:!1,error:s.error});return}fe=Sb(s),localStorage.setItem(Ds,JSON.stringify({version:Td,data:fe,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function eg(){localStorage.removeItem(Ds)}async function Ab(t){if(!H.isVerified||!H.sessionToken){ng(),wo();return}if(!wp[t]){Se("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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:uc()})})).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"),Se("Could not start checkout. Please try again.","error")}}async function Fb(t){if(!H.isVerified||!H.sessionToken){wo();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Se("Could not open billing portal. Please try again.","error")}}const Vs=new Set;function tg(){Vs.forEach(t=>t.abort()),Vs.clear()}async function Gs(t,e,n,i={},r=[]){const o=new AbortController;Vs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(W0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Wn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=_y(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),_n())}else _b(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Vs.delete(o)}}let xl=!1;function Rb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),eg(),xl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Se("Checkout cancelled.","info")),e}function Tb(){if(!xl)return;xl=!1;const t=fe.tier!=="free";Se(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Eo(){const t=H.isVerified&&!!H.email,e=fe.tier,n=t&&Ci(),i=!t||Ot(),r=document.getElementById("subscription-tier-badge");if(r){const a=Yl,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"),Mb(i?e:null),kb(),cc(),_n(),bg()}function Mb(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 $b(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=oy[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 Il(){const t=uc(),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=Zi(Ji.professional,t)),n&&(n.textContent=Zi(Ji.power,t)),i&&(i.textContent=Zi(Ji.professional,t)),r&&(r.textContent=Zi(Ji.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ii(){Il();const t=document.getElementById("pricing-modal");t&&Ve(t),rw().then(()=>Il())}function ng(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Se(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()=>{iy(),Yb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Lb(),window.__heroField=f0(),window.__pipelineLogo=m0(),mE(),lc=N0({onSubmit:Sr}),dl=(async()=>{try{await lb(),Rb(),await Qp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await dl,Tb(),Eo(),Il(),$b(),await $w(),Aw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Lp(),Zp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(mc(),ao())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(ug(),$e.phaseId||Rc(),Gd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(Gd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,Tc()},1e3))}),jc()});function Lb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Nb(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Lp()}let or=null;async function kl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Od,n=++oo,i=()=>e===Od,r=gt;wr=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==ke)return kl();if(n>un&&(un=n,hc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),wr={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==ke)return kl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function Ob(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=wr;return!n||n.key!==ke||n.generation!==gt?null:e}function Ac(t,e,n,i=null){or={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,kl();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function ig(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),or=null}function Bb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 rg(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function sg(t){Tc(),rb(t);const e=t.remoteRefusal===!0;Fc(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 Fc(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(nc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function og(t){Fc(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 ag(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Cl=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Fc(t,{heading:e,title:n,guidance:i})}let Cl=null;function lg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function Db(){const t=Cl;if(!t||Mc)return;Cl=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);cg(),$c(!0),Rc();try{$e.set("package");const n=s_(t.fileMap,t.landed,t.serializedYaml),i=await po(n,new Map),r=await vo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),$e.set("push");const o=await go(e,s);if(o.success){Ks({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||ho(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ks({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function cg(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function jb(){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 Vd={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}},Ub=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function ug(){Un&&clearTimeout(Un),Un=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){ug(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(sd(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Vd[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=Vd[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=Ub.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(Hb(e)),dg(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&&(sd(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function Hb(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 Rc(t){$e.start(t)}function Tc(){$e.stop()}function dg(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Gd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,dg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function Wb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===X.CODE_FILE):t.codeInfo?.codeType===X.CODE_FILE}let Mc=!1;function $c(t){Mc=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 Ks(t){Tc(),$c(!1);const e=hp(t);e===Ne.COMMITTED?rg(t):e===Ne.PARTIAL?og(t):e===Ne.UNCONFIRMED?ag(t):sg(t)}async function qb(){if(!or){console.error("No pending commit data");return}if(Mc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=or;if(or=null,sr=Ob(),ig(),$c(!0),Rc({withProvisioning:Wb(t)}),t.bundlePlan){const o=await Gw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Np(),s=await Vw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(s)}window.runThinkingPipeline=Sr;window.toggleStep=Jw;window.toggleSection=Yw;window.selectWorkflowStep=at;window.copyCode=Zw;window.retryWithDifferentModel=tb;window.openApiKeysModal=gc;window.closeApiKeysModal=Mp;window.openComposerSettings=Tp;window.closeComposerSettings=ww;window.walkthroughConnectAccount=_w;window.closeWalkthroughModal=Ew;window.openWalkthroughModal=bw;window.advanceWalkthrough=mc;window.commitToFlutterFlow=zw;function zb(){y.isRunning||Bt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Vb(){Tp();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=zb;window.openModelSelector=Vb;window.handlePromptImageSelect=nw;window.removePromptImage=iw;window.saveApiKeys=Iw;window.validateFlutterFlowConnection=yc;window.clearAllApiKeys=kw;window.toggleKeyVisibility=Rw;window.handleWelcomeVideoEnd=Nb;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=nb;window.updateFlutterFlowCredentialStatus=sb;window.openCommitConfirmModal=Ac;window.closeCommitConfirmModal=ig;window.closeCommitSuccessModal=Bb;window.closeCommitTerminalModal=cg;window.finishProvisionedDeploy=Db;window.showCommitPartialModal=og;window.showCommitUnconfirmedModal=ag;window.showCommitSuccessModal=rg;window.showCommitFailureModal=sg;window.toggleCodePreview=jb;window.confirmCommitToFlutterFlow=qb;window.runRefinement=qp;window.regenerateFromPastedErrors=zp;window.clearErrorInput=eb;window.setFlutterFlowEndpoint=mw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=wo;window.closeSignInModal=Jp;window.handleMagicLinkRequest=ub;window.handleSignOut=db;window.handleSendNewLink=pb;window.handleClearCache=gb;window.handleDeleteAccount=mb;window.closeDeleteUnavailableModal=vb;window.startCheckout=Ab;window.openCustomerPortal=Fb;window.openPricingModal=Ii;window.closePricingModal=ng;let cs=null,fg=null,hn={1:"pending",2:"pending",3:"pending"},qn=1,Pl=null,Lc=null;const So={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Gb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Kb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function xo(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function hg(){y.runId+=1}function Nc(t){return document.getElementById(`pdot-${t}`)}const pg=window.matchMedia("(max-width: 920px)");function Kd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=pg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Yb(){Kd(),pg.addEventListener("change",Kd)}function Jb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Ys(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 Io(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){hn[t]=e;const n=Nc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=So[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 Zb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Ar(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${Xb()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function Xb(){const t=33.333333333333336,e=hn[qn];if(e==="active"&&Pl!==null){const n=(Date.now()-Pl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:Zb()/3*100}function ko(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?Kb[t]:Gb[t]),i&&(i.textContent=Jb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${So[t]}${a}`}}function Qb(t){hn[t]==="pending"||hn[t]==="skipped"||(Lc=t,[1,2,3].forEach(e=>{const n=Nc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),ko(t))}function Oc(){Lc=null,[1,2,3].forEach(t=>{const e=Nc(t);e&&e.removeAttribute("aria-pressed")})}function gg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function eE(t,e,n){le(n)&&gg(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function Bc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function tE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Gn()}function nE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function iE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=iE;function rE(t,e){_p(t,document.getElementById("main-stage-container"),nE()),D0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function Co(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Fr(),kn(),Bt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),Io("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}fg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Oc(),Bc(),gg(""),[1,2,3].forEach(a=>zn(a,"pending")),Lt(1,n),sE()}function Lt(t,e){le(e)&&(qn=t,Pl=Date.now(),Oc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),ko(t),Ar())}function fn(t,e){le(e)&&(zn(t,"done"),Lc===null&&ko(t,{done:!0}),Ar())}function mg(t,{stage:e=1,runId:n,retry:i=vg}={}){if(!le(n))return;Po(),Fr(),kn(),Io("failed"),Bt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Oc(),ko(e),Ar();const o=mp(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=`${So[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>Ii()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Al}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Al}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Al(){hg(),tg(),y.isRunning=!1,Ys(!1),pn(),Io("settled"),kn(),Po(),Fr(),Bc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Bt(!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 vg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),Bc(),Sr()}function sE(){Po(),cs=setInterval(()=>{const t=(Date.now()-fg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Ar()},250)}function Po(){cs&&(clearInterval(cs),cs=null)}let ar=null;function Fr(){ar&&(clearTimeout(ar),ar=null)}function Pi(){Po(),Fr(),Io("settled"),Ar();const t=document.getElementById("pipeline-progress-fill");ar=setTimeout(()=>{ar=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function ki(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function yg(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function oE(){return m_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function aE(t){return`
    ${ki(t.severity)}
    @@ -177,14 +177,14 @@ Error: ${g} ${W(t.source)}
    - `}function cE(t){return` + `}function lE(t){return`
  • ${W(t.title)} ${t.detail&&t.detail!==t.title?`

    ${W(t.detail)}

    `:""}
  • - `}function uE(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 cE(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=>`
    • @@ -251,14 +251,14 @@ Error: ${g}
    - `}function dE(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(lE).join(""):`
    ${ki(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` + `}function uE(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(aE).join(""):`
    ${ki(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>`
  • ${W(l.name)}${l.version?` ${W(l.version)}`:""}${l.reason?`

    ${W(l.reason)}

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

    ${W(l.description)}

    `:""}
  • `).join(""):'
  • No relationships for this file
  • ';return`
    - ${ki(e.status)} ${W(_g(e.status))} + ${ki(e.status)} ${W(yg(e.status))}

    ${W(e.artifactName)}

    ${e.description?`

    ${W(e.description)}

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

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(cE).join("")}
    +
      ${e.manualSteps.map(lE).join("")}
    `:""}
    @@ -306,7 +306,7 @@ Error: ${g}
      ${a}
    - `}function fE(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=""),Yd();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 dE(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=""),Yd();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&&Dc(o.dataset.artifactId)},Yd()),e&&e.classList.add("visible")}function Yd(){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")wg();else{const a=s.dataset.artifactId;a&&Dc(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 Rr(){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=aE(),o=wc();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")}uE(s),fE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` -`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=vp(a),!nE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=dE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Tr(t,e){const n=document.getElementById("main-stage-container"),i=D0(n),r=document.body.classList.contains("results-fullscreen");Fr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),Bt(!0),y.selectedArtifactId||(y.selectedArtifactId=bi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Rr(),pn(),hE(),r||_p(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function hE(){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=""),Fl=!1}function Dc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Rr()}function wg(){y.resultsViewMode="summary",Rr()}function pE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=wc(),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 Fl=!1;async function gE(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Fl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Fl=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 kc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function mE(){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 bg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function vE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function Bt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function Eg(){const t=H.isVerified&&!!H.email,e=fe.tier||"free",n=t&&Ci(),i=!t||Ot(),s=n?"Checking…":i?Yl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Pc();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 yE(){Eg();const t=document.getElementById("credits-modal");t&&Ve(t)}function _E(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function Sg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),lc?.cancelTyping?.(),y.isRunning&&(pg(),ng(),y.isRunning=!1,Ys(!1),Pi(),y.artifactBundle?Rr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")Bt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&Bt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let Jd=!1;function jc(){const t=window.location.hash.replace(/^#/,"");Sg(t||"home",!1,Jd),Jd=!0}window.addEventListener("popstate",t=>{jc()});window.addEventListener("hashchange",()=>{jc()});window.copyResultsCode=pE;window.selectArtifact=Dc;window.selectResultsSummary=wg;window.submitResultsFeedback=gE;window.showErrorInputPanel=mE;window.hideErrorInputPanel=bg;window.setGenerationStageVisible=Bt;window.switchView=Sg;window.selectPipelineStage=eE;window.editPipelinePrompt=Al;window.retryPipelineRun=yg;window.openCreditsModal=yE;window.closeCreditsModal=_E; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&Dc(o.dataset.artifactId)},Yd()),e&&e.classList.add("visible")}function Yd(){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")_g();else{const a=s.dataset.artifactId;a&&Dc(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 Rr(){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=oE(),o=wc();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")}cE(s),dE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` +`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=vp(a),!tE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=uE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Tr(t,e){const n=document.getElementById("main-stage-container"),i=O0(n),r=document.body.classList.contains("results-fullscreen");Fr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),Bt(!0),y.selectedArtifactId||(y.selectedArtifactId=bi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Rr(),pn(),fE(),r||_p(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function fE(){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=""),Fl=!1}function Dc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Rr()}function _g(){y.resultsViewMode="summary",Rr()}function hE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=wc(),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 Fl=!1;async function pE(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Fl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Fl=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 kc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function gE(){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 wg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function mE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function Bt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function bg(){const t=H.isVerified&&!!H.email,e=fe.tier||"free",n=t&&Ci(),i=!t||Ot(),s=n?"Checking…":i?Yl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Pc();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 vE(){bg();const t=document.getElementById("credits-modal");t&&Ve(t)}function yE(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function Eg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),lc?.cancelTyping?.(),y.isRunning&&(hg(),tg(),y.isRunning=!1,Ys(!1),Pi(),y.artifactBundle?Rr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")Bt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&Bt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let Jd=!1;function jc(){const t=window.location.hash.replace(/^#/,"");Eg(t||"home",!1,Jd),Jd=!0}window.addEventListener("popstate",t=>{jc()});window.addEventListener("hashchange",()=>{jc()});window.copyResultsCode=hE;window.selectArtifact=Dc;window.selectResultsSummary=_g;window.submitResultsFeedback=pE;window.showErrorInputPanel=gE;window.hideErrorInputPanel=wg;window.setGenerationStageVisible=Bt;window.switchView=Eg;window.selectPipelineStage=Qb;window.editPipelinePrompt=Al;window.retryPipelineRun=vg;window.openCreditsModal=vE;window.closeCreditsModal=yE; diff --git a/dist/index.html b/dist/index.html index be0cc03..3c507a0 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3273,7 +3273,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu382-plans-paywall.spec.js b/e2e/stu382-plans-paywall.spec.js index 32f9d72..a3e2ab0 100644 --- a/e2e/stu382-plans-paywall.spec.js +++ b/e2e/stu382-plans-paywall.spec.js @@ -8,6 +8,7 @@ import { ENDPOINTS, checkoutSession, } from "./fixtures/apiFixtures.js"; +import { PLAN_LIMITS } from "../src/plansSurface.js"; /** * STU-382 — the plans surface and paywall states must be backed by real @@ -72,6 +73,50 @@ test.describe("STU-382 plans surface and paywall states", () => { await page.addInitScript(() => localStorage.setItem("hasSeenWalkthrough", "true")); }); + test("an out-of-runs user writes their prompt first; the paywall answers the submit", async ({ page }) => { + const pipelineRequests = []; + page.on("request", (request) => { + if (request.url().startsWith(ENDPOINTS.pipeline)) pipelineRequests.push(request.url()); + }); + await applyDefaultRoutes(page, { + [ENDPOINTS.identity]: identityWithUsage({ count: PLAN_LIMITS.free, status: "guest" }), + [ENDPOINTS.getSubscription]: freeSubscription(), + }); + await page.goto("/"); + + // Wait for the startup usage decision to land at the limit: the page still + // opens on the composer, not the exhausted screen. + await page.waitForFunction( + (limit) => JSON.parse(localStorage.getItem("ccc_usage") || "{}").count >= limit, + PLAN_LIMITS.free, + { timeout: 8000 }, + ); + const field = page.locator("#pipeline-input"); + await expect(field).toBeVisible(); + await expect(page.locator("#paywall-exhausted")).toBeHidden(); + await expect(page.locator("#generation-stage")).toBeHidden(); + + // Submitting the prompt is what surfaces the paywall, with the prompt in + // the recap and pricing open — and no generation request leaves. + const prompt = "A habit tracker heatmap with streak counts"; + await field.fill(prompt); + await page.locator("#hero-send").click(); + await expect(page.locator("#paywall-exhausted")).toBeVisible(); + await expect(page.locator("#paywall-exhausted-text")).toContainText( + `You've used all ${PLAN_LIMITS.free} free generations this month.`, + ); + await expect(page.locator("#pipeline-submitted-prompt")).toHaveText(prompt); + await expect(page.locator("#pricing-modal")).toHaveClass(/open/); + + // Edit prompt goes back to the composer holding what the user wrote. + await page.keyboard.press("Escape"); + await expect(page.locator("#pricing-modal")).not.toHaveClass(/open/); + await page.locator("#pipeline-edit-prompt").click(); + await expect(page.locator("#generation-stage")).toBeHidden(); + await expect(field).toHaveValue(prompt); + expect(pipelineRequests).toEqual([]); + }); + test("C1: professional labels and current-plan indicators agree across surfaces", async ({ page }) => { await seedSession(page); await applyDefaultRoutes(page, { diff --git a/e2e/stu391-tutorial-onboarding.spec.js b/e2e/stu391-tutorial-onboarding.spec.js index 0952553..451f700 100644 --- a/e2e/stu391-tutorial-onboarding.spec.js +++ b/e2e/stu391-tutorial-onboarding.spec.js @@ -108,9 +108,9 @@ async function clickInsideWalkthrough(page, selector) { // so a returning-user reopen goes through the app's own modal function. On a // cold start the deferred app.js module may not have wired openWalkthroughModal // yet — wait for the wire-up first. The startup usage pass is awaited only so -// usage state settles: an exhausted allowance is suppressed while a dialog is -// open (updateUsageDisplay gates on !hasActiveModal()), so it can no longer -// close a walkthrough opened mid-flight. Then wait for the open animation. +// usage state settles: a usage update never surfaces the paywall (only a run +// attempt does), so it can't close a walkthrough opened mid-flight. Then wait +// for the open animation. async function reopenWalkthrough(page) { await page.waitForFunction( () => typeof window.openWalkthroughModal === "function", @@ -347,22 +347,19 @@ test.describe("STU-391 tutorial + connection onboarding", () => { }); // Contract: the startup usage decision is PASSIVE, and a passive exhausted - // decision must never take a tour the user is reading away from them. - // resolveIdentity lands its metered count asynchronously and, when that count - // is exhausted, renders the paywall state through updateUsageDisplay -> - // showPaywallExhausted. updateUsageDisplay defers the ENTIRE paywall while - // any dialog is open, so the exhausted surface is held back — it is not - // rendered alongside the tour, and the tour is not closed either. The identity - // response is gated so the tour is guaranteed open when the decision arrives - // (the exact sequence the original flake pinned), and the persisted metered - // count is cleared first so "the decision landed" is observed, not assumed: - // resolveIdentity writes it and calls updateUsageDisplay in one synchronous - // block, so the key reappearing at the limit means the decision has fully run. - // Once no dialog is open, the very next usage decision DOES surface the - // paywall — the deferral is a delay, never a suppression. A run attempt is not - // passive: an out-of-runs run must still surface the paywall, take the tour - // with it, and open pricing. - test("the startup paywall decision defers the paywall while a tour is open; an out-of-runs run attempt still surfaces it", async ({ page }) => { + // decision never surfaces the paywall at all. resolveIdentity lands its + // metered count asynchronously and calls updateUsageDisplay, which only ever + // clears the paywall: an out-of-runs user lands on the composer and writes + // their prompt first, and a tour they are reading is never taken away. The + // identity response is gated so the tour is guaranteed open when the + // decision arrives (the exact sequence the original flake pinned), and the + // persisted metered count is cleared first so "the decision landed" is + // observed, not assumed: resolveIdentity writes it and calls + // updateUsageDisplay in one synchronous block, so the key reappearing at the + // limit means the decision has fully run. A run attempt is not passive: an + // out-of-runs run surfaces the paywall with the submitted prompt, takes the + // tour with it, and opens pricing. + test("an out-of-runs startup never surfaces the paywall; a run attempt does, with the prompt", async ({ page }) => { let releaseIdentity; const identityGate = new Promise((resolve) => { releaseIdentity = resolve; @@ -411,7 +408,7 @@ test.describe("STU-391 tutorial + connection onboarding", () => { { timeout: 8000 }, ); - // The passive decision defers the paywall entirely while the tour is open: + // The passive decision leaves the paywall alone while the tour is open: // the exhausted surface is not rendered, and the tour the user is reading // is neither hidden nor closed. await expect(page.locator("#paywall-exhausted")).toBeHidden(); @@ -425,11 +422,21 @@ test.describe("STU-391 tutorial + connection onboarding", () => { await clickInsideWalkthrough(page, ".wt-gotit-btn"); await expect(page.locator(WALKTHROUGH)).toBeHidden(); - // Deferral is a delay, not a suppression: the next passive usage decision - // with nothing open renders the exhausted surface. + // With nothing open, the passive decision still leaves the user on the + // composer: they write their prompt before they learn they are out of runs. + // Clear the persisted count first so the reloaded page's own decision is + // what the wait observes. + await page.evaluate(() => localStorage.removeItem("ccc_usage")); await page.reload(); await expect(page.locator(WALKTHROUGH)).toBeHidden(); - await expect(page.locator("#paywall-exhausted")).toBeVisible(); + await page.waitForFunction( + (limit) => JSON.parse(localStorage.getItem("ccc_usage") || "{}").count >= limit, + PLAN_LIMITS.free, + { timeout: 8000 }, + ); + await expect(page.locator("#pipeline-input")).toBeVisible(); + await expect(page.locator("#paywall-exhausted")).toBeHidden(); + await expect(page.locator("#generation-stage")).toBeHidden(); // A run attempt is not passive: an out-of-runs run must surface the paywall // in place of the tour, and open pricing so the user can act on it. @@ -444,5 +451,9 @@ test.describe("STU-391 tutorial + connection onboarding", () => { await expect(page.locator(WALKTHROUGH)).toHaveAttribute("aria-hidden", "true"); await expect(page.locator("#paywall-exhausted")).toBeVisible(); await expect(page.locator("#pricing-modal")).toHaveClass(/open/); + // The paywall answers the submitted prompt: it sits in the recap. + await expect(page.locator("#pipeline-submitted-prompt")).toHaveText( + "A circular progress gauge", + ); }); }); diff --git a/src/sharedControls.js b/src/sharedControls.js index 2a9807c..ad4b722 100644 --- a/src/sharedControls.js +++ b/src/sharedControls.js @@ -110,10 +110,6 @@ export function closeModal(modalOrId, options = {}) { return true; } -export function hasActiveModal() { - return Boolean(activeModal); -} - export function setModalPending(modalOrId, pending, message = "Operation in progress") { const modal = typeof modalOrId === "string" ? document.getElementById(modalOrId) : modalOrId; if (!modal) return; From 5c619f9310e8d3cfdfd2a01a7c59f7f016ec07e2 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:02:49 +0000 Subject: [PATCH 03/10] fix(paywall): keep Home on the composer after editing or a quota correction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two Devin Review findings on #127: - A usage update that dropped the count below the limit while the paywall was up hid the paywall but left the generation stage owning Home, so the user faced an empty panel instead of the composer. updateUsageDisplay() now also restores the composer when the paywall it hides was the live panel — covering both the count correction and the unresolved- subscription paths, and leaving progress/results panels alone. - Edit prompt hid the stage but left the paywall live inside it and the main-stage latch set, so a Plans trip and back reopened the paywall with no new submit. Editing now dismisses the paywall too, and switchView only restores the stage while a panel inside it is still live (progress, results, paywall or ready state) via generationStageHasLivePanel(). Two new stu382 specs cover both: a held identity response correcting the count mid-paywall hands the composer back with the draft, and a Plans round-trip after Edit prompt keeps Home on the composer. Both fail on the pre-change app.js. Co-Authored-By: Stuart Gardoll --- app.js | 50 +++++++++++++++++----- e2e/stu382-plans-paywall.spec.js | 72 ++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 11 deletions(-) diff --git a/app.js b/app.js index 9a557b0..0143536 100644 --- a/app.js +++ b/app.js @@ -6887,18 +6887,24 @@ function renderAccountOverview() { function updateUsageDisplay() { renderUsageSurfaces() - if (authState.isVerified && (isSubscriptionLoading() || !isSubscriptionResolved())) { - hidePaywallExhausted() - return - } - // The paywall answers a generation attempt — canRunPipeline shows it when // a prompt is submitted at the limit — so a usage update never surfaces it // on its own: an out-of-runs user still lands on the composer and writes // their prompt first. An update only clears it once the limit no longer - // applies (an upgrade, a sign-in, a new month). - const { count } = getUsage() - if (count < getRunLimit()) hidePaywallExhausted() + // applies (an upgrade, a sign-in, a new month) or while the subscription + // cannot confirm it. + const subscriptionUncertain = authState.isVerified && (isSubscriptionLoading() || !isSubscriptionResolved()) + if (subscriptionUncertain || getUsage().count < getRunLimit()) { + const paywallWasVisible = !document.getElementById('paywall-exhausted')?.classList.contains('hidden') + hidePaywallExhausted() + // A correction that lands while the paywall is up (a stale stored count + // replaced by a smaller authoritative one) frees runs: with nothing else + // live in the stage, hand the composer back with its draft intact rather + // than leave an empty panel. + if (paywallWasVisible && !generationStageHasLivePanel()) { + setGenerationStageVisible(false) + } + } } function updateGuestUsageCounter() { @@ -8988,6 +8994,9 @@ function editPipelinePrompt() { hidePipelineFailure(); const progress = document.getElementById("pipeline-progress"); if (progress) progress.classList.remove("visible"); + // Editing abandons the gated submit as well: the paywall it opened must not + // be left live inside the stage for the next return Home to reopen. + hidePaywallExhausted(); setGenerationStageVisible(false); const input = document.getElementById("pipeline-input"); if (input) { @@ -9921,6 +9930,22 @@ function initExactShell() { mobile.addEventListener("change", order); } +// The stage only deserves the home surface while a panel inside it is still +// live — running progress or a failure, results, the paywall, or the ready +// state. Everything the stage can hold hides once Edit prompt returns to the +// composer, and the stage's bare latch must not reopen an empty panel. +function generationStageHasLivePanel() { + const progress = document.getElementById("pipeline-progress"); + if (progress?.classList.contains("visible")) return true; + const results = document.getElementById("results-view"); + if (results?.classList.contains("visible")) return true; + const paywall = document.getElementById("paywall-exhausted"); + if (paywall && !paywall.classList.contains("hidden")) return true; + const ready = document.getElementById("ready-state"); + if (ready && !ready.classList.contains("hidden")) return true; + return false; +} + function setGenerationStageVisible(visible) { const stage = document.getElementById("generation-stage"); if (!stage) return; @@ -10028,9 +10053,12 @@ function switchView(view, pushState = true, moveFocus = true) { } }); - // Generation overlay only belongs to the home surface. - if (view !== "home") setGenerationStageVisible(false); - else { + // Generation overlay only belongs to the home surface — and only while a + // panel inside it is still live. Its latch marks that it took over once; + // after Edit prompt returned to the composer there is nothing to reopen. + if (view !== "home" || !generationStageHasLivePanel()) { + setGenerationStageVisible(false); + } else { const stage = document.getElementById("main-stage-container"); if (stage && stage.classList.contains("visible")) setGenerationStageVisible(true); } diff --git a/e2e/stu382-plans-paywall.spec.js b/e2e/stu382-plans-paywall.spec.js index a3e2ab0..f57c238 100644 --- a/e2e/stu382-plans-paywall.spec.js +++ b/e2e/stu382-plans-paywall.spec.js @@ -117,6 +117,78 @@ test.describe("STU-382 plans surface and paywall states", () => { expect(pipelineRequests).toEqual([]); }); + test("a usage correction landing on the paywall hands the composer back with the draft", async ({ page }) => { + // A stale stored count greets the submit before the authoritative + // identity response lands with the real, lower count. + await page.addInitScript(() => { + localStorage.setItem( + "ccc_usage", + JSON.stringify({ count: 2, month: new Date().toISOString().slice(0, 7) }), + ); + }); + let releaseIdentity; + const identityGate = new Promise((resolve) => { releaseIdentity = resolve; }); + await applyDefaultRoutes(page, { + [ENDPOINTS.getSubscription]: freeSubscription(), + }); + // Registered after applyDefaultRoutes so it wins the match: the identity + // response is held until the paywall is up, then reports one used run. + await page.route(ENDPOINTS.identity, async (route) => { + await identityGate; + await route.fulfill(identityWithUsage({ count: 1, status: "guest" })); + }); + await page.goto("/"); + + // The stale count is enough to gate the submit while identity is pending. + const prompt = "A countdown timer with lap history"; + const field = page.locator("#pipeline-input"); + await field.fill(prompt); + await page.locator("#hero-send").click(); + await expect(page.locator("#paywall-exhausted")).toBeVisible(); + + // The authoritative count lands below the limit: the paywall leaves and + // the composer comes back holding the draft — not an empty stage. + releaseIdentity(); + await expect(page.locator("#paywall-exhausted")).toBeHidden(); + await expect(page.locator("#generation-stage")).toBeHidden(); + await expect(field).toBeVisible(); + await expect(field).toHaveValue(prompt); + }); + + test("Edit prompt keeps Home on the composer after a Plans trip", async ({ page }) => { + await applyDefaultRoutes(page, { + [ENDPOINTS.identity]: identityWithUsage({ count: PLAN_LIMITS.free, status: "guest" }), + [ENDPOINTS.getSubscription]: freeSubscription(), + }); + await page.goto("/"); + await page.waitForFunction( + (limit) => JSON.parse(localStorage.getItem("ccc_usage") || "{}").count >= limit, + PLAN_LIMITS.free, + { timeout: 8000 }, + ); + + const prompt = "A kanban board with drag handles"; + const field = page.locator("#pipeline-input"); + await field.fill(prompt); + await page.locator("#hero-send").click(); + await expect(page.locator("#paywall-exhausted")).toBeVisible(); + await page.keyboard.press("Escape"); + + await page.locator("#pipeline-edit-prompt").click(); + await expect(field).toHaveValue(prompt); + + // Visiting Plans and returning Home must not reopen the answered paywall: + // the stage only comes back while a panel inside it is still live. + await page.locator("#topbar-plan").click(); + await expect(page.locator("#plans-view")).toBeVisible(); + await page.locator("a.brand").click(); + await expect(page.locator("#plans-view")).toBeHidden(); + await expect(page.locator("#generation-stage")).toBeHidden(); + await expect(page.locator("#paywall-exhausted")).toBeHidden(); + await expect(field).toBeVisible(); + await expect(field).toHaveValue(prompt); + }); + test("C1: professional labels and current-plan indicators agree across surfaces", async ({ page }) => { await seedSession(page); await applyDefaultRoutes(page, { From 74d1a6257e5d67e988e336e8c2b6f2a42332a48d Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:03:03 +0000 Subject: [PATCH 04/10] build: rebuild dist Co-Authored-By: Stuart Gardoll --- .../{index-DGpKq1Hs.js => index-jgsziodK.js} | 136 +++++++++--------- dist/index.html | 2 +- 2 files changed, 69 insertions(+), 69 deletions(-) rename dist/assets/{index-DGpKq1Hs.js => index-jgsziodK.js} (62%) diff --git a/dist/assets/index-DGpKq1Hs.js b/dist/assets/index-jgsziodK.js similarity index 62% rename from dist/assets/index-DGpKq1Hs.js rename to dist/assets/index-jgsziodK.js index 781868c..d2b1d7c 100644 --- a/dist/assets/index-DGpKq1Hs.js +++ b/dist/assets/index-jgsziodK.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 E=typeof window<"u"?window:void 0,Be=typeof globalThis<"u"?globalThis:E,qe=Be?.navigator,F=Be?.document,we=Be?.location,Rl=Be?.fetch,ya=Be!=null&&Be.XMLHttpRequest&&"withCredentials"in new Be.XMLHttpRequest?Be.XMLHttpRequest:void 0,Gc=Be?.AbortController,Ag=Be?.CompressionStream,Je=qe?.userAgent;function Zd(){return!(!E||E.navigator.onLine===!1)}var Ri=typeof globalThis<"u"?globalThis:E;Ri&&typeof self>"u"&&(Ri.self=Ri),Ri&&typeof File>"u"&&(Ri.File=function(){});var N=E??{},oe={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Kc(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 ce(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){Kc(s,i,r,o,a,"next",l)}function a(l){Kc(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 Xd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var Yc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Jc(t){return typeof t=="string"||t}function Zc(t){return typeof t=="string"?t:void 0}var Ti,Fg=["$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"],Kt=(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})({}),Xc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Rg=["$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"],Tg=["token"],Qd="NativeGzipValidationError",_a=t=>t.length>=2&&t[0]===31&&t[1]===139,Qc=(t,e)=>t===Xc.GZipJS||e===Xc.GZipJS||e==="gzip",eu=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Nr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Qd,e},Mg=(function(){var t=ce((function*(e,n){18>e.size&&Nr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());_a(i)&&i[2]===8||Nr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Ti)return Ti;Ti=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;Ti[c]=d>>>0}return Ti})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Nr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Nr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function wa(){return wa=ce((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=ce((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 Mg(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),wa.apply(this,arguments)}var $g=["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"],tu=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return $g.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Js=function(t){return t.trim()},ba=function(t){return t.replace(/^\$/,"")};function ef(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 tf=Object.prototype,nf=tf.hasOwnProperty,Zs=tf.toString,U=Array.isArray||function(t){return Zs.call(t)==="[object Array]"},Ue=t=>typeof t=="function",me=t=>t===Object(t)&&!U(t),rn=t=>{if(me(t)){for(var e in t)if(nf.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,ee=t=>Zs.call(t)=="[object String]",Ea=t=>ee(t)&&t.trim().length===0,Qe=t=>t===null,q=t=>C(t)||Qe(t),Ae=t=>Zs.call(t)=="[object Number]"&&t==t,Vt=t=>Ae(t)&&t>0,wt=t=>Zs.call(t)==="[object Boolean]",Lg=t=>t instanceof FormData,Ng=t=>j(Rg,t),Og=t=>j(Tg,t);function rf(t){return t===null||typeof t!="object"}function us(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Tl(t){return typeof Event<"u"&&sf(t,Event)}function sf(t,e){try{return t instanceof e}catch{return!1}}var Bg=[!0,"true",1,"1","yes"],Bo=t=>j(Bg,t),Dg=[!1,"false",0,"0","no"];function Rt(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Ae(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),Rt(r||n,e,n,i))}class jg{constructor(e){this.tt={},this.et=e.et,this.it=Rt(e.bucketSize,0,100,e.rt),this.nt=Rt(e.refillRate,0,this.it,e.rt),this.st=Rt(e.refillInterval,0,864e5,e.rt)}ot(e,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 lt="Mobile",ds="iOS",sn="Android",gi="Tablet",of=sn+" "+gi,af="iPad",lf="Apple",cf=lf+" Watch",Qi="Safari",mi="BlackBerry",uf="Samsung",df=uf+"Browser",ff=uf+" Internet",Hn="Chrome",Ug=Hn+" OS",hf=Hn+" "+ds,Ml="Internet Explorer",pf=Ml+" "+lt,$l="Opera",Hg=$l+" Mini",Ll="Edge",gf="Microsoft "+Ll,ui="Firefox",mf=ui+" "+ds,lr="Nintendo",cr="PlayStation",di="Xbox",vf=sn+" "+lt,yf=lt+" "+Qi,Wi="Windows",Sa=Wi+" Phone",nu="Nokia",xa="Ouya",_f="Generic",Wg=_f+" "+lt.toLowerCase(),wf=_f+" "+gi.toLowerCase(),Ia="Konqueror",bf="Oculus Browser",fs="Vivaldi",Ef="Yandex",hs="Whale",ka="DuckDuckGo",Sf="Pale Moon",ps="Waterfox",er="Brave",xf="Google Search App",xe="(\\d+(\\.\\d+)?)",Do=new RegExp("Version/"+xe),qg=new RegExp(di,"i"),zg=new RegExp(cr+" \\w+","i"),Vg=new RegExp(lr+" \\w+","i"),Nl=new RegExp(mi+"|PlayBook|BB10","i"),Gg={"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"},If=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?er:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?xf:j(t," OPR/")&&j(t,"Mini")?Hg:j(t," OPR/")?$l:Nl.test(t)?mi:j(t,"IE"+lt)||j(t,"WPDesktop")?pf:j(t,"OculusBrowser")?bf:j(t,df)?ff:j(t,Ll)||j(t,"Edg/")?gf:j(t,fs+"/")?fs:j(t,"YaBrowser/")?Ef:j(t,hs+"/")?hs:j(t,ka+"/")||j(t,"Ddg/")?ka:j(t,"FBIOS")?"Facebook "+lt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?hf:j(t,"CrMo")||j(t,Hn)?Hn:j(t,sn)&&j(t,Qi)?vf:j(t,"FxiOS")?mf:j(t.toLowerCase(),Ia.toLowerCase())?Ia:j(t,er+"/")?er:((s,o)=>o&&j(o,lf)||(function(a){return j(a,Qi)&&!j(a,Hn)&&!j(a,sn)})(s))(t,e)?j(t,lt)?yf:Qi:j(t,"PaleMoon/")?Sf:j(t,ps+"/")?ps:j(t,ui)?ui:j(t,"MSIE")||j(t,"Trident/")?Ml:j(t,"Gecko")?ui:"")},Kg={[pf]:[new RegExp("rv:"+xe)],[gf]:[new RegExp(Ll+"?\\/"+xe)],[Hn]:[new RegExp("("+Hn+"|CrMo)\\/"+xe)],[hf]:[new RegExp("CriOS\\/"+xe)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+xe)],[Qi]:[Do],[yf]:[Do],[$l]:[new RegExp("(Opera|OPR)\\/"+xe)],[ui]:[new RegExp(ui+"\\/"+xe)],[mf]:[new RegExp("FxiOS\\/"+xe)],[Ia]:[new RegExp("Konqueror[:/]?"+xe,"i")],[mi]:[new RegExp(mi+" "+xe),Do],[vf]:[new RegExp("android\\s"+xe,"i")],[ff]:[new RegExp(df+"\\/"+xe)],[bf]:[new RegExp("OculusBrowser\\/"+xe)],[fs]:[new RegExp(fs+"\\/"+xe)],[Ef]:[new RegExp("YaBrowser\\/"+xe)],[hs]:[new RegExp(hs+"\\/"+xe)],[er]:[new RegExp(er+"\\/"+xe)],[ka]:[new RegExp("(DuckDuckGo|Ddg)\\/"+xe)],[Sf]:[new RegExp("PaleMoon\\/"+xe)],[ps]:[new RegExp(ps+"\\/"+xe)],[xf]:[new RegExp("GSA\\/"+xe)],[Ml]:[new RegExp("(rv:|MSIE )"+xe)],Mozilla:[new RegExp("rv:"+xe)]},Yg=function(t,e,n,i){var r=If(t,e,n,i),s=Kg[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},iu=[[new RegExp(di+"; "+di+" (.*?)[);]","i"),t=>[di,t&&t[1]||""]],[new RegExp(lr,"i"),[lr,""]],[new RegExp(cr,"i"),[cr,""]],[Nl,[mi,""]],[new RegExp(Wi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Sa,""];if(new RegExp(lt).test(e)&&!/IEMobile\b/.test(e))return[Wi+" "+lt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Gg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Wi,i]}return[Wi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[ds,[t[3],t[4],t[5]||"0"].join(".")]:[ds,""]],[/(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("("+sn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+sn+")","i"),t=>t&&t[2]?[sn,[t[2],t[3],t[4]||"0"].join(".")]:[sn,""]],[/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/,[Ug,""]],[/Linux|debian/i,["Linux",""]]],ru=function(t){return Vg.test(t)?lr:zg.test(t)?cr:qg.test(t)?di:new RegExp(xa,"i").test(t)?xa:new RegExp("("+Sa+"|WPDesktop)","i").test(t)?Sa:/iPad/.test(t)?af:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?cf:Nl.test(t)?mi:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(nu,"i").test(t)?nu:/(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(lt).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)?sn:of:new RegExp("(pda|"+lt+")","i").test(t)?Wg:new RegExp(gi,"i").test(t)&&!new RegExp(gi+" pc","i").test(t)?wf:""},Jg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function su(t,e){return typeof(n=t)=="string"&&Jg.test(n)?t:e();var n}function wn(t){return t&&t.split("#")[0]}function Ol(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function ou(t,e,n){return kf.apply(this,arguments)}function kf(){return(kf=ce((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 Zg=t=>t instanceof Error,Cf={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}},Xg=Cf.info;function Pf(t){if(wt(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=>Pf(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function gs(t){var e=[];for(var n in t){var i=t[n];Qe(i)||C(i)||e.push({key:n,value:Pf(i)})}return e}function Qg(t,e){var n=Cf[t.level||"info"]||Xg,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),q(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),q(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:gs(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 Af(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 Ff(t,e,n,i){return{resourceLogs:[{resource:{attributes:gs(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let em=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:Qg(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 ce((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return ce((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Kt.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=Ff(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(Kt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return ce((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Kt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Kt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Af(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Kt.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(Kt.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(Kt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return ce((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield ou(n,t):yield n}))()}flushWithTimeout(t){var e=this;return ce((function*(){var n=e.flush();yield ou(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 jo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function au(t){return String(t)+"000000"}function lu(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 tm=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=ce((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=lu(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(jo.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,jo)]+=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 ce((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:gs(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=au(Date.now()),n=new Map;for(var i of t.values()){var r,s=lu(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=gs((r=i.attributes)!==null&&r!==void 0?r:{}),l=au(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:jo})}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 Or,cu,Uo;function nm(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Uo&&n.length===cu||(cu=n.length,Uo=n.reduce(((i,r)=>{Or||(Or={});var s=Or[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,Or[r]=[u,c];break}}return i}),{})),Uo}}class im{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 ce((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 ce((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:nm(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 vi="?";function Ca(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?vi:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Rf=(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]:vi,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},rm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,sm=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,om=/\((\S*)(?::(\d+))(?::(\d+))\)/,am=(t,e)=>{var n=rm.exec(t);if(n)return Ca(e,n[1],vi,+n[2],+n[3]);var i=sm.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=om.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Rf(i[1]||vi,i[2]);return Ca(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},lm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,cm=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,um=(t,e)=>{var n=lm.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=cm.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]||vi,o=Rf(s,r);return Ca(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},uu=/\(error: (.*)\)/;class dm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=ee(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 us(e,"DOMException")}isDOMError(e){return us(e,"DOMError")}}class fm{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 sf(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 hm{constructor(){}match(e){return!!us(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 ee(e.message)&&e.message.length>0}pe(e){var n=e;if(ee(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 pm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class gm{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(pm);return r&&(n=r[1],i=r[2]),[n,i]}}var mm=["fatal","error","warning","log","info","debug"];function Tf(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 vm{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: "+Tf(e)}isSeverityLevel(e){return ee(e)&&!Ea(e)&&mm.indexOf(e)>=0}getStack(e){try{return ee(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ee(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(Zg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class ym{match(e){return Tl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Tf(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class _m{match(e){return rf(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 wm{match(e){return us(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 rf(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 ms="$message",vs="$timestamp",bm=new Set([ms,vs]),Ho={enabled:!0,max_bytes:32768};function ys(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Ho.enabled,max_bytes:Sm(t.max_bytes,Ho.max_bytes)}:k({},Ho)}class Em{constructor(e){this.Ke=[],this.Je=0,this.Ne=ys(e)}setConfig(e){this.Ne=ys(e),this.Xe()}add(e){var n=(function(r){var s;try{s=ef(r)}catch{return}try{var o=JSON.parse(s);if(!me(o))return;var a=o,l=a[ms],u=a[vs];return!ee(l)||l.trim().length===0||!ee(u)&&!Ae(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 Sm(t,e){if(!Ae(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Mf=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(E&&(oe.DEBUG||E.POSTHOG_DEBUG||n)&&!C(E.console)&&E.console){for(var s=("__rrweb_original__"in E.console[r])?E.console[r].__rrweb_original__:E.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)=>Mf(t+" "+r,s)};return i},A=Mf("[PostHog.js]"),ve=A.createLogger,xm=ve("[ExternalScriptsLoader]"),Wo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return xm.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)};N.__PosthogExtensions__=N.__PosthogExtensions__||{},N.__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)}},N.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);Wo(t,i,n)};oe.DEBUG=!1,oe.LIB_VERSION="1.415.7",oe.LIB_NAME="web";var $f="$people_distinct_id",ur="$device_id",qo="$device_model",qi="__alias",zi="__timers",Pa="$autocapture_disabled_server_side",Aa="$heatmaps_enabled_server_side",Fa="$exception_capture_enabled_server_side",Ra="$error_tracking_suppression_rules",Ta="$error_tracking_capture_extension_exceptions",Ma="$web_vitals_enabled_server_side",Bl="$dead_clicks_enabled_server_side",Dl="$product_tours_enabled_server_side",$a="$web_vitals_allowed_metrics",jn="$session_recording_remote_config",Lf="$replay_sample_rate",Nf="$replay_override_sampling",Of="$replay_override_linked_flag",Bf="$replay_override_url_trigger",Df="$replay_override_event_trigger",ai="$sesid",jl="$session_is_sampled",$n="$enabled_feature_flags",Vi="$active_feature_flags",Jr="$early_access_features",La="$feature_flag_details",Gi="$feature_flag_payloads",Zr="$feature_flag_request_id",_s="$minimal_flag_called_events",Pt="$override_feature_flags",Ln="$override_feature_flag_payloads",Gt="$stored_person_properties",Nn="$stored_group_properties",Na="$surveys",ws="$surveys_loaded_at",Oa="$surveys_activated",Xr="$surveys_activated_session",Qr="$surveys_activated_timestamps",Ki="ph_product_tours",Bn="$flag_call_reported",Yi="$flag_call_reported_session_id",es="$feature_flag_errors",tr="$feature_flag_evaluated_at",ft="$user_state",Ba="$client_session_props",Da="$capture_rate_limit",ja="$initial_campaign_params",Ua="$initial_referrer_info",bs="$initial_person_info",Es="$epp",Br="$posthog_cookieless",jf="$cookieless_mode",Uf="$sdk_debug_extensions_init_method",Hf="$sdk_debug_extensions_init_time_ms",Wf="$sdk_debug_recording_script_not_loaded",Ul="PostHog loadExternalDependency extension not found.",On="on_reject",Xt="always",ei="anonymous",Pn="identified",Ha="identified_only",Ss="visibilitychange",xs="beforeunload",si="$pageview",zo="$pageleave",Vo="$identify",du="$groupidentify";function Dr(t,e){U(t)&&t.forEach(e)}function ae(t,e){if(!q(t))if(U(t))t.forEach(e);else if(Lg(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)nf.call(t,n)&&e(t[n],n)}var ge=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 ts(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 fu=function(t){try{return t()}catch{return}},Im=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 ae(t,(function(n,i){(ee(n)&&n.length>0||Ae(n))&&(e[i]=n)})),e},km=["herokuapp.com","vercel.app","netlify.app"];function Cm(t){var e=t?.hostname;if(!ee(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of km)if(n===i)return!1;return!0}function be(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 Wa(t){return t.name==="ph_toolbar_internal"}var qf=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 Ae(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 Pm{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 Am}}var hu,zf=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};E&&!C(E.crypto)&&crypto.getRandomValues&&(zf=t=>crypto.getRandomValues(t));class Am{nextUint32(){return this.R.length>this.O||(zf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Yt=()=>Fm().toString(),Fm=()=>(hu||(hu=new Pm)).generate(),Mi="",Rm=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:qf,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(h,g){if(g===void 0&&(g=F),Mi)return Mi;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),b="dmn_chk_"+Yt();!Mi&&v--;){var w=m.slice(v).join("."),_=b+"=1;domain=."+w+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(b)&&(g.cookie=_+";max-age=0",Mi=w)}return Mi})(c);if(!f){var p=(h=>{var g=h.match(Rm);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}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}}},Go=null,de={N(){if(!Qe(Go))return Go;var t=!0;if(C(E))t=!1;else try{var e="__mplssupport__";de.F(e,"xyz"),de.P(e)!=='"xyz"'&&(t=!1),de.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Go=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return E?.localStorage.getItem(t)}catch(e){de.j(e)}return null},H(t){try{return JSON.parse(de.P(t))||{}}catch{}return null},F(t,e){try{return E?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){de.j(n)}return!1},q(t){try{E?.localStorage.removeItem(t)}catch(e){de.j(e)}}},Tm=[ur,"distinct_id",ai,jl,Es,bs,ft],jr={},Mm={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>jr[t]||null,H:t=>jr[t]||null,F:(t,e)=>(jr[t]=e,!0),q(t){delete jr[t]}},An=null,Ie={N(){if(!Qe(An))return An;if(An=!0,C(E))An=!1;else try{var t="__support__";Ie.F(t,"xyz"),Ie.P(t)!=='"xyz"'&&(An=!1),Ie.q(t)}catch{An=!1}return An},j(t){A.error("sessionStorage error: ",t)},P(t){try{return E?.sessionStorage.getItem(t)}catch(e){Ie.j(e)}return null},H(t){try{return JSON.parse(Ie.P(t))||null}catch{}return null},F(t,e){try{return E?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){Ie.j(n)}return!1},q(t){try{E?.sessionStorage.removeItem(t)}catch(e){Ie.j(e)}}};class $m{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===Xt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===On}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 Bo(e)?1:j(Dg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?de:Qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Qt:de;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Bo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[qe?.doNotTrack,qe?.msDoNotTrack,N.doNotTrack].some((e=>Bo(e)))}}function Vf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Ue(i))return e;try{var r=i(e);return ee(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var Gf="__POSTHOG_TOOLBAR__",Lm=1,Nm=3,Om=11;function pu(t){return t instanceof Element&&(t.id===Gf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function bn(t){return!!t&&t.nodeType===Lm}function rt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Kf(t){return!!t&&t.nodeType===Nm}function Yf(t){return!!t&&t.nodeType===Om&&bn(t.host)}var Jf=1e3;function Wl(t){return t?Js(t).split(/\s+/):[]}function gu(t,e){var n=(function(i){var r,s=E==null||(r=E.location)==null?void 0:r.href;return C(s)?void 0:Vf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ks(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 Wl(e)}function Zf(t){return q(t)?null:Js(t).split(/(\s+)/).filter((e=>nr(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function dr(t){var e="";return za(t)&&!th(t)&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;Kf(n)&&n.textContent&&(e+=(i=Zf(n.textContent))!==null&&i!==void 0?i:"")})),Js(e)}function Ko(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ql=["a","button","form","input","select","textarea","label"];function qa(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 Xf(t){var e=t.parentNode;return!(!e||!bn(e))&&e}var Bm=[".ph-no-autocapture","[data-ph-no-autocapture]"],Qf=["next","previous","prev",">","<"],Dm=[...Qf,"+","-","−","–"],mu=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,vu=[".ph-no-rageclick",".ph-no-capture"],jm=["","text","search","email","password","url","tel","number"];function yu(t,e){if(!E||zl(t))return!1;var n,i,r,s,o;if(wt(e)?(n=!!e&&vu,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:vu,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!bn(l))&&(!!rt(l,"textarea")||(rt(l,"input")?j(jm,(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=eh(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=Qf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,p=d.ariaLabel;return c.some((h=>mu(f,h)||mu(p,h)))}))})(i,a.map((l=>{var u;return{safeText:dr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!qa(a,n)}var zl=t=>!t||rt(t,"html")||!bn(t),eh=(t,e)=>{if(!E||zl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!rt(r,"body");)if(Yf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=Xf(r);if(!s)break;if(e||ql.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=E.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function za(t){for(var e=new Set,n=0,i=t;i.parentNode&&!rt(i,"body");i=i.parentNode){if(n++>=Jf||e.has(i))return!1;e.add(i);var r=ks(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(ks(t),"ph-include"))return!0;var s=t.type||"";if(ee(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!ee(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 th(t){return!!(rt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||rt(t,"select")||rt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var _u=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}))$"),wu=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Um=[16,15,14,13],Hm=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),bu=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Eu=/[0-9A-Za-z_]/;function Wm(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 nr(t,e){if(e===void 0&&(e=!0),q(t))return!1;if(ee(t)){t=Js(t);var n=e?_u.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(wu.lastIndex=0;s=wu.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Um){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(_u.test(d)&&Wm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Hm.test(t):(function(r){var s;for(bu.lastIndex=0;s=bu.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Eu.test(o)&&Eu.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Su(t){var e=dr(t);return nr(e=(e+" "+nh(t)).trim())?e:""}function nh(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=dr(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+nh(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function xu(t){return t.replace(/"|\\"/g,'\\"')}function qm(t){var e=t.attr__class;if(e)return U(e)?e:Wl(e)}var Ur=ve("[Dead Clicks]"),zm=()=>!0,Vm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(Bl)),i=t.instance.config.capture_dead_clicks;return wt(i)?i:!!me(i)||n};class Iu{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({[Bl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=N.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Ur.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=N.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=me(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=N.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),Ur.info("starting...")}}else Ur.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Ur.info("stopping..."))}}var Yo=ve("[SegmentIntegration]"),ih="posthog-js";function rh(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,p,h,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,b=((d=c.exception)==null?void 0:d.values)||[],w=b.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=b[0])==null?void 0:f.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=b[0])==null?void 0:h.value)||c.message,$sentry_exception_type:(g=b[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 Gm{constructor(e,n,i,r,s,o){this.name=ih,this.setupOnce=function(a){a(rh(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class ku{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=E?.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?Rt(a/o,0,1,A):1,p=o>1?Rt(l/o,0,1,A):1,h=u>1?Rt(c/u,0,1,A):1,g=u>1?Rt(d/u,0,1,A):1;r=ge(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Jo=["flags","surveys"],Km={[$f]:{exposure:"hidden"},[qi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[zi]:{exposure:"hidden"},[Pa]:{exposure:"event"},[Aa]:{exposure:"hidden"},[Fa]:{exposure:"event"},[Ra]:{exposure:"hidden"},[Ta]:{exposure:"event"},[Ma]:{exposure:"event"},[Bl]:{exposure:"event"},[Dl]:{exposure:"hidden"},[$a]:{exposure:"event"},[jn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ai]:{exposure:"hidden"},[jl]:{exposure:"event"},[Lf]:{exposure:"event",shouldSkipFromEventProperties:t=>Qe(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"},[$n]:{exposure:"hidden",storageGroup:"flags"},[Vi]:{exposure:"hidden",storageGroup:"flags"},[Jr]:{exposure:"hidden"},[La]:{exposure:"hidden",storageGroup:"flags"},[Gi]:{exposure:"hidden",storageGroup:"flags"},[Zr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[_s]:{exposure:"hidden",storageGroup:"flags"},[Pt]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Gt]:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[Na]:{exposure:"hidden",storageGroup:"surveys"},[ws]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Oa]:{exposure:"event"},[Xr]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[Ki]:{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"},[Bn]:{exposure:"hidden"},[Yi]:{exposure:"hidden"},[es]:{exposure:"hidden"},[tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[Ba]:{exposure:"hidden"},[Da]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[Ua]:{exposure:"hidden"},[bs]:{exposure:"hidden"},[Es]:{exposure:"hidden"},[Nf]:{exposure:"event"},[Of]:{exposure:"event"},[Bf]:{exposure:"event"},[Df]:{exposure:"event"},[Uf]:{exposure:"event"},[Hf]:{exposure:"event"},[Wf]:{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"}},Ym=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Fn=t=>{var e=Km[t];if(e)return e;for(var n of Ym){var i=n[1];if(t.indexOf(n[0])===0)return i}},li=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return ef(t)}},Cs=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},yi=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," ")},fr=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},Ps=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},sh=(t,e)=>t>=e&&Zd(),oh=(t,e,n,i)=>{if(t===0){if(Zd()){var r=e+1;return r===n&&i(),r}return e}return 0},Hr="https?://(.*)",_i=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Jm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",..._i],hr="",Zm=["li_fat_id"];function ah(t,e,n){if(!F)return{};var i,r=e?[..._i,...n||[]]:[],s=lh(fr(F.URL,r,hr),t),o=(i={},ae(Zm,(function(a){var l=qf(a);i[a]=l||null})),i);return ge(o,s)}function lh(t,e){var n=Jm.concat(e||[]),i={};return ae(n,(function(r){var s=yi(t,r);i[r]=s||null})),i}function ch(t){var e=(function(s){return s?s.search(Hr+"google.([^/?]*)")===0?"google":s.search(Hr+"bing.com")===0?"bing":s.search(Hr+"yahoo.com")===0?"yahoo":s.search(Hr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Qe(e)){i.$search_engine=e;var r=F?yi(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Cu(){return navigator.language||navigator.userLanguage}var As="$direct";function uh(){return F?.referrer||As}function dh(t,e,n){n===void 0&&(n=!1);var i=t?[..._i,...e||[]]:[],r=n?wn(we?.href):we?.href,s=r?.substring(0,1e3);return{r:uh().substring(0,1e3),u:s?fr(s,i,hr):void 0}}function fh(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?wn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==As?As:(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=lh(s);ge(o,l)}if(i){var u=ch(i);ge(o,u)}return o}function hh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Xm(){try{return new Date().getTimezoneOffset()}catch{return}}var Qm={flags:tr,surveys:ws},ev=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ti="main";class Zo{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(),E){var r=()=>this.flush();be(E,"beforeunload",r,{capture:!1}),be(E,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Ae(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){ev.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=[...Tm,...o];return k({},de,{H(u){try{var c={};try{c=Qt.H(u)||{}}catch{}var d,f=JSON.parse(de.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];Qe(g)||g===""||(p[h]=g)}d=ge(f,p)}else d=ge(c,f);return de.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=de.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Qt.F(u,m,d,f,p,h)}catch(v){de.j(v)}return g},q(u,c){try{E?.localStorage.removeItem(u),Qt.q(u,c)}catch(d){de.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&de.N()?(n=de,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&Ie.N()?n=Ie:s==="memory"?n=Mm: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 ae(this.props,((n,i)=>{var r=Fn(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=ge({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Jo){var n=de.H(this.Si(e));if(n&&!rn(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ge(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Fn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=Qm[e];if(!i)return!1;var r=n[i],s=this.props[i];return Ae(r)&&Ae(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Fn(e))==null?void 0:n.storageGroup:void 0,r=i?de.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,ti))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,ti),Jo)){var s,o=i[r];(!rn(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(de,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ae(this.props,((i,r)=>{var s,o=(s=Fn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===ti)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ae(e,((r,s)=>{var o;i[s]=(o=Fn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===ti||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!==ti&&(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 Jo)de.q(this.Si(r));i?delete this.ci[ti]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(me(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ae(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(me(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ae(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||me(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=ah(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);rn(Hl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?ch(e):{})}update_referrer_info(){var e;this.register_once({$referrer:uh(),$referring_domain:F!=null&&F.referrer&&((e=Cs(F.referrer))==null?void 0:e.host)||As},void 0)}set_initial_person_info(){this.props[ja]||this.props[Ua]||this.register_once({[bs]:dh(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={};ae([Ua,ja],(r=>{var s=this.props[r];s&&ae(s,(function(o,a){e["$initial_"+ba(a)]=o}))}));var n=this.props[bs];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=fh(r,s),a={};return ae(o,(function(l,u){a["$initial_"+ba(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ge(e,i)}return e}safe_merge(e){return ae(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,p)=>f===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[zi]||{};i[e]=n,this.Pi(zi,i),this.save()}remove_event_timer(e){var n=this.props[zi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(zi,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=Fn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Fn(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&&Ue(n.then)&&n.then(void 0,(()=>{}))}}}}var He={GZipJS:"gzip-js",Base64:"base64"},$i={Activation:"events",Cancellation:"cancelEvents"},Xo={Popover:"popover",API:"api",Widget:"widget"},en={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Qo={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},Va={Popover:"popover",Inline:"inline"},tv={SHOWN:"product tour shown"},Pu={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Au=ve("[RateLimiter]");class nv{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=>{Au.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Au.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=(Ae(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")&&we!=null&&we.pathname)return""+((e=we.origin)!==null&&e!==void 0?e:"")+we.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 mn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void mn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return mn.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){mn.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||mn.warn("Failed to fetch remote config from PostHog."):mn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){mn.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){mn.error("Error loading feature flags",r)}}}var pt=Uint8Array,Xe=Uint16Array,wi=Uint32Array,Vl=new pt([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]),Gl=new pt([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]),Fu=new pt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),gh=function(t,e){for(var n=new Xe(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]},mh=gh(Vl,2),Ga=mh[1];mh[0][28]=258,Ga[258]=28;for(var Ru=gh(Gl,0)[1],vh=new Xe(32768),Ee=0;32768>Ee;++Ee){var ni=(43690&Ee)>>>1|(21845&Ee)<<1;vh[Ee]=((65280&(ni=(61680&(ni=(52428&ni)>>>2|(13107&ni)<<2))>>>4|(3855&ni)<<4))>>>8|(255&ni)<<8)>>>1}var ir=function(t,e,n){for(var i=t.length,r=0,s=new Xe(e);i>r;++r)++s[t[r]-1];var o,a=new Xe(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Xe(i),r=0;i>r;++r)o[r]=vh[a[t[r]-1]++]>>>15-t[r];return o},Vn=new pt(288);for(Ee=0;144>Ee;++Ee)Vn[Ee]=8;for(Ee=144;256>Ee;++Ee)Vn[Ee]=9;for(Ee=256;280>Ee;++Ee)Vn[Ee]=7;for(Ee=280;288>Ee;++Ee)Vn[Ee]=8;var Fs=new pt(32);for(Ee=0;32>Ee;++Ee)Fs[Ee]=5;var iv=ir(Vn,9),rv=ir(Fs,5),yh=function(t){return(t/8>>0)+(7&t&&1)},_h=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Xe?Xe:t instanceof wi?wi:pt)(n-e);return i.set(t.subarray(e,n)),i},qt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Li=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},ea=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 pt(0),0];if(r==1){var o=new pt(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 p=new Xe(f+1),h=Ka(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var b=s[i].s;if(e>=p[b])break;g+=v-(1<>>=m;g>0;){var w=s[i].s;e>p[w]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new pt(p),h]},Ka=function(t,e,n){return t.s==-1?Math.max(Ka(t.l,e,n+1),Ka(t.r,e,n+1)):e[t.s]=n},Tu=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Xe(++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]},Ni=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ya=function(t,e,n){var i=n.length,r=yh(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)},Mu=function(t,e,n,i,r,s,o,a,l,u,c){qt(e,c++,n),++r[256];for(var d=ea(r,15),f=d[0],p=d[1],h=ea(s,15),g=h[0],m=h[1],v=Tu(f),b=v[0],w=v[1],_=Tu(g),x=_[0],I=_[1],T=new Xe(19),S=0;b.length>S;++S)T[31&b[S]]++;for(S=0;x.length>S;++S)T[31&x[S]]++;for(var P=ea(T,7),R=P[0],L=P[1],$=19;$>4&&!R[Fu[$-1]];--$);var O,J,G,M,K=u+5<<3,ie=Ni(r,Vn)+Ni(s,Fs)+o,B=Ni(r,f)+Ni(s,g)+o+14+3*$+Ni(T,R)+(2*T[16]+3*T[17]+7*T[18]);if(ie>=K&&B>=K)return Ya(e,c,t.subarray(l,l+u));if(qt(e,c,1+(ie>B)),c+=2,ie>B){O=ir(f,p),J=f,G=ir(g,m),M=g;var Z=ir(R,L);for(qt(e,c,w-257),qt(e,c+5,I-1),qt(e,c+10,$-4),c+=14,S=0;$>S;++S)qt(e,c+3*S,R[Fu[S]]);c+=3*$;for(var se=[b,x],Ce=0;2>Ce;++Ce){var Q=se[Ce];for(S=0;Q.length>S;++S)qt(e,c,Z[ue=31&Q[S]]),c+=R[ue],ue>15&&(qt(e,c,Q[S]>>>5&127),c+=Q[S]>>>12)}}else O=iv,J=Vn,G=rv,M=Fs;for(S=0;a>S;++S)if(i[S]>255){var ue;Li(e,c,O[257+(ue=i[S]>>>18&31)]),c+=J[ue+257],ue>7&&(qt(e,c,i[S]>>>23&31),c+=Vl[ue]);var ye=31&i[S];Li(e,c,G[ye]),c+=M[ye],ye>3&&(Li(e,c,i[S]>>>5&8191),c+=Gl[ye])}else Li(e,c,O[i[S]]),c+=J[i[S]];return Li(e,c,O[256]),c+J[256]},sv=new wi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ov=(function(){for(var t=new wi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),ta=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function av(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=ov[255&p^f[h]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,p,h,g,m){var v=d.length,b=new pt(h+v+5*(1+Math.floor(v/7e3))+g),w=b.subarray(h,b.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=Ya(w,_,d.subarray(x,I)):(w[x]=!0,_=Ya(w,_,d.subarray(x,v)))}else{for(var T=sv[f-1],S=T>>>13,P=8191&T,R=(1<x;++x){var ue=G(x),ye=32767&x,je=$[ue];if(L[ye]=je,$[ue]=ye,x>=Ce){var St=v-x;if((B>7e3||se>24576)&&St>423){_=Mu(d,w,0,M,K,ie,Z,se,Q,x-Q,_),se=B=Z=0,Q=x;for(var _e=0;286>_e;++_e)K[_e]=0;for(_e=0;30>_e;++_e)ie[_e]=0}var et=2,xt=0,Cn=P,Le=ye-je&32767;if(St>2&&ue==G(x-Le))for(var Re=Math.min(S,St)-1,Dt=Math.min(32767,x),Zn=Math.min(258,St);Dt>=Le&&--Cn&&ye!=je;){if(d[x+et]==d[x+et-Le]){for(var Ke=0;Zn>Ke&&d[x+Ke]==d[x+Ke-Le];++Ke);if(Ke>et){if(et=Ke,xt=Le,Ke>Re)break;var Xn=Math.min(Le,Ke-2),jt=0;for(_e=0;Xn>_e;++_e){var Ut=x-Le+_e+32768&32767,ut=Ut-L[Ut]+32768&32767;ut>jt&&(jt=ut,je=Ut)}}}Le+=(ye=je)-(je=L[ye])+32768&32767}if(xt){M[se++]=268435456|Ga[et]<<18|Ru[xt];var Ht=31&Ga[et],Ai=31&Ru[xt];Z+=Vl[Ht]+Gl[Ai],++K[257+Ht],++ie[Ai],Ce=x+et,++B}else M[se++]=d[x],++K[d[x]]}}_=Mu(d,w,!0,M,K,ie,Z,se,Q,x-Q,_)}return _h(b,0,h+yh(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var p=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&ta(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),ta(u,c-8,n.d()),ta(u,c-4,i),u}var lv=!!ya||!!Rl,wh="text/plain",ns=!1,bh=(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:"")},Xs=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("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return ae(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},na=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===He.GZipJS){var i=av((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new pt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new pt(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return _h(c,0,d)})(li(e)),{mtime:0});return{contentType:wh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===He.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(li(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:li(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=li(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Eh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Xs(t.url,{compression:He.Base64}),encodedBody:na(k({},t,{compression:He.Base64,Ji:void 0}))}:{url:bh(t.url,"compression"),encodedBody:na(k({},t,{compression:void 0,Ji:void 0}))};try{e=na(t)}catch(r){if(Qc(t.compression,yi(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&Qc(t.compression,yi(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?_a(new Uint8Array(n)):ArrayBuffer.isView(n)&&_a(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(ns=!0,i()):{url:t.url,encodedBody:e}},Sh=t=>{try{return Eh(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},cv=(function(){var t=ce((function*(e){var n=li(e.data),i=yield(function(s,o,a){return wa.apply(this,arguments)})(n,oe.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:wh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),uv=/Failed to fetch|NetworkError|Load failed/i,xh=t=>t?.name==="TypeError"&&uv.test(t?.message||""),Ih=t=>{var e=Sh(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ae(t.headers,(function(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Gc){var d=new Gc;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||xh(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;Rl(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(h){u&&clearTimeout(u.timeout),f(h)}}},Ja=t=>{try{var e,n=Eh(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(qe.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 Ja(k({},t,{data:d(u.slice(0,c))})),void Ja(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Ih(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},$u=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Xs(n===He.GZipJS?bh(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===He.GZipJS?{}:{compression:n}))},is=[];Rl&&is.push({transport:"fetch",method:Ih}),ya&&is.push({transport:"XHR",method(t){var e=Sh(t);if(e){var n=new ya,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ae(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)}}}),qe!=null&&qe.sendBeacon&&is.push({transport:"sendBeacon",method:Ja});var Za=3e3;class dv{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Rt(n?.flush_interval_ms||Za,250,5e3,A.createLogger("flush interval"),Za),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)&&ae(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 ae(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 fv=["retriesPerformedSoFar"];class hv{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(E)&&"onLine"in E.navigator&&(this.dr=E.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},be(E,"online",this.vr),be(E,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=Xd(e,fv);Vt(n)&&(i.url=Xs(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(E)||(this.vr&&(E.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(E.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 pv{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(){be(E,"scroll",this.yr,{capture:!0}),be(E,"scrollend",this.yr,{capture:!0}),be(E,"resize",this.yr)}scrollElement(){if(!this._r)return E?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=E?.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 E?e==="y"?E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop||0:E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var gv=t=>dh(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Lu{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({[Ba]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||gv,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Ba]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?fh(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 ae(Hl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+ba(i)]=n})),e}}class Kl{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 Oi=ve("[SessionId]");class Nu{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 Kl,this.Lr=(u,c)=>!(!Vt(u)||!Vt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Xt)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||Yt,this.Nr=i||Yt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Oi.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=Ie.H(this.jr),a=Ie.H(this.Br);o&&!a?this.Or=o:Ie.q(this.jr),Ie.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){Oi.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&&Ie.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&Ie.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?Ie.H(this.jr):null}Zr(e){var n=this.Pr;return!Qe(n)&&!Qe(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({[ai]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Vt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(ai):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Qe(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({[ai]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Vt(e)?e:0,i=Vt(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[ai];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&&E&&(E.removeEventListener(xs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&Ie.q(this.Br)},be(E,xs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Xt)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=Vt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||Oi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),Oi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Oi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Vt(a)&&e&&!u?a:i,v=Vt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var b={noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(s,l,b))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var kh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&tu(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>tu(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Ch(){return(Ch=ce((function*(){var t=qe?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return ee(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 Rs=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 ia(t,e,n){return li({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Ph={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=>Rs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Rs(n,i))))),icontains:(t,e)=>e.map(qr).some((n=>t.map(qr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(qr).every((n=>t.map(qr).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 Ah(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Qe(r))return!1;var s=[String(r)],o=Ph[i.operator];return!!o&&o(i.values,s)}))}var Xa="custom",Ou="i.posthog.com",mv=/^\/static\//;class vv{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":Xa),this.en[this.apiHost]}rn(e){if(mv.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=Ou+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Fh(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var te=ve("[Surveys]"),Rh="seenSurvey_",Th=t=>{try{var e=(n=>((i,r)=>""+Rh+(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){te.error("Failed to persist survey seen state",n)}},yv=[Xo.Popover,Xo.Widget,Xo.API],_v={ignoreConditions:!1,ignoreDelay:!1,displayType:Va.Popover},wv=ve("[PostHog ExternalIntegrations]"),bv={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Ev{constructor(e){this._instance=e}ai(e,n){var i;(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return wv.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=N.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(bv[l],(()=>{var c;(c=N.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=N.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=N.__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 Sv{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return ce((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&&Ue(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 xv{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 Bu="extensionsRemoteConfig";class Iv{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new xv(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(Bu,i);return this.un&&i(this.un),Wr(r)},this.vn=new Sv(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(ur))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(ur);return typeof e=="string"?e:void 0}get library(){return{name:oe.LIB_NAME,version:oe.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 ce((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(Bu,e))}sendRequest(e,n){var i=this;return ce((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?Xs(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 rr={},ra=0,Ts=()=>{},Du='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Bi="Surveys module not available",ju="sanitize_properties is deprecated. Use before_send instead",Mh="Invalid value for property_denylist config: ",kv=["token","distinct_id",jf],oi="posthog",$h=!lv&&Je?.indexOf("MSIE")===-1&&Je?.indexOf("Mozilla")===-1,sa=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:Cm(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Ts,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:we&&ee(we?.search)&&we.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:(E==null||(e=E.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:Ha,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Za},error_tracking:{},_onCapture:Ts},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Dm,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))},Cv=[["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 Cv){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=ge({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),ee(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(Mh+t.property_denylist)),s};class Pv{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 tt{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===Xt||this.config.cookieless_mode===On&&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 Pv,this.mn=!1,this.version=oe.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Kl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=sa(),this.SentryIntegration=Gm,this.sentryIntegration=i=>(function(r,s){var o=rh(r,s);return{name:ih,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 pv(this),this.pageViewManager=new ku(this),this.rateLimiter=new nv(this),this.requestRouter=new vv(this),this.consent=new $m(this),this.externalIntegrations=new Ev(this);var n=(e=tt.__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=ee(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=ee(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!==oi){var r,s=(r=rr[i])!==null&&r!==void 0?r:new tt;return s._init(e,n,i),rr[i]=s,rr[oi][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=ee(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=sa(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=sa(n.defaults),u=Uu(n),c=ge({},l,u,{name:i,token:a});me(l.rageclick)&&me(u.rageclick)&&(c.rageclick=ge({},l.rageclick,u.rageclick)),me(l.session_recording)&&me(u.session_recording)&&(c.session_recording=ge({},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:He.GZipJS;var d=this.En();if(this.persistence=new Zo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Zo(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&&Ie.N()){var f=Ie.H(this.bn);U(f)&&f.forEach((I=>{ee(I)&&this.yn.add(I)}))}else Ie.q(this.bn);var p=k({},this.persistence.props),h=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new dv((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new hv(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Nu(this),this.sessionPropsManager=new Lu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.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)),oe.DEBUG=oe.DEBUG||this.config.debug,oe.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p,s:h}),!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(),b=this.persistence.get_property(ft);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===ei)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Pn)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 w=this.config.get_device_id(Yt()),_=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(ft,n.bootstrap.isIdentifiedID?Pn:ei),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Br,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Yt());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ft,ei)}return be(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var S=I.config.segment;if(!S)return T();(function(P,R){var L=P.config.segment;if(!L)return R();var $=J=>{var G=()=>J.anonymousId()||Yt();P.config.get_device_id=G,J.id()&&(P.register({distinct_id:J.id(),$device_id:G()}),P.persistence.set_property(ft,Pn)),R()},O=L.user();"then"in O&&Ue(O.then)?O.then($):$(O)})(I,(()=>{S.register((P=>{typeof Promise<"u"&&Promise.resolve||Yo.warn("This browser does not have Promise support, and can not use the segment integration");var R=(L,$)=>{if(!$)return L;L.event.userId||L.event.anonymousId===P.get_distinct_id()||(Yo.info("No userId set, resetting PostHog"),P.reset()),L.event.userId&&L.event.userId!==P.get_distinct_id()&&(Yo.info("UserId set, identifying with PostHog"),P.identify(L.event.userId));var O=P.calculateEventProperties($,L.event.properties);return L.event.properties=Object.assign({},O,L.event.properties),L};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:L=>R(L,L.event.event),page:L=>R(L,si),identify:L=>R(L,Vo),screen:L=>R(L,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),Ue(this.config._onCapture)&&this.config._onCapture!==Ts&&(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 Ch.apply(this,arguments)})().then((I=>{I&&this.register({[qo]:I})})).catch(Ts),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=tt.__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)),Ue(this.featureFlags.onReloading)&&Ue(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({},tt.__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,Vm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Uf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Hf]: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,He.GZipJS)?He.GZipJS:j(r.supportedCompression,He.Base64)?He.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:Ha}),(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&&we!=null&&we.hostname){var e=we.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 ph(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()&&Dr(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(zo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(zo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?$h?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=He.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((b=>k({},b,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=$u(o.url,o.method,o.compression,o.timestampMode);var p=is.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var b=0;m.length>b;b++)if(m[b].transport===f)return m[b]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){xh(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===He.GZipJS&&Ag&&typeof Promise<"u"&&!ns?cv(o).then((m=>{g(m)})).catch((m=>{if(eu(m))return ns=!0,void g(k({},o,{compression:void 0,url:$u(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var b="name"in v?String(v.name):"";return eu(v)||b===Qd})(m)&&(ns=!0),g(o)})):h(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){ra++;try{var n,i=[],r=[],s=[];Dr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(Ue(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&&Ue(this[n])?s.push(a):r.push(a)}));var o=function(a,l){Dr(a,(function(u){try{if(U(u[0])){var c=l;ae(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{ra--}}push(e){if(ra>0&&U(e)&&ee(e[0])){var n=tt.prototype[e[0]];Ue(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)&&ee(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&&!ee(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,p=su(i?.uuid,Yt),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===si&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(_s)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,b,w,_=g?void 0:this.Vn(i?.$set_once,e!==du,e===Vo);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=$=>ee($)?$.slice(0,s):$,l=new Set,h=(function $(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var G;if(l.add(O),U(O))G=[],Dr(O,(K=>{G.push($(K))}));else{var M={};ae(O,((K,ie)=>{l.has(K)||(M[ie]=$(K))})),G=M}return G}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function($,O){O===void 0&&(O=[]);var J={},G=M=>{$[M]!==void 0&&(J[M]=$[M])};return Fg.forEach(G),O.forEach(G),J})(h.properties,kv)),e===en.DISMISSED||e===en.SENT){var x=n?.[Qo.SURVEY_ID],I=n?.[Qo.SURVEY_ITERATION];Th({id:x,current_iteration:I}),h.$set=k({},h.$set,{[(v={id:x,current_iteration:I},b=e===en.SENT?"responded":"dismissed",w="$survey_"+b+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+b+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===en.SHOWN&&(h.$set=k({},h.$set,{[Qo.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===tv.SHOWN){var T=n?.[Pu.TOUR_TYPE];T&&(h.$set=k({},h.$set,{[Pu.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var S=k({},h.properties.$set,h.$set);if(rn(S)||this.setPersonPropertiesForFlags(S),!q(this.config.before_send)){var P=this.Pt(h);if(!P)return;(h=P).uuid=su(h.uuid,Yt)}this.dn.emit("eventCaptured",h);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),L={method:"POST",url:R,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"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(L):this.In.enqueue(L),h}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Iv(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[jf]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!ee(a.distinct_id)&&!Ae(a.distinct_id)||Ea(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,T,S){var P,R,L,$;if(S===void 0&&(S=!1),!Je)return{};var O,J=x?[..._i,...I||[]]:[],G=(function(Zn){for(var Ke=0;iu.length>Ke;Ke++){var Xn=iu[Ke],jt=Xn[1],Ut=Xn[0].exec(Zn),ut=Ut&&(Ue(jt)?jt(Ut,Zn):jt);if(ut)return ut}return["",""]})(Je),M=G[0],K=G[1],ie=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},B={};C(T)||(B.detectGoogleSearchApp=T);var Z={},se=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,Ce=(R=navigator)==null?void 0:R.maxTouchPoints,Q=E==null||(L=E.screen)==null?void 0:L.width,ue=E==null||($=E.screen)==null?void 0:$.height,ye=E?.devicePixelRatio;C(se)||(Z.userAgentDataPlatform=se),C(Ce)||(Z.maxTouchPoints=Ce),C(Q)||(Z.screenWidth=Q),C(ue)||(Z.screenHeight=ue),C(ye)||(Z.devicePixelRatio=ye);var je,St,_e,et,xt,Cn,Le,Re,Dt=ge(Hl({$os:M,$os_version:K,$browser:If(Je,navigator.vendor,ie,B),$device:ru(Je),$device_type:(St=Je,_e=Z,Re=ru(St),Re===af||Re===of||Re==="Kobo"||Re==="Kindle Fire"||Re===wf?gi:Re===lr||Re===di||Re===cr||Re===xa?"Console":Re===cf?"Wearable":Re?lt:_e?.userAgentDataPlatform==="Android"&&((et=_e?.maxTouchPoints)!==null&&et!==void 0?et:0)>0?600>Math.min((xt=_e?.screenWidth)!==null&&xt!==void 0?xt:0,(Cn=_e?.screenHeight)!==null&&Cn!==void 0?Cn:0)/((Le=_e?.devicePixelRatio)!==null&&Le!==void 0?Le:1)?lt:gi:"Desktop"),$timezone:hh(),$timezone_offset:Xm()}),{$current_url:fr(S?wn(we?.href):we?.href,J,hr),$host:we?.host,$pathname:we?.pathname,$raw_user_agent:Je.length>1e3?Je.substring(0,997)+"...":Je,$browser_version:Yg(Je,navigator.vendor,ie,B),$browser_language:Cu(),$browser_language_prefix:(je=Cu(),typeof je=="string"?je.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:oe.LIB_NAME,$lib_version:oe.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return oe.SDK_DIST_CHANNEL&&(Dt.$sdk_dist_channel=oe.SDK_DIST_CHANNEL),Dt})(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&&ge(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ge(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===Xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==si||s?e!==zo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=ge(a,u),e===si&&F&&(a.title=F.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}Je&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ae(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var b of this._n.slice())try{ge(v,b())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=ge({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ae(this.config.property_denylist,(function(x){delete a[x]})):A.error(Mh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(A.error(ju),a=w(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=ge({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(ju),a=l(a,"$set_once")),n&&(this.mn=!0),rn(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||!Ie.N())Ie.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?Ie.F(this.bn,n):Ie.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:Bi}),()=>{})}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:Bi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Bi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=_v),(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:Bi}}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:Bi})}Jn(e){return!e||Ea(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Br?(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(Ae(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(ur)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(qi)&&(this.unregister(qi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ft)||ei)===ei,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ft,Pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Vo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=ia(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ft,Pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=ia(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Bn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=ia(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=>ee(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(du,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var p,h=this.get_property(ur),g=this.get_property(qo),m=this.get_property(jn),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(p=this.persistence)==null||p.register({[jn]: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(ft,ei),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Xt)this.register_once({distinct_id:Br,$device_id:null},"");else{var b=this.config.get_device_id(Yt());this.register_once({distinct_id:b,$device_id:e?b:h},""),e||C(g)||this.register({[qo]: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 ce((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($f)?(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(qi,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(me(e)){var i,r,s,o,a,l,u,c,d,f,p,h;ge(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 Zo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);wt(m)&&(this.config.debug=m),wt(this.config.debug)&&(this.config.debug?(oe.DEBUG=!0,de.N()&&de.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(oe.DEBUG=!1,de.N()&&de.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){oe.LIB_NAME=e,oe.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:tt.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:oi;return n!==oi&&(n=oi+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ft))===Pn||((n=this.sessionPersistence)==null?void 0:n.get_property(ft))===Pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===Ha&&!this._isIdentified()&&rn(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[qi])&&((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!==On)}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!==Xt){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 Nu(this),this.pageViewManager=new ku(this),this.persistence&&(this.sessionPropsManager=new Lu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=tt.__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==On&&((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(Du)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Xt?(this.config.cookieless_mode===On&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===On&&(this.register({distinct_id:Br,$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(Du)}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===Xt||(this.config.cookieless_mode===On?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return qe?kh(qe,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(si,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(Ss,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),be(F,Ss,this.kn)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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&&!q(n[i]),l=r in n&&!q(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(q(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Og),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),q(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Ng(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!rn(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&&q(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=wt(e)&&!e,i=de.N()&&de.P("ph_debug")==="true";return!n&&(!!i||e)}}tt.__defaultExtensionClasses={},tt.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]]=Im(t.prototype[e[n]])})(tt,["identify"]);class Hu{constructor(e){this.disabled=e===!1;var n=me(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 oa="$copy_autocapture",aa=ve("[AutoCapture]");function la(t,e){return e.length>t?e.slice(0,t)+"...":e}function Av(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!bn(e));return e}function Fv(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!bn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!rt(f,"body")&&Jf>c.length;)if(Yf(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!bn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},b=!1,w=!1;if(ae(c,(S=>{var P=za(S);if(rt(S,"a")){var R=S.getAttribute("href");b=!!(P&&R&&nr(R))&&(u?wn(R):R)}j(ks(S),"ph-no-capture")&&(w=!0),m.push((function($,O,J,G,M){M===void 0&&(M=!1);var K=$.tagName.toLowerCase(),ie={tag_name:K};ql.indexOf(K)>-1&&!J&&(ie.$el_text=K.toLowerCase()==="a"||K.toLowerCase()==="button"?la(1024,Su($)):la(1024,dr($)));var B=ks($);B.length>0&&(ie.classes=B.filter((function(Q){return Q!==""}))),ae($.attributes,(function(Q){var ue;if((!th($)||["name","id","class","aria-label"].indexOf(Q.name)!==-1)&&(G==null||!G.includes(Q.name))&&!O&&nr(Q.value)&&(!ee(ue=Q.name)||ue.substring(0,10)!=="_ngcontent"&&ue.substring(0,7)!=="_nghost")){var ye=Q.value;Q.name==="class"&&(ye=Wl(ye).join(" ")),ie["attr__"+Q.name]=la(1024,Q.name==="href"&&M?wn(ye):ye)}}));for(var Z=1,se=1,Ce=$;Ce=Av(Ce);)Z++,Ce.tagName===$.tagName&&se++;return ie.nth_child=Z,ie.nth_of_type=se,ie})(S,s,o,a,u));var L=(function($){if(!za($))return{};var O={};return ae($.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var G=J.name.replace("data-ph-capture-attribute-",""),M=J.value;G&&M&&nr(M)&&(O[G]=M)}})),O})(S);ge(v,L)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=rt(t,"a")||rt(t,"button")?Su(t):dr(t)),b){var _,x;m[0].attr__href=b;var I=(_=Cs(b))==null?void 0:_.host,T=E==null||(x=E.location)==null?void 0:x.host;I&&T&&I!==T&&(h=b)}return{props:ge({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((P=>{var R,L,$="";if(P.tag_name&&($+=P.tag_name),P.attr_class)for(var O of(P.attr_class.sort(),P.attr_class))$+="."+O.replace(/"/g,"");var J=k({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(L=P.nth_of_type)!==null&&L!==void 0?L:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),G={};return ts(J).sort(((M,K)=>M[0].localeCompare(K[0]))).forEach((M=>{var K=M[1];return G[xu(M[0].toString())]=xu(K.toString())})),($+=":")+ts(G).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(S){return S.map((P=>{var R,L,$={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(L=P.attr__href)==null?void 0:L.slice(0,2048),attr_class:qm(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return ts(P).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>$.attributes[O[0]]=O[1])),$}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var Di=ve("[ExceptionAutocapture]"),Wu=()=>{},Rv=ve("[TracingHeaders]"),Rn=ve("[Web Vitals]"),qu=9e5,zu="disabled",Vu="lazy_loading",ji="awaiting_config",zr="missing_config";ve("[SessionRecording]"),ve("[SessionRecording]");var Qa="[SessionRecording]",zt=ve(Qa),Tv=ve("[Heatmaps]");function ca(t){return me(t)&&"clientX"in t&&"clientY"in t&&Ae(t.clientX)&&Ae(t.clientY)}var Vr=ve("[Product Tours]"),ua=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Dl))},Mv=["$set_once","$set"],It=ve("[SiteApps]"),Gu="Error while initializing PostHog app with config id ";function ii(t,e,n){if(q(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 $v{constructor(e){this.ns=new Kl,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"||!ii(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=>ii(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&ii((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=>ii(u.text,n.text,n.text_matching||"exact")||ii(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;!q(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=>ii(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||Ah(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 Lv{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&&Ah(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===$i.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 $v(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,$i.Activation),this.ks=this.Ps(e,$i.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,$i.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,$i.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&&(rn(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Ae(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=>Ae(s[o]))).forEach((o=>this.Bs(o)))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter((e=>!this.ea(e)))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class Nv extends Lv{constructor(e){super(e)}Js(){return Oa}Ys(){return Xr}Ms(){return Qr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Qr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Qr)}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 Ae(r)&&r>0}ra(){return en.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 te}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Oa]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Xr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Xr)}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 Fh(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===en.SHOWN?"consume":"ignore":e===en.SHOWN?"persist":e===en.DISMISSED||e===en.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Gr="SDK is not enabled or survey functionality is not yet loaded",Ku="Disabled. Not loading surveys.",Ov=E!=null&&E.location?Ps(E.location.hash,"__posthog")||Ps(location.hash,"state"):null,Yu="_postHogToolbarParams",Ju=ve("[Toolbar]"),Zu=ve("[FeatureFlags]");class Bv{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||(Zu.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)||Zu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Xu=ve("[FeatureFlags]"),Tn=ve("[FeatureFlags]",{debugEnabled:!0}),da=`" failed. Feature flags didn't load in time.`,Qu="connection_error",ed=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},td=t=>{var e={};for(var n of ts(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},kt=ve("[Error tracking]"),nd="Refusing to render web experiment since the viewer is a likely bot",Dv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Rs(e,t),not_regex:(t,e)=>!Rs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Oe{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Oe.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Oe.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);ee(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];Oe.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())Oe.aa(nd);else if(!this.Ne.disable_web_experiments){if(q(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Oe.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=Oe.getWindowLocation();if(e!=null&&e.search){var n=yi(e?.search,"__experiment_id"),i=yi(e?.search,"__experiment_variant");n&&i&&(Oe.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&&(Oe.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!q(e.conditions)&&Oe.da(e,n)&&Oe.va(e)}static da(e,n){var i;if(q(e.conditions)||q((i=e.conditions)==null?void 0:i.url))return!0;var r=Oe.getWindowLocation();if(r){var s,o,a,l=Vf(n,r.href);return(s=e.conditions)==null||!s.url||Dv[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return E?.location}static va(e){var n;if(q(e.conditions)||q((n=e.conditions)==null?void 0:n.utm))return!0;var i=ah();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,h=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&h&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Oe.aa(nd):n!=="control"?i.forEach((r=>{if(r.selector){var s;Oe.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)}))}})):Oe.aa("Control variants leave the page unmodified.")}_is_bot(){return qe&&this._instance?kh(qe,this.Ne.custom_blocked_useragents):void 0}}var dt=ve("[Conversations]"),Mn="Conversations not available yet.",id="console",Lh="__posthogHandledLogsRequestError",fa=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Lh]=!0,n},rd=t=>!!t&&typeof t=="object"&&t[Lh]===!0,Qs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Xu,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 Bv(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 E&&be(E,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){E?.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=[],E?.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[Vi,Gi,Zr,Pt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa($n);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(tr);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($n))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Gi))!==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:Jc(f),variant:Zc(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(Pt),n=this.Oa(Ln);if(!n&&!e)return t||{};var i=ge({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],p=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Jc(i),variant:Zc(i),payload:Yc(e[n])}}))}getFlagVariants(){var t=this.Oa($n),e=this.Oa(Pt);if(!e)return t||{};for(var n=ge({},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(Gi),e=this.Oa(Ln);if(!e)return t||{};for(var n=ge({},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(Bn)}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(Gt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Nn),timezone:hh()};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({[es]:[Qu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?He.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Qu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[es]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(p,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return sh(this.Sa,3)}Ua(t){this.Sa=oh(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+da)}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(Zr)||void 0,u=this.Oa(tr)||void 0,c=this.Oa(Bn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Yi);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Bn]:c,[Yi]:n});else{var h,g,m,v,b,w,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Bn]:c},n?{[Yi]:n}:{}));var S=this.getFeatureFlagDetails(t),P=[...(h=this.Oa(es))!==null&&h!==void 0?h:[]];C(s)&&P.push("flag_missing");var R={$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(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),C(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var L,$=(w=S==null||(_=S.reason)==null?void 0:_.description)!==null&&w!==void 0?w:S==null||(x=S.reason)==null?void 0:x.code;$&&(R.$feature_flag_reason=$),S!=null&&(I=S.metadata)!=null&&I.id&&(R.$feature_flag_id=S.metadata.id),C(S?.original_variant)&&C(S?.original_enabled)||(R.$feature_flag_original_response=C(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(T=S.metadata)!=null&&T.original_payload&&(R.$feature_flag_original_payload=S==null||(L=S.metadata)==null?void 0:L.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[Bn]:c,[Yi]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Yc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+da)}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 ce((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"?He.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+da),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=Xu);var c=((I,T)=>{var S=I.flags;return S?k({},I,{featureFlags:Object.fromEntries(Object.keys(S).map((P=>{var R;return[P,(R=S[P].variant)!==null&&R!==void 0?R:S[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((P=>S[P].enabled)).filter((P=>{var R;return(R=S[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=S[P].metadata)==null?void 0:R.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,p=c.featureFlagPayloads;if(f){var h=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Vi]:f,[$n]:m,[_s]:!1}}var b=f,w=p,_=d;if(l!=null&&l.partialResponse)b=k({},s,b),w=k({},o,w),_=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)})));b=k({},s,Object.fromEntries(Object.entries(b).filter((I=>x.has(I[0]))))),w=k({},o,Object.fromEntries(Object.entries(w||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else b=k({},s,b),w=k({},o,w),_=k({},a,_);return k({[Vi]:Object.keys(td(b)),[$n]:b||{},[Gi]:w||{},[La]:_||{},[_s]:r.minimalFlagCalledEvents===!0},h?{[Zr]:h}:{},g?{[tr]: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([Pt,Ln]),this.Va(),void Tn.info("All overrides cleared");if(U(t))return this.F({[Pt]:ed(t)}),this.Va(),void Tn.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[Pt]=U(r)?ed(r):r),s&&(i[Ln]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([Pt,Ln]):r===!1?this.q(Pt):s===!1&&this.q(Ln),this.Va(),r===!1?Tn.info("Flag overrides cleared"):r&&Tn.info("Flag overrides set",{flags:r}),void(s===!1?Tn.info("Payload overrides cleared"):s&&Tn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[Pt]:t}),this.Va(),void Tn.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(Jr)||[]).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({[Vi]:Object.keys(td(o)),[$n]:o,[Gt]:k({},this.Oa(Gt)||{},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(Jr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return ce((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({[Jr]: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(Gt)||{},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({[Gt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Gt)||{});t.forEach((i=>{delete n[i]})),this.F({[Gt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Gt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(Nn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[Nn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Nn)||{};this.F({[Nn]:k({},e,{[t]:{}})})}else this.q(Nn)}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}}},jv={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===ji||this.Ya===zr?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=zu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=E==null||(e=E.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 zt.error("started without valid sessionManager"),new Error(Qa+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Xt)throw new Error(Qa+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&be(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(jn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return E&&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),zt.info("starting")):(this.Ya=zu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ji&&this.Ya!==zr&&(this.Ya=Vu),N!=null&&(e=N.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=N.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return zt.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(jl),(e=this.Mr)==null||e.unregister(Lf)}uo(t,e){if(q(t))return null;var n,i=Ae(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(zt.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;q(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[jn]: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===ji&&(this.Ya=zr,zt.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):zt.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(jn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(jn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return zt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!q(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=N.__PosthogExtensions__)==null||!e.initSessionRecording)return zt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Wf]:!0});var r;if(this.Ja||(this.Ja=(r=N.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===zr||this.Ya===ji?void 0:(this.Ya=ji,zt.info("persisted remote config is stale, requesting fresh config before starting"),void new ph(this._instance).load());this.Ya=Vu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Of]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Nf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Bf:Df]:!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))}}},Uv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Hu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=me(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(E&&F){var t=n=>{n=n||E?.event;try{this.bo(n)}catch(i){aa.error("Failed to capture event",i)}};if(be(F,"submit",t,{capture:!0}),be(F,"change",t,{capture:!0}),be(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||E?.event;try{this.bo(n,oa)}catch(i){aa.error("Failed to capture copy/cut event",i)}};be(F,"copy",e,{capture:!0}),be(F,"cut",e,{capture:!0})}}}else aa.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;wt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Pa]: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[Pa],i=this.co,r=this.instance.Qi()&&!this.fo;if(Qe(i)&&!wt(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=Ko(t);Kf(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())&&yu(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===oa;if(i&&(function(d,f,p,h,g,m){var v;if(!E||zl(d)||p!=null&&p.url_allowlist&&!gu(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&gu(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>f.type===S)))return!1}var w=eh(d,h),_=w.parentIsUsefulElement,x=w.targetElementList;if(!(function(S,P){var R=P?.element_allowlist;if(C(R))return!0;var L,$=function(J){if(R.some((G=>J.tagName.toLowerCase()===G)))return{v:!0}};for(var O of S)if(L=$(O))return L.v;return!1})(x,p)||!qa(x,p?.css_selector_allowlist)||qa(x,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Bm))return!1;try{var I=E.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&&(ql.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Fv(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===oa){var l,u=Zf(E==null||(l=E.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 Ue(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(E==null||(e=E.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(){E&&E.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(E&&((e=E.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return Wu;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 Ue(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];Ue(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 Wu}})(E.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=E==null||(e=E.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(si,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};be(E,"popstate",t),this.wo=()=>{E&&E.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Aa]),this.rageclicks=new Hu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return me(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return q(this.Ne.capture_heatmaps)?q(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Tv.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Aa]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ca(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(){E&&F&&(this.Po=this.cr.bind(this),be(E,xs,this.Po),this.Ro=t=>this.ke(t||E?.event),be(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||E?.event),be(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Iu(this.instance,zm,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),be(F,Ss,this.Oo),this.vo=!0)}Eo(){var t;E&&F&&(this.Po&&E.removeEventListener(xs,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.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&&bn(u)&&!rt(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:E)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=Xf(u)}return!1})(Ko(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"),!pu(t.target)&&ca(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&yu(Ko(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!pu(t.target)&&ca(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(E){var e=this.Ne.disable_capture_url_hashes?wn(E.location.href):E.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[..._i,...n||[]]:[],r=fr(e,i,hr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!rn(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Iu,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},q(n?.name)||q(n?.value))Rn.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=Ae(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 Rn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=N.__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 Rn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Ma]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=me(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return q(n)?((e=this._instance.persistence)==null?void 0:e.props[$a])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(me(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=me(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=me(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=me(this.Wo)&&Ae(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:qu;return t>0&&6e4>=t?qu:t}get isEnabled(){var t=we?.protocol;if(t!=="http:"&&t!=="https:")return Rn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=me(this.Wo)?this.Wo.web_vitals:wt(this.Wo)?this.Wo:void 0;return wt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Rn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=me(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=me(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Ma]:n}),this._instance.persistence.register({[$a]: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=N.__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?Rn.error("failed to load script",r):t()}))}Bo(t){var e=t||E?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?wn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[..._i,...i||[]]:[];return fr(n,r,hr)}Rn.error("Could not determine current URL")}}},Hv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(E&&this.isEnabled&&(n=N.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=N.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=N.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=N.__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){Di.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Fa]),this.Jo=new jg(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:Di})),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 me(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?(Di.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Di.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({[Fa]: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)?Di.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 im([new dm,new wm,new hm,new fm,new ym,new vm,new gm,new _m],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var p=uu.test(f)?f.replace(uu,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((b=>{return k({},b,{filename:b.filename||(w=v,w[w.length-1]||{}).filename,function:b.function||vi});var w}))})(u)}})("web:javascript",am,um)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(Ra))!==null&&e!==void 0?e:[],this.el=ys(this.il()),this.rl=new Em(this.el)}onConfigChange(){this.el=ys(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,[Ta]:o})}}}get nl(){var t,e=!!this._instance.get_property(Ta),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(!ee(t)||t.trim().length===0)return void kt.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)=>bm.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&&kt.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[ms]:t,[vs]:new Date().toISOString()},i))}catch(s){kt.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 kt.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 kt.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 kt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&q(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 kt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void kt.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 kt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[ms]:t,[vs]:new Date().toISOString()})}sl(t){return me(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 ee(r)&&r.length>0&&n.$exception_types.push(r),ee(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=Ph[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 kt.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!q(t)&&U(t)}}},Wv=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({[Dl]:!!e.productTours}),!ua(this._instance))return!this.vl&&q((n=this.Mr)==null?void 0:n.props[Ki])||Vr.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&&ua(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Vr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=N.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=N.__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[Ki];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(ua(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||Vr.warn(o):Vr.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({[Ki]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){q(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(Ki)}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)}}},Qs),qv={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=N._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var p=t.$set_once,h=t.$set;return{event:k({},Xd(t,Mv),{properties:k({},t.properties,h?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(It.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)||(It.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,p=(m,v,b)=>{if(m!=null&&m[v]){var w=m[v];m[v]=b(w),c.push((()=>{m[v]=w}))}},h=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:h(v))).filter((v=>!Qe(v)));return p(u,"appendChild",(m=>function(v){var b=h(v);return b?m.call(this,b):v})),p(u,"insertBefore",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):v})),p(u,"replaceChild",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):b})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];var x=g(w);return w.length&&!x.length?void 0:v.apply(this,x)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,b){var w=h(b);return w?m.call(this,v,w):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&&(It.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,It.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){It.error(Gu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){It.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){It.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 It.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;N["__$$ph_site_app_"+u]=r._instance,(l=N.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return It.error(Gu+u,d)}))};for(var a of s.siteApps)o()}else It.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},zv={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=N.__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=N.__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=N.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Rv.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()}}},Vv=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 te.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(q(e))return te.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,te.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)te.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)te.info(Ku);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())te.info("Not loading surveys in cookieless mode without consent.");else{var t=N?.__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 te.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Nv(this._instance),te.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){te.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 te.info(Ku),t([]);var n,i=this._instance.get_property(Na);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?te.error(a):r.error||te.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&(Fh(p)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[Na]:c,[ws]: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(ws);return Ae(t)&&Date.now()-t>3e5}Bl(){return Ae(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Th(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){te.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!q(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);te.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(q(this._surveyManager))return{eligible:!1,reason:Gr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(q(this._surveyManager))return{eligible:!1,reason:Gr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(q(this._surveyManager))return te.warn("init was not called"),{visible:!1,disabledReason:Gr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return q(this._surveyManager)?(te.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Gr})):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(q(this._surveyManager))te.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(yv.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(te.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;te.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),te.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);te.warn("Survey element not found")}else te.warn("Surveys of type "+r.type+" cannot be rendered in the app");else te.warn("Survey not found")}}displaySurvey(t,e){var n;if(q(this._surveyManager))te.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!==Va.Popover&&e.initialResponses&&te.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 te.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==Va.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else te.warn("Survey not found")}}cancelPendingSurvey(t){q(this._surveyManager)?te.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Qs),Gv={toolbar:class{constructor(t){this.instance=t}Wl(t){N.ph_toolbar_state=t}Vl(){var t;return(t=N.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),Wa(this.instance.config)||!E||!F)return!1;t=t??E.location,n=n??E.history;try{if(!e){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}e=E?.localStorage}var i,r=Ov||Ps(t.hash,"__posthog")||Ps(t.hash,"state"),s=r?fu((()=>JSON.parse(atob(decodeURIComponent(r)))))||fu((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(Yu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=N.ph_load_toolbar||N.ph_load_editor;!q(e)&&Ue(e)?e(t,this.instance):Ju.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(Gf));if(!E||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(E.localStorage.setItem(Yu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=N.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Ju.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),be(E,"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)}}},Kv=k({experiments:Oe},Qs),Yv={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;q(e)||(wt(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||Wa(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=N?.__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 dt.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,dt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else dt.error("Cannot complete initialization: remote config is null")}eu(t,e){dt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():dt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Qe(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Wa(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?q(this.Jl)||!this.Jl.token?"missing_token":N!=null&&N.__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 ce((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(dt.warn(Mn),null)}))()}getMessages(t,e){var n=this;return ce((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(dt.warn(Mn),null)}))()}markAsRead(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(dt.warn(Mn),null)}))()}getTickets(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(dt.warn(Mn),null)}))()}requestRestoreLink(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(dt.warn(Mn),null)}))()}restoreFromToken(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(dt.warn(Mn),null)}))()}restoreFromUrlToken(){var t=this;return ce((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(dt.warn(Mn),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()}}},Jv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ve("[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(rd)||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),E&&be(E,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=C(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(f=w?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=w?.["deployment.environment"])!==null&&h!==void 0?h:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,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 em(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},id);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;!q(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){rd(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=N?.__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===Kt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Kt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.LIB_VERSION}}Ot(t){return new Promise((e=>{if(sh(this.Sa,3))e({kind:"fatal",error:fa(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:fa(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:fa(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=oh(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,oe.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,id,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ff(s,Af(n,oe.LIB_NAME,oe.LIB_VERSION),i,oe.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,q(r)||(e.sessionStartTimestamp=r),q(s)||(e.lastActivityTimestamp=s)}if(N!=null&&(t=N.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?wn(N.location.href):N.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Zv={metrics:class{constructor(t){this.rt=ve("[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 tm(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:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.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)}}},Xv=k({},Qs,jv,Uv,Hv,Wv,qv,Vv,zv,Gv,Kv,Yv,Jv,Zv);tt.__defaultExtensionClasses=k({},Xv);var Nh=(function(){oe.SDK_DIST_CHANNEL="npm";var t=rr[oi]=new tt;return(function(){function e(){e.done||(e.done=!0,$h=!1,ae(rr,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():be(F,"DOMContentLoaded",e,{capture:!1}):E&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const Qv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let nt=null,Ms=null,Oh="";const el=new Map;function Bh(t){return[...t.querySelectorAll(Qv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function ey(t){for(const n of document.body.children)n===t||n.tagName==="SCRIPT"||(el.set(n,{inert:n.inert,ariaHidden:n.getAttribute("aria-hidden")}),n.inert=!0,n.setAttribute("aria-hidden","true"));const e=document.activeElement;e&&e!==document.body&&!t.contains(e)&&e.blur()}function ty(){for(const[t,e]of el)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);el.clear()}function Dh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=nt&&nt!==n?nt:null,r=Ms;if(i&&Ge(i,{restoreFocus:!1,force:!0}),nt!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),Ms=a,Oh=document.body.style.overflow,ey(n),document.body.style.overflow="hidden"}nt=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(nt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Bh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function Ge(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Dh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==nt)return!0;ty(),document.body.style.overflow=Oh,nt=null;const i=Ms;return Ms=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function sd(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 ny(t){if(!Dh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ge(t)}document.addEventListener("keydown",t=>{if(!nt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),ny(nt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Bh(nt);if(!e.length){t.preventDefault(),(nt.querySelector(".modal-content")||nt).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 iy(){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 Yl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),ry=Object.freeze({free:2,professional:50,power:2e3}),sy="(contact us)",oy=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 ${sy}`])}),jh="CodeFile",Uh="GeneratedCode",ay={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function vn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tl(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ly(t={},e=0){const n=tl(t.artifactType||t.type||jh),i=tl(t.artifactName||t.name||t.fileName||`${Uh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Hh(t={},e=0){const n=vn(t),i=n.artifactType||n.type||jh,r=n.artifactName||n.name||Uh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:tl(n.id)||ly({...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:Wh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:qh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:vn(n.metadata),codeType:n.codeType||ay[i]||"O"}}function Wh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=vn(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(vn(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function qh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=vn(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 nl(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 pr(t,e={}){const n=[],i=typeof t=="string"?nl(t):t,s=vn(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)=>Hh(d,f)),l=new Map(o.map((d,f)=>[vn(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=qh(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:Wh(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:vn(s.metadata)}}function bi(t){return pr(t).artifacts[0]||Hh()}function an(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Ei(t){return JSON.stringify(t,null,2)}function cy(t){return Ei({task:"architect",userRequest:String(t??"")})}function uy(t){const e=an(t);return e&&typeof e=="object"&&typeof e.task=="string"?Ei(e):Ei({task:"generate_bundle",bundleSpec:e})}function dy(t){return Ei({task:"review_bundle",generatedBundle:an(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 Jl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=an(e)),n}function fy({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return Ei({task:"regenerate_artifact",artifactId:i,bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(r)})}function zh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Ei({task:"regenerate_bundle",bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(i??"")})}const od={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"},hy=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function st(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function py(t){return st(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||st(t.filterSummary)||st(t.filterResults):!1}function Vh(t,e=0){if(!st(t)||e>3)return null;if(py(t))return t;for(const n of hy){const i=t[n];if(st(i)){const r=Vh(i,e+1);if(r)return r}}return null}function $s(t){return Array.isArray(t)?t.some($s):st(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some($s):!1}function il(t){return Array.isArray(t)?t.some(il):st(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(il):!1}function Gh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function gy(t,e){if(st(t))for(const[n,i]of Object.entries(t)){if(!st(i))continue;const r=st(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>st(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Gh(n))}}function my(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>st(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!$s(r))continue;const s=Gh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=st(o)?Object.entries(o).filter(([,l])=>$s(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function vy(t){return od[t]?od[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ad(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 yy(t){const e=Vh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);gy(e.filterSummary,n),my(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=il(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function _y(t,e){const n=yy(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(vy))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ad(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 ${ad(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 wy(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ld(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of wy(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 Zl(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 cd(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 by(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=Zl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await cd(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await cd(c)),n[o]=u,a.type==="F"){const d=ld(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const r=new Set(ld(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 Ey=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),ud={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Sy=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),xy=["Struct","Record"],Iy=[{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=>ha(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=>ha(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 E=typeof window<"u"?window:void 0,Be=typeof globalThis<"u"?globalThis:E,qe=Be?.navigator,F=Be?.document,we=Be?.location,Fl=Be?.fetch,va=Be!=null&&Be.XMLHttpRequest&&"withCredentials"in new Be.XMLHttpRequest?Be.XMLHttpRequest:void 0,Vc=Be?.AbortController,Pg=Be?.CompressionStream,Je=qe?.userAgent;function Yd(){return!(!E||E.navigator.onLine===!1)}var Fi=typeof globalThis<"u"?globalThis:E;Fi&&typeof self>"u"&&(Fi.self=Fi),Fi&&typeof File>"u"&&(Fi.File=function(){});var N=E??{},oe={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 ce(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 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 Jd(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 Kc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Yc(t){return typeof t=="string"||t}function Jc(t){return typeof t=="string"?t:void 0}var Ri,Ag=["$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"],Kt=(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})({}),Zc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Fg=["$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"],Rg=["token"],Zd="NativeGzipValidationError",ya=t=>t.length>=2&&t[0]===31&&t[1]===139,Xc=(t,e)=>t===Zc.GZipJS||e===Zc.GZipJS||e==="gzip",Qc=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Lr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Zd,e},Tg=(function(){var t=ce((function*(e,n){18>e.size&&Lr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());ya(i)&&i[2]===8||Lr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Ri)return Ri;Ri=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;Ri[c]=d>>>0}return Ri})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Lr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Lr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function _a(){return _a=ce((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=ce((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 Tg(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),_a.apply(this,arguments)}var Mg=["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"],eu=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Mg.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Ys=function(t){return t.trim()},wa=function(t){return t.replace(/^\$/,"")};function Xd(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 Qd=Object.prototype,ef=Qd.hasOwnProperty,Js=Qd.toString,U=Array.isArray||function(t){return Js.call(t)==="[object Array]"},Ue=t=>typeof t=="function",me=t=>t===Object(t)&&!U(t),rn=t=>{if(me(t)){for(var e in t)if(ef.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,ee=t=>Js.call(t)=="[object String]",ba=t=>ee(t)&&t.trim().length===0,Qe=t=>t===null,q=t=>C(t)||Qe(t),Ae=t=>Js.call(t)=="[object Number]"&&t==t,Vt=t=>Ae(t)&&t>0,wt=t=>Js.call(t)==="[object Boolean]",$g=t=>t instanceof FormData,Lg=t=>j(Fg,t),Ng=t=>j(Rg,t);function tf(t){return t===null||typeof t!="object"}function cs(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Rl(t){return typeof Event<"u"&&nf(t,Event)}function nf(t,e){try{return t instanceof e}catch{return!1}}var Og=[!0,"true",1,"1","yes"],Oo=t=>j(Og,t),Bg=[!1,"false",0,"0","no"];function Tt(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Ae(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),Tt(r||n,e,n,i))}class Dg{constructor(e){this.tt={},this.et=e.et,this.it=Tt(e.bucketSize,0,100,e.rt),this.nt=Tt(e.refillRate,0,this.it,e.rt),this.st=Tt(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 lt="Mobile",us="iOS",sn="Android",pi="Tablet",rf=sn+" "+pi,sf="iPad",of="Apple",af=of+" Watch",Xi="Safari",gi="BlackBerry",lf="Samsung",cf=lf+"Browser",uf=lf+" Internet",Un="Chrome",jg=Un+" OS",df=Un+" "+us,Tl="Internet Explorer",ff=Tl+" "+lt,Ml="Opera",Ug=Ml+" Mini",$l="Edge",hf="Microsoft "+$l,ci="Firefox",pf=ci+" "+us,ar="Nintendo",lr="PlayStation",ui="Xbox",gf=sn+" "+lt,mf=lt+" "+Xi,Hi="Windows",Ea=Hi+" Phone",tu="Nokia",Sa="Ouya",vf="Generic",Hg=vf+" "+lt.toLowerCase(),yf=vf+" "+pi.toLowerCase(),xa="Konqueror",_f="Oculus Browser",ds="Vivaldi",wf="Yandex",fs="Whale",Ia="DuckDuckGo",bf="Pale Moon",hs="Waterfox",Qi="Brave",Ef="Google Search App",xe="(\\d+(\\.\\d+)?)",Bo=new RegExp("Version/"+xe),Wg=new RegExp(ui,"i"),qg=new RegExp(lr+" \\w+","i"),zg=new RegExp(ar+" \\w+","i"),Ll=new RegExp(gi+"|PlayBook|BB10","i"),Vg={"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"},Sf=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?Qi:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Ef:j(t," OPR/")&&j(t,"Mini")?Ug:j(t," OPR/")?Ml:Ll.test(t)?gi:j(t,"IE"+lt)||j(t,"WPDesktop")?ff:j(t,"OculusBrowser")?_f:j(t,cf)?uf:j(t,$l)||j(t,"Edg/")?hf:j(t,ds+"/")?ds:j(t,"YaBrowser/")?wf:j(t,fs+"/")?fs:j(t,Ia+"/")||j(t,"Ddg/")?Ia:j(t,"FBIOS")?"Facebook "+lt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?df:j(t,"CrMo")||j(t,Un)?Un:j(t,sn)&&j(t,Xi)?gf:j(t,"FxiOS")?pf:j(t.toLowerCase(),xa.toLowerCase())?xa:j(t,Qi+"/")?Qi:((s,o)=>o&&j(o,of)||(function(a){return j(a,Xi)&&!j(a,Un)&&!j(a,sn)})(s))(t,e)?j(t,lt)?mf:Xi:j(t,"PaleMoon/")?bf:j(t,hs+"/")?hs:j(t,ci)?ci:j(t,"MSIE")||j(t,"Trident/")?Tl:j(t,"Gecko")?ci:"")},Gg={[ff]:[new RegExp("rv:"+xe)],[hf]:[new RegExp($l+"?\\/"+xe)],[Un]:[new RegExp("("+Un+"|CrMo)\\/"+xe)],[df]:[new RegExp("CriOS\\/"+xe)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+xe)],[Xi]:[Bo],[mf]:[Bo],[Ml]:[new RegExp("(Opera|OPR)\\/"+xe)],[ci]:[new RegExp(ci+"\\/"+xe)],[pf]:[new RegExp("FxiOS\\/"+xe)],[xa]:[new RegExp("Konqueror[:/]?"+xe,"i")],[gi]:[new RegExp(gi+" "+xe),Bo],[gf]:[new RegExp("android\\s"+xe,"i")],[uf]:[new RegExp(cf+"\\/"+xe)],[_f]:[new RegExp("OculusBrowser\\/"+xe)],[ds]:[new RegExp(ds+"\\/"+xe)],[wf]:[new RegExp("YaBrowser\\/"+xe)],[fs]:[new RegExp(fs+"\\/"+xe)],[Qi]:[new RegExp(Qi+"\\/"+xe)],[Ia]:[new RegExp("(DuckDuckGo|Ddg)\\/"+xe)],[bf]:[new RegExp("PaleMoon\\/"+xe)],[hs]:[new RegExp(hs+"\\/"+xe)],[Ef]:[new RegExp("GSA\\/"+xe)],[Tl]:[new RegExp("(rv:|MSIE )"+xe)],Mozilla:[new RegExp("rv:"+xe)]},Kg=function(t,e,n,i){var r=Sf(t,e,n,i),s=Gg[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},nu=[[new RegExp(ui+"; "+ui+" (.*?)[);]","i"),t=>[ui,t&&t[1]||""]],[new RegExp(ar,"i"),[ar,""]],[new RegExp(lr,"i"),[lr,""]],[Ll,[gi,""]],[new RegExp(Hi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ea,""];if(new RegExp(lt).test(e)&&!/IEMobile\b/.test(e))return[Hi+" "+lt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Vg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Hi,i]}return[Hi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[us,[t[3],t[4],t[5]||"0"].join(".")]:[us,""]],[/(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("("+sn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+sn+")","i"),t=>t&&t[2]?[sn,[t[2],t[3],t[4]||"0"].join(".")]:[sn,""]],[/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/,[jg,""]],[/Linux|debian/i,["Linux",""]]],iu=function(t){return zg.test(t)?ar:qg.test(t)?lr:Wg.test(t)?ui:new RegExp(Sa,"i").test(t)?Sa:new RegExp("("+Ea+"|WPDesktop)","i").test(t)?Ea:/iPad/.test(t)?sf:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?af:Ll.test(t)?gi:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(tu,"i").test(t)?tu:/(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(lt).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)?sn:rf:new RegExp("(pda|"+lt+")","i").test(t)?Hg:new RegExp(pi,"i").test(t)&&!new RegExp(pi+" pc","i").test(t)?yf:""},Yg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ru(t,e){return typeof(n=t)=="string"&&Yg.test(n)?t:e();var n}function wn(t){return t&&t.split("#")[0]}function Nl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function su(t,e,n){return xf.apply(this,arguments)}function xf(){return(xf=ce((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=Nl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var Jg=t=>t instanceof Error,If={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}},Zg=If.info;function kf(t){if(wt(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=>kf(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function ps(t){var e=[];for(var n in t){var i=t[n];Qe(i)||C(i)||e.push({key:n,value:kf(i)})}return e}function Xg(t,e){var n=If[t.level||"info"]||Zg,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),q(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),q(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:ps(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 Cf(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 Pf(t,e,n,i){return{resourceLogs:[{resource:{attributes:ps(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let Qg=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:Xg(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 ce((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return ce((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Kt.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=Pf(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(Kt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return ce((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Kt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Kt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Cf(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Kt.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(Kt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Nl((()=>{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(Kt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return ce((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield su(n,t):yield n}))()}flushWithTimeout(t){var e=this;return ce((function*(){var n=e.flush();yield su(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 Do=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ou(t){return String(t)+"000000"}function au(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 em=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=ce((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=au(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(Do.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,Do)]+=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=Nl((()=>{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 ce((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:ps(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=ou(Date.now()),n=new Map;for(var i of t.values()){var r,s=au(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=ps((r=i.attributes)!==null&&r!==void 0?r:{}),l=ou(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:Do})}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 Nr,lu,jo;function tm(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return jo&&n.length===lu||(lu=n.length,jo=n.reduce(((i,r)=>{Nr||(Nr={});var s=Nr[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,Nr[r]=[u,c];break}}return i}),{})),jo}}class nm{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 ce((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 ce((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:tm(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 mi="?";function ka(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?mi:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Af=(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]:mi,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},im=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,rm=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,sm=/\((\S*)(?::(\d+))(?::(\d+))\)/,om=(t,e)=>{var n=im.exec(t);if(n)return ka(e,n[1],mi,+n[2],+n[3]);var i=rm.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=sm.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Af(i[1]||mi,i[2]);return ka(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},am=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,lm=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,cm=(t,e)=>{var n=am.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=lm.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]||mi,o=Af(s,r);return ka(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},cu=/\(error: (.*)\)/;class um{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=ee(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 cs(e,"DOMException")}isDOMError(e){return cs(e,"DOMError")}}class dm{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 nf(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 fm{constructor(){}match(e){return!!cs(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 ee(e.message)&&e.message.length>0}pe(e){var n=e;if(ee(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 hm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class pm{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(hm);return r&&(n=r[1],i=r[2]),[n,i]}}var gm=["fatal","error","warning","log","info","debug"];function Ff(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 mm{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var i,r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(i=this.getStack(e))!==null&&i!==void 0?i:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Rl(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var i=this.getObjectClassName(e);return(i&&i!=="Object"?"'"+i+"'":"Object")+" captured as exception with keys: "+Ff(e)}isSeverityLevel(e){return ee(e)&&!ba(e)&&gm.indexOf(e)>=0}getStack(e){try{return ee(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ee(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(Jg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class vm{match(e){return Rl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Ff(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class ym{match(e){return tf(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 _m{match(e){return cs(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Rl(e))return!1;try{var n=e.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(e,n){var i,r=this.getUnhandledRejectionReason(e);return tf(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 gs="$message",ms="$timestamp",wm=new Set([gs,ms]),Uo={enabled:!0,max_bytes:32768};function vs(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Uo.enabled,max_bytes:Em(t.max_bytes,Uo.max_bytes)}:k({},Uo)}class bm{constructor(e){this.Ke=[],this.Je=0,this.Ne=vs(e)}setConfig(e){this.Ne=vs(e),this.Xe()}add(e){var n=(function(r){var s;try{s=Xd(r)}catch{return}try{var o=JSON.parse(s);if(!me(o))return;var a=o,l=a[gs],u=a[ms];return!ee(l)||l.trim().length===0||!ee(u)&&!Ae(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 Em(t,e){if(!Ae(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Rf=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(E&&(oe.DEBUG||E.POSTHOG_DEBUG||n)&&!C(E.console)&&E.console){for(var s=("__rrweb_original__"in E.console[r])?E.console[r].__rrweb_original__:E.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)=>Rf(t+" "+r,s)};return i},A=Rf("[PostHog.js]"),ve=A.createLogger,Sm=ve("[ExternalScriptsLoader]"),Ho=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Sm.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)};N.__PosthogExtensions__=N.__PosthogExtensions__||{},N.__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)}Ho(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");Ho(t,o,n)}},N.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);Ho(t,i,n)};oe.DEBUG=!1,oe.LIB_VERSION="1.415.7",oe.LIB_NAME="web";var Tf="$people_distinct_id",cr="$device_id",Wo="$device_model",Wi="__alias",qi="__timers",Ca="$autocapture_disabled_server_side",Pa="$heatmaps_enabled_server_side",Aa="$exception_capture_enabled_server_side",Fa="$error_tracking_suppression_rules",Ra="$error_tracking_capture_extension_exceptions",Ta="$web_vitals_enabled_server_side",Ol="$dead_clicks_enabled_server_side",Bl="$product_tours_enabled_server_side",Ma="$web_vitals_allowed_metrics",Dn="$session_recording_remote_config",Mf="$replay_sample_rate",$f="$replay_override_sampling",Lf="$replay_override_linked_flag",Nf="$replay_override_url_trigger",Of="$replay_override_event_trigger",oi="$sesid",Dl="$session_is_sampled",$n="$enabled_feature_flags",zi="$active_feature_flags",Yr="$early_access_features",$a="$feature_flag_details",Vi="$feature_flag_payloads",Jr="$feature_flag_request_id",ys="$minimal_flag_called_events",At="$override_feature_flags",Ln="$override_feature_flag_payloads",Gt="$stored_person_properties",Nn="$stored_group_properties",La="$surveys",_s="$surveys_loaded_at",Na="$surveys_activated",Zr="$surveys_activated_session",Xr="$surveys_activated_timestamps",Gi="ph_product_tours",Bn="$flag_call_reported",Ki="$flag_call_reported_session_id",Qr="$feature_flag_errors",er="$feature_flag_evaluated_at",ft="$user_state",Oa="$client_session_props",Ba="$capture_rate_limit",Da="$initial_campaign_params",ja="$initial_referrer_info",ws="$initial_person_info",bs="$epp",Or="$posthog_cookieless",Bf="$cookieless_mode",Df="$sdk_debug_extensions_init_method",jf="$sdk_debug_extensions_init_time_ms",Uf="$sdk_debug_recording_script_not_loaded",jl="PostHog loadExternalDependency extension not found.",On="on_reject",Xt="always",Qn="anonymous",Pn="identified",Ua="identified_only",Es="visibilitychange",Ss="beforeunload",ri="$pageview",qo="$pageleave",zo="$identify",uu="$groupidentify";function Br(t,e){U(t)&&t.forEach(e)}function ae(t,e){if(!q(t))if(U(t))t.forEach(e);else if($g(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)ef.call(t,n)&&e(t[n],n)}var ge=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 es(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 du=function(t){try{return t()}catch{return}},xm=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)}}},Ul=function(t){var e={};return ae(t,(function(n,i){(ee(n)&&n.length>0||Ae(n))&&(e[i]=n)})),e},Im=["herokuapp.com","vercel.app","netlify.app"];function km(t){var e=t?.hostname;if(!ee(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Im)if(n===i)return!1;return!0}function be(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 Ha(t){return t.name==="ph_toolbar_internal"}var Hf=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 Ae(t)&&isFinite(t)&&Math.floor(t)===t});class xs{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 xs(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 xs(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 Cm{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 xs.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 Pm}}var fu,Wf=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};E&&!C(E.crypto)&&crypto.getRandomValues&&(Wf=t=>crypto.getRandomValues(t));class Pm{nextUint32(){return this.R.length>this.O||(Wf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Yt=()=>Am().toString(),Am=()=>(fu||(fu=new Cm)).generate(),Ti="",Fm=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:Hf,H(t){var e;try{e=JSON.parse(Qt.P(t))||{}}catch{}return e},F(t,e,n,i,r){if(!F)return!1;try{var s="",o="",a=(function(c,d){if(d){var f=(function(h,g){if(g===void 0&&(g=F),Ti)return Ti;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),b="dmn_chk_"+Yt();!Ti&&v--;){var w=m.slice(v).join("."),_=b+"=1;domain=."+w+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(b)&&(g.cookie=_+";max-age=0",Ti=w)}return Ti})(c);if(!f){var p=(h=>{var g=h.match(Fm);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}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}}},Vo=null,de={N(){if(!Qe(Vo))return Vo;var t=!0;if(C(E))t=!1;else try{var e="__mplssupport__";de.F(e,"xyz"),de.P(e)!=='"xyz"'&&(t=!1),de.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Vo=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return E?.localStorage.getItem(t)}catch(e){de.j(e)}return null},H(t){try{return JSON.parse(de.P(t))||{}}catch{}return null},F(t,e){try{return E?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){de.j(n)}return!1},q(t){try{E?.localStorage.removeItem(t)}catch(e){de.j(e)}}},Rm=[cr,"distinct_id",oi,Dl,bs,ws,ft],Dr={},Tm={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>Dr[t]||null,H:t=>Dr[t]||null,F:(t,e)=>(Dr[t]=e,!0),q(t){delete Dr[t]}},An=null,Ie={N(){if(!Qe(An))return An;if(An=!0,C(E))An=!1;else try{var t="__support__";Ie.F(t,"xyz"),Ie.P(t)!=='"xyz"'&&(An=!1),Ie.q(t)}catch{An=!1}return An},j(t){A.error("sessionStorage error: ",t)},P(t){try{return E?.sessionStorage.getItem(t)}catch(e){Ie.j(e)}return null},H(t){try{return JSON.parse(Ie.P(t))||null}catch{}return null},F(t,e){try{return E?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){Ie.j(n)}return!1},q(t){try{E?.sessionStorage.removeItem(t)}catch(e){Ie.j(e)}}};class Mm{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===Xt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===On}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 Oo(e)?1:j(Bg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?de:Qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Qt:de;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Oo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[qe?.doNotTrack,qe?.msDoNotTrack,N.doNotTrack].some((e=>Oo(e)))}}function qf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Ue(i))return e;try{var r=i(e);return ee(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var zf="__POSTHOG_TOOLBAR__",$m=1,Lm=3,Nm=11;function hu(t){return t instanceof Element&&(t.id===zf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function bn(t){return!!t&&t.nodeType===$m}function rt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Vf(t){return!!t&&t.nodeType===Lm}function Gf(t){return!!t&&t.nodeType===Nm&&bn(t.host)}var Kf=1e3;function Hl(t){return t?Ys(t).split(/\s+/):[]}function pu(t,e){var n=(function(i){var r,s=E==null||(r=E.location)==null?void 0:r.href;return C(s)?void 0:qf(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 Hl(e)}function Yf(t){return q(t)?null:Ys(t).split(/(\s+)/).filter((e=>tr(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function ur(t){var e="";return qa(t)&&!Qf(t)&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;Vf(n)&&n.textContent&&(e+=(i=Yf(n.textContent))!==null&&i!==void 0?i:"")})),Ys(e)}function Go(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Wl=["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 Jf(t){var e=t.parentNode;return!(!e||!bn(e))&&e}var Om=[".ph-no-autocapture","[data-ph-no-autocapture]"],Zf=["next","previous","prev",">","<"],Bm=[...Zf,"+","-","−","–"],gu=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,mu=[".ph-no-rageclick",".ph-no-capture"],Dm=["","text","search","email","password","url","tel","number"];function vu(t,e){if(!E||ql(t))return!1;var n,i,r,s,o;if(wt(e)?(n=!!e&&mu,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:mu,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!bn(l))&&(!!rt(l,"textarea")||(rt(l,"input")?j(Dm,(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=Xf(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=Zf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,p=d.ariaLabel;return c.some((h=>gu(f,h)||gu(p,h)))}))})(i,a.map((l=>{var u;return{safeText:ur(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!Wa(a,n)}var ql=t=>!t||rt(t,"html")||!bn(t),Xf=(t,e)=>{if(!E||ql(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!rt(r,"body");)if(Gf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=Jf(r);if(!s)break;if(e||Wl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=E.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function qa(t){for(var e=new Set,n=0,i=t;i.parentNode&&!rt(i,"body");i=i.parentNode){if(n++>=Kf||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(ee(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!ee(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 Qf(t){return!!(rt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||rt(t,"select")||rt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var yu=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}))$"),_u=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,jm=[16,15,14,13],Um=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),wu=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),bu=/[0-9A-Za-z_]/;function Hm(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 tr(t,e){if(e===void 0&&(e=!0),q(t))return!1;if(ee(t)){t=Ys(t);var n=e?yu.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(_u.lastIndex=0;s=_u.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of jm){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(yu.test(d)&&Hm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Um.test(t):(function(r){var s;for(wu.lastIndex=0;s=wu.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&bu.test(o)&&bu.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Eu(t){var e=ur(t);return tr(e=(e+" "+eh(t)).trim())?e:""}function eh(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=ur(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+eh(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function Su(t){return t.replace(/"|\\"/g,'\\"')}function Wm(t){var e=t.attr__class;if(e)return U(e)?e:Hl(e)}var jr=ve("[Dead Clicks]"),qm=()=>!0,zm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(Ol)),i=t.instance.config.capture_dead_clicks;return wt(i)?i:!!me(i)||n};class xu{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({[Ol]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=N.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?jr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=N.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=me(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=N.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),jr.info("starting...")}}else jr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,jr.info("stopping..."))}}var Ko=ve("[SegmentIntegration]"),th="posthog-js";function nh(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,p,h,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,b=((d=c.exception)==null?void 0:d.values)||[],w=b.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=b[0])==null?void 0:f.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=b[0])==null?void 0:h.value)||c.message,$sentry_exception_type:(g=b[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 Vm{constructor(e,n,i,r,s,o){this.name=th,this.setupOnce=function(a){a(nh(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Iu{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=E?.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?Tt(a/o,0,1,A):1,p=o>1?Tt(l/o,0,1,A):1,h=u>1?Tt(c/u,0,1,A):1,g=u>1?Tt(d/u,0,1,A):1;r=ge(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Yo=["flags","surveys"],Gm={[Tf]:{exposure:"hidden"},[Wi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[qi]:{exposure:"hidden"},[Ca]:{exposure:"event"},[Pa]:{exposure:"hidden"},[Aa]:{exposure:"event"},[Fa]:{exposure:"hidden"},[Ra]:{exposure:"event"},[Ta]:{exposure:"event"},[Ol]:{exposure:"event"},[Bl]:{exposure:"hidden"},[Ma]:{exposure:"event"},[Dn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[oi]:{exposure:"hidden"},[Dl]:{exposure:"event"},[Mf]:{exposure:"event",shouldSkipFromEventProperties:t=>Qe(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"},[$n]:{exposure:"hidden",storageGroup:"flags"},[zi]:{exposure:"hidden",storageGroup:"flags"},[Yr]:{exposure:"hidden"},[$a]:{exposure:"hidden",storageGroup:"flags"},[Vi]:{exposure:"hidden",storageGroup:"flags"},[Jr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ys]:{exposure:"hidden",storageGroup:"flags"},[At]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Gt]:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[La]:{exposure:"hidden",storageGroup:"surveys"},[_s]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Na]:{exposure:"event"},[Zr]:{exposure:"hidden"},[Xr]:{exposure:"hidden"},[Gi]:{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"},[Bn]:{exposure:"hidden"},[Ki]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[er]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[Oa]:{exposure:"hidden"},[Ba]:{exposure:"hidden"},[Da]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[ws]:{exposure:"hidden"},[bs]:{exposure:"hidden"},[$f]:{exposure:"event"},[Lf]:{exposure:"event"},[Nf]:{exposure:"event"},[Of]:{exposure:"event"},[Df]:{exposure:"event"},[jf]:{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"}},Km=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Fn=t=>{var e=Gm[t];if(e)return e;for(var n of Km){var i=n[1];if(t.indexOf(n[0])===0)return i}},ai=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return Xd(t)}},ks=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},vi=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," ")},dr=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},Cs=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},ih=(t,e)=>t>=e&&Yd(),rh=(t,e,n,i)=>{if(t===0){if(Yd()){var r=e+1;return r===n&&i(),r}return e}return 0},Ur="https?://(.*)",yi=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Ym=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...yi],fr="",Jm=["li_fat_id"];function sh(t,e,n){if(!F)return{};var i,r=e?[...yi,...n||[]]:[],s=oh(dr(F.URL,r,fr),t),o=(i={},ae(Jm,(function(a){var l=Hf(a);i[a]=l||null})),i);return ge(o,s)}function oh(t,e){var n=Ym.concat(e||[]),i={};return ae(n,(function(r){var s=vi(t,r);i[r]=s||null})),i}function ah(t){var e=(function(s){return s?s.search(Ur+"google.([^/?]*)")===0?"google":s.search(Ur+"bing.com")===0?"bing":s.search(Ur+"yahoo.com")===0?"yahoo":s.search(Ur+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!Qe(e)){i.$search_engine=e;var r=F?vi(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function ku(){return navigator.language||navigator.userLanguage}var Ps="$direct";function lh(){return F?.referrer||Ps}function ch(t,e,n){n===void 0&&(n=!1);var i=t?[...yi,...e||[]]:[],r=n?wn(we?.href):we?.href,s=r?.substring(0,1e3);return{r:lh().substring(0,1e3),u:s?dr(s,i,fr):void 0}}function uh(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?wn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==Ps?Ps:(n=ks(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=ks(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=oh(s);ge(o,l)}if(i){var u=ah(i);ge(o,u)}return o}function dh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Zm(){try{return new Date().getTimezoneOffset()}catch{return}}var Xm={flags:er,surveys:_s},Qm=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ei="main";class Jo{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(),E){var r=()=>this.flush();be(E,"beforeunload",r,{capture:!1}),be(E,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Ae(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){Qm.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=[...Rm,...o];return k({},de,{H(u){try{var c={};try{c=Qt.H(u)||{}}catch{}var d,f=JSON.parse(de.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];Qe(g)||g===""||(p[h]=g)}d=ge(f,p)}else d=ge(c,f);return de.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=de.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Qt.F(u,m,d,f,p,h)}catch(v){de.j(v)}return g},q(u,c){try{E?.localStorage.removeItem(u),Qt.q(u,c)}catch(d){de.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&de.N()?(n=de,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&Ie.N()?n=Ie:s==="memory"?n=Tm: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 ae(this.props,((n,i)=>{var r=Fn(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=ge({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Yo){var n=de.H(this.Si(e));if(n&&!rn(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ge(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Fn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=Xm[e];if(!i)return!1;var r=n[i],s=this.props[i];return Ae(r)&&Ae(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Fn(e))==null?void 0:n.storageGroup:void 0,r=i?de.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,ei))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,ei),Yo)){var s,o=i[r];(!rn(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(de,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ae(this.props,((i,r)=>{var s,o=(s=Fn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===ei)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ae(e,((r,s)=>{var o;i[s]=(o=Fn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===ei||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!==ei&&(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 Yo)de.q(this.Si(r));i?delete this.ci[ei]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(me(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ae(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(me(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ae(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||me(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=sh(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);rn(Ul(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?ah(e):{})}update_referrer_info(){var e;this.register_once({$referrer:lh(),$referring_domain:F!=null&&F.referrer&&((e=ks(F.referrer))==null?void 0:e.host)||Ps},void 0)}set_initial_person_info(){this.props[Da]||this.props[ja]||this.register_once({[ws]:ch(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={};ae([ja,Da],(r=>{var s=this.props[r];s&&ae(s,(function(o,a){e["$initial_"+wa(a)]=o}))}));var n=this.props[ws];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=uh(r,s),a={};return ae(o,(function(l,u){a["$initial_"+wa(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ge(e,i)}return e}safe_merge(e){return ae(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,p)=>f===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[qi]||{};i[e]=n,this.Pi(qi,i),this.save()}remove_event_timer(e){var n=this.props[qi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(qi,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=Fn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Fn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Hr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Ue(n.then)&&n.then(void 0,(()=>{}))}}}}var He={GZipJS:"gzip-js",Base64:"base64"},Mi={Activation:"events",Cancellation:"cancelEvents"},Zo={Popover:"popover",API:"api",Widget:"widget"},en={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Xo={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},za={Popover:"popover",Inline:"inline"},ev={SHOWN:"product tour shown"},Cu={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Pu=ve("[RateLimiter]");class tv{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=>{Pu.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Pu.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(Ba))!==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=(Ae(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(Ba,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")&&we!=null&&we.pathname)return""+((e=we.origin)!==null&&e!==void 0?e:"")+we.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 mn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void mn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return mn.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){mn.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||mn.warn("Failed to fetch remote config from PostHog."):mn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){mn.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){mn.error("Error loading feature flags",r)}}}var pt=Uint8Array,Xe=Uint16Array,_i=Uint32Array,zl=new pt([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]),Vl=new pt([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]),Au=new pt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),hh=function(t,e){for(var n=new Xe(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]},ph=hh(zl,2),Va=ph[1];ph[0][28]=258,Va[258]=28;for(var Fu=hh(Vl,0)[1],gh=new Xe(32768),Ee=0;32768>Ee;++Ee){var ti=(43690&Ee)>>>1|(21845&Ee)<<1;gh[Ee]=((65280&(ti=(61680&(ti=(52428&ti)>>>2|(13107&ti)<<2))>>>4|(3855&ti)<<4))>>>8|(255&ti)<<8)>>>1}var nr=function(t,e,n){for(var i=t.length,r=0,s=new Xe(e);i>r;++r)++s[t[r]-1];var o,a=new Xe(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Xe(i),r=0;i>r;++r)o[r]=gh[a[t[r]-1]++]>>>15-t[r];return o},zn=new pt(288);for(Ee=0;144>Ee;++Ee)zn[Ee]=8;for(Ee=144;256>Ee;++Ee)zn[Ee]=9;for(Ee=256;280>Ee;++Ee)zn[Ee]=7;for(Ee=280;288>Ee;++Ee)zn[Ee]=8;var As=new pt(32);for(Ee=0;32>Ee;++Ee)As[Ee]=5;var nv=nr(zn,9),iv=nr(As,5),mh=function(t){return(t/8>>0)+(7&t&&1)},vh=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Xe?Xe:t instanceof _i?_i:pt)(n-e);return i.set(t.subarray(e,n)),i},qt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},$i=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},Qo=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 pt(0),0];if(r==1){var o=new pt(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 p=new Xe(f+1),h=Ga(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var b=s[i].s;if(e>=p[b])break;g+=v-(1<>>=m;g>0;){var w=s[i].s;e>p[w]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new pt(p),h]},Ga=function(t,e,n){return t.s==-1?Math.max(Ga(t.l,e,n+1),Ga(t.r,e,n+1)):e[t.s]=n},Ru=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Xe(++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]},Li=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ka=function(t,e,n){var i=n.length,r=mh(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)},Tu=function(t,e,n,i,r,s,o,a,l,u,c){qt(e,c++,n),++r[256];for(var d=Qo(r,15),f=d[0],p=d[1],h=Qo(s,15),g=h[0],m=h[1],v=Ru(f),b=v[0],w=v[1],_=Ru(g),x=_[0],I=_[1],T=new Xe(19),S=0;b.length>S;++S)T[31&b[S]]++;for(S=0;x.length>S;++S)T[31&x[S]]++;for(var P=Qo(T,7),R=P[0],L=P[1],$=19;$>4&&!R[Au[$-1]];--$);var O,J,G,M,K=u+5<<3,ie=Li(r,zn)+Li(s,As)+o,B=Li(r,f)+Li(s,g)+o+14+3*$+Li(T,R)+(2*T[16]+3*T[17]+7*T[18]);if(ie>=K&&B>=K)return Ka(e,c,t.subarray(l,l+u));if(qt(e,c,1+(ie>B)),c+=2,ie>B){O=nr(f,p),J=f,G=nr(g,m),M=g;var Z=nr(R,L);for(qt(e,c,w-257),qt(e,c+5,I-1),qt(e,c+10,$-4),c+=14,S=0;$>S;++S)qt(e,c+3*S,R[Au[S]]);c+=3*$;for(var se=[b,x],Ce=0;2>Ce;++Ce){var Q=se[Ce];for(S=0;Q.length>S;++S)qt(e,c,Z[ue=31&Q[S]]),c+=R[ue],ue>15&&(qt(e,c,Q[S]>>>5&127),c+=Q[S]>>>12)}}else O=nv,J=zn,G=iv,M=As;for(S=0;a>S;++S)if(i[S]>255){var ue;$i(e,c,O[257+(ue=i[S]>>>18&31)]),c+=J[ue+257],ue>7&&(qt(e,c,i[S]>>>23&31),c+=zl[ue]);var ye=31&i[S];$i(e,c,G[ye]),c+=M[ye],ye>3&&($i(e,c,i[S]>>>5&8191),c+=Vl[ye])}else $i(e,c,O[i[S]]),c+=J[i[S]];return $i(e,c,O[256]),c+J[256]},rv=new _i([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),sv=(function(){for(var t=new _i(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),ea=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function ov(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=sv[255&p^f[h]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,p,h,g,m){var v=d.length,b=new pt(h+v+5*(1+Math.floor(v/7e3))+g),w=b.subarray(h,b.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=Ka(w,_,d.subarray(x,I)):(w[x]=!0,_=Ka(w,_,d.subarray(x,v)))}else{for(var T=rv[f-1],S=T>>>13,P=8191&T,R=(1<x;++x){var ue=G(x),ye=32767&x,je=$[ue];if(L[ye]=je,$[ue]=ye,x>=Ce){var xt=v-x;if((B>7e3||se>24576)&&xt>423){_=Tu(d,w,0,M,K,ie,Z,se,Q,x-Q,_),se=B=Z=0,Q=x;for(var _e=0;286>_e;++_e)K[_e]=0;for(_e=0;30>_e;++_e)ie[_e]=0}var et=2,It=0,Cn=P,Le=ye-je&32767;if(xt>2&&ue==G(x-Le))for(var Re=Math.min(S,xt)-1,Dt=Math.min(32767,x),Jn=Math.min(258,xt);Dt>=Le&&--Cn&&ye!=je;){if(d[x+et]==d[x+et-Le]){for(var Ke=0;Jn>Ke&&d[x+Ke]==d[x+Ke-Le];++Ke);if(Ke>et){if(et=Ke,It=Le,Ke>Re)break;var Zn=Math.min(Le,Ke-2),jt=0;for(_e=0;Zn>_e;++_e){var Ut=x-Le+_e+32768&32767,ut=Ut-L[Ut]+32768&32767;ut>jt&&(jt=ut,je=Ut)}}}Le+=(ye=je)-(je=L[ye])+32768&32767}if(It){M[se++]=268435456|Va[et]<<18|Fu[It];var Ht=31&Va[et],Pi=31&Fu[It];Z+=zl[Ht]+Vl[Pi],++K[257+Ht],++ie[Pi],Ce=x+et,++B}else M[se++]=d[x],++K[d[x]]}}_=Tu(d,w,!0,M,K,ie,Z,se,Q,x-Q,_)}return vh(b,0,h+mh(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var p=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&ea(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),ea(u,c-8,n.d()),ea(u,c-4,i),u}var av=!!va||!!Fl,yh="text/plain",ts=!1,_h=(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:"")},Zs=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("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return ae(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},ta=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===He.GZipJS){var i=ov((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new pt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new pt(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return vh(c,0,d)})(ai(e)),{mtime:0});return{contentType:yh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===He.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(ai(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:ai(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=ai(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},wh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Zs(t.url,{compression:He.Base64}),encodedBody:ta(k({},t,{compression:He.Base64,Ji:void 0}))}:{url:_h(t.url,"compression"),encodedBody:ta(k({},t,{compression:void 0,Ji:void 0}))};try{e=ta(t)}catch(r){if(Xc(t.compression,vi(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&Xc(t.compression,vi(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?ya(new Uint8Array(n)):ArrayBuffer.isView(n)&&ya(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(ts=!0,i()):{url:t.url,encodedBody:e}},bh=t=>{try{return wh(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},lv=(function(){var t=ce((function*(e){var n=ai(e.data),i=yield(function(s,o,a){return _a.apply(this,arguments)})(n,oe.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:yh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),cv=/Failed to fetch|NetworkError|Load failed/i,Eh=t=>t?.name==="TypeError"&&cv.test(t?.message||""),Sh=t=>{var e=bh(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ae(t.headers,(function(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Vc){var d=new Vc;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||Eh(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;Fl(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(h){u&&clearTimeout(u.timeout),f(h)}}},Ya=t=>{try{var e,n=wh(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(qe.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 Ya(k({},t,{data:d(u.slice(0,c))})),void Ya(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Sh(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Mu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Zs(n===He.GZipJS?_h(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===He.GZipJS?{}:{compression:n}))},ns=[];Fl&&ns.push({transport:"fetch",method:Sh}),va&&ns.push({transport:"XHR",method(t){var e=bh(t);if(e){var n=new va,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ae(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)}}}),qe!=null&&qe.sendBeacon&&ns.push({transport:"sendBeacon",method:Ya});var Ja=3e3;class uv{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Tt(n?.flush_interval_ms||Ja,250,5e3,A.createLogger("flush interval"),Ja),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)&&ae(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 ae(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 dv=["retriesPerformedSoFar"];class fv{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(E)&&"onLine"in E.navigator&&(this.dr=E.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},be(E,"online",this.vr),be(E,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=Jd(e,dv);Vt(n)&&(i.url=Zs(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(E)||(this.vr&&(E.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(E.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 hv{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(){be(E,"scroll",this.yr,{capture:!0}),be(E,"scrollend",this.yr,{capture:!0}),be(E,"resize",this.yr)}scrollElement(){if(!this._r)return E?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=E?.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 E?e==="y"?E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop||0:E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var pv=t=>ch(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class $u{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({[Oa]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||pv,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Oa]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?uh(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 ae(Ul(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+wa(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 Ni=ve("[SessionId]");class Lu{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)=>!(!Vt(u)||!Vt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Xt)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||Yt,this.Nr=i||Yt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Tt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ni.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=Ie.H(this.jr),a=Ie.H(this.Br);o&&!a?this.Or=o:Ie.q(this.jr),Ie.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){Ni.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&&Ie.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&Ie.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?Ie.H(this.jr):null}Zr(e){var n=this.Pr;return!Qe(n)&&!Qe(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({[oi]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Vt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(oi):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Qe(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({[oi]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Vt(e)?e:0,i=Vt(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[oi];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&&E&&(E.removeEventListener(Ss,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&Ie.q(this.Br)},be(E,Ss,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Xt)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=Vt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||Ni.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),Ni.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Ni.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Vt(a)&&e&&!u?a:i,v=Vt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var b={noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(s,l,b))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var xh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&eu(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>eu(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Ih(){return(Ih=ce((function*(){var t=qe?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return ee(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 Fs=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 na(t,e,n){return ai({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var kh={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=>Fs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Fs(n,i))))),icontains:(t,e)=>e.map(Wr).some((n=>t.map(Wr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Wr).every((n=>t.map(Wr).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 Ch(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Qe(r))return!1;var s=[String(r)],o=kh[i.operator];return!!o&&o(i.values,s)}))}var Za="custom",Nu="i.posthog.com",gv=/^\/static\//;class mv{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":Za),this.en[this.apiHost]}rn(e){if(gv.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===Za)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 Ph(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var te=ve("[Surveys]"),Ah="seenSurvey_",Fh=t=>{try{var e=(n=>((i,r)=>""+Ah+(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){te.error("Failed to persist survey seen state",n)}},vv=[Zo.Popover,Zo.Widget,Zo.API],yv={ignoreConditions:!1,ignoreDelay:!1,displayType:za.Popover},_v=ve("[PostHog ExternalIntegrations]"),wv={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class bv{constructor(e){this._instance=e}ai(e,n){var i;(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return _v.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=N.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(wv[l],(()=>{var c;(c=N.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=N.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=N.__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 Ev{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return ce((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&&Ue(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 Sv{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 Ou="extensionsRemoteConfig";class xv{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Sv(e),this.onEvent=n=>Hr(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 Hr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(Ou,i);return this.un&&i(this.un),Hr(r)},this.vn=new Ev(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(cr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(cr);return typeof e=="string"?e:void 0}get library(){return{name:oe.LIB_NAME,version:oe.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 ce((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 Hr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(Ou,e))}sendRequest(e,n){var i=this;return ce((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?Zs(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 ir={},ia=0,Rs=()=>{},Bu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Oi="Surveys module not available",Du="sanitize_properties is deprecated. Use before_send instead",Rh="Invalid value for property_denylist config: ",Iv=["token","distinct_id",Bf],si="posthog",Th=!av&&Je?.indexOf("MSIE")===-1&&Je?.indexOf("Mozilla")===-1,ra=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:km(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Rs,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:we&&ee(we?.search)&&we.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:(E==null||(e=E.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:Ua,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Ja},error_tracking:{},_onCapture:Rs},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Bm,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))},kv=[["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"]],ju=t=>{var e={};for(var n of kv){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=ge({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),ee(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(Rh+t.property_denylist)),s};class Cv{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 tt{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===Xt||this.config.cookieless_mode===On&&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 Cv,this.mn=!1,this.version=oe.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=ra(),this.SentryIntegration=Vm,this.sentryIntegration=i=>(function(r,s){var o=nh(r,s);return{name:th,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 hv(this),this.pageViewManager=new Iu(this),this.rateLimiter=new tv(this),this.requestRouter=new mv(this),this.consent=new Mm(this),this.externalIntegrations=new bv(this);var n=(e=tt.__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=ee(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=ee(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!==si){var r,s=(r=ir[i])!==null&&r!==void 0?r:new tt;return s._init(e,n,i),ir[i]=s,ir[si][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=ee(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=ra(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=ra(n.defaults),u=ju(n),c=ge({},l,u,{name:i,token:a});me(l.rageclick)&&me(u.rageclick)&&(c.rageclick=ge({},l.rageclick,u.rageclick)),me(l.session_recording)&&me(u.session_recording)&&(c.session_recording=ge({},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:He.GZipJS;var d=this.En();if(this.persistence=new Jo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Jo(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&&Ie.N()){var f=Ie.H(this.bn);U(f)&&f.forEach((I=>{ee(I)&&this.yn.add(I)}))}else Ie.q(this.bn);var p=k({},this.persistence.props),h=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new uv((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new fv(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Lu(this),this.sessionPropsManager=new $u(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.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)),oe.DEBUG=oe.DEBUG||this.config.debug,oe.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p,s:h}),!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(),b=this.persistence.get_property(ft);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Qn)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Pn)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 w=this.config.get_device_id(Yt()),_=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(ft,n.bootstrap.isIdentifiedID?Pn:Qn),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Or,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Yt());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ft,Qn)}return be(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var S=I.config.segment;if(!S)return T();(function(P,R){var L=P.config.segment;if(!L)return R();var $=J=>{var G=()=>J.anonymousId()||Yt();P.config.get_device_id=G,J.id()&&(P.register({distinct_id:J.id(),$device_id:G()}),P.persistence.set_property(ft,Pn)),R()},O=L.user();"then"in O&&Ue(O.then)?O.then($):$(O)})(I,(()=>{S.register((P=>{typeof Promise<"u"&&Promise.resolve||Ko.warn("This browser does not have Promise support, and can not use the segment integration");var R=(L,$)=>{if(!$)return L;L.event.userId||L.event.anonymousId===P.get_distinct_id()||(Ko.info("No userId set, resetting PostHog"),P.reset()),L.event.userId&&L.event.userId!==P.get_distinct_id()&&(Ko.info("UserId set, identifying with PostHog"),P.identify(L.event.userId));var O=P.calculateEventProperties($,L.event.properties);return L.event.properties=Object.assign({},O,L.event.properties),L};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:L=>R(L,L.event.event),page:L=>R(L,ri),identify:L=>R(L,zo),screen:L=>R(L,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),Ue(this.config._onCapture)&&this.config._onCapture!==Rs&&(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 Ih.apply(this,arguments)})().then((I=>{I&&this.register({[Wo]:I})})).catch(Rs),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=tt.__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)),Ue(this.featureFlags.onReloading)&&Ue(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({},tt.__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,zm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Df]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[jf]: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,He.GZipJS)?He.GZipJS:j(r.supportedCompression,He.Base64)?He.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:Ua}),(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&&we!=null&&we.hostname){var e=we.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 fh(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Br(this.__request_queue,(e=>this.Pn(e))),this.__request_queue=[],this.Bn()}_handle_unload(){var e,n,i,r,s;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(n=this.metrics)==null||n.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(qo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(qo,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=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=He.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((b=>k({},b,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Mu(o.url,o.method,o.compression,o.timestampMode);var p=ns.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var b=0;m.length>b;b++)if(m[b].transport===f)return m[b]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){Eh(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===He.GZipJS&&Pg&&typeof Promise<"u"&&!ts?lv(o).then((m=>{g(m)})).catch((m=>{if(Qc(m))return ts=!0,void g(k({},o,{compression:void 0,url:Mu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var b="name"in v?String(v.name):"";return Qc(v)||b===Zd})(m)&&(ts=!0),g(o)})):h(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){ia++;try{var n,i=[],r=[],s=[];Br(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(Ue(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&&Ue(this[n])?s.push(a):r.push(a)}));var o=function(a,l){Br(a,(function(u){try{if(U(u[0])){var c=l;ae(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{ia--}}push(e){if(ia>0&&U(e)&&ee(e[0])){var n=tt.prototype[e[0]];Ue(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)&&ee(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&&!ee(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,p=ru(i?.uuid,Yt),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===ri&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(ys)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,b,w,_=g?void 0:this.Vn(i?.$set_once,e!==uu,e===zo);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=$=>ee($)?$.slice(0,s):$,l=new Set,h=(function $(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var G;if(l.add(O),U(O))G=[],Br(O,(K=>{G.push($(K))}));else{var M={};ae(O,((K,ie)=>{l.has(K)||(M[ie]=$(K))})),G=M}return G}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function($,O){O===void 0&&(O=[]);var J={},G=M=>{$[M]!==void 0&&(J[M]=$[M])};return Ag.forEach(G),O.forEach(G),J})(h.properties,Iv)),e===en.DISMISSED||e===en.SENT){var x=n?.[Xo.SURVEY_ID],I=n?.[Xo.SURVEY_ITERATION];Fh({id:x,current_iteration:I}),h.$set=k({},h.$set,{[(v={id:x,current_iteration:I},b=e===en.SENT?"responded":"dismissed",w="$survey_"+b+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+b+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===en.SHOWN&&(h.$set=k({},h.$set,{[Xo.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===ev.SHOWN){var T=n?.[Cu.TOUR_TYPE];T&&(h.$set=k({},h.$set,{[Cu.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var S=k({},h.properties.$set,h.$set);if(rn(S)||this.setPersonPropertiesForFlags(S),!q(this.config.before_send)){var P=this.Pt(h);if(!P)return;(h=P).uuid=ru(h.uuid,Yt)}this.dn.emit("eventCaptured",h);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),L={method:"POST",url:R,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"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(L):this.In.enqueue(L),h}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new xv(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[Bf]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!ee(a.distinct_id)&&!Ae(a.distinct_id)||ba(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,S){var P,R,L,$;if(S===void 0&&(S=!1),!Je)return{};var O,J=x?[...yi,...I||[]]:[],G=(function(Jn){for(var Ke=0;nu.length>Ke;Ke++){var Zn=nu[Ke],jt=Zn[1],Ut=Zn[0].exec(Jn),ut=Ut&&(Ue(jt)?jt(Ut,Jn):jt);if(ut)return ut}return["",""]})(Je),M=G[0],K=G[1],ie=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},B={};C(T)||(B.detectGoogleSearchApp=T);var Z={},se=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,Ce=(R=navigator)==null?void 0:R.maxTouchPoints,Q=E==null||(L=E.screen)==null?void 0:L.width,ue=E==null||($=E.screen)==null?void 0:$.height,ye=E?.devicePixelRatio;C(se)||(Z.userAgentDataPlatform=se),C(Ce)||(Z.maxTouchPoints=Ce),C(Q)||(Z.screenWidth=Q),C(ue)||(Z.screenHeight=ue),C(ye)||(Z.devicePixelRatio=ye);var je,xt,_e,et,It,Cn,Le,Re,Dt=ge(Ul({$os:M,$os_version:K,$browser:Sf(Je,navigator.vendor,ie,B),$device:iu(Je),$device_type:(xt=Je,_e=Z,Re=iu(xt),Re===sf||Re===rf||Re==="Kobo"||Re==="Kindle Fire"||Re===yf?pi:Re===ar||Re===ui||Re===lr||Re===Sa?"Console":Re===af?"Wearable":Re?lt:_e?.userAgentDataPlatform==="Android"&&((et=_e?.maxTouchPoints)!==null&&et!==void 0?et:0)>0?600>Math.min((It=_e?.screenWidth)!==null&&It!==void 0?It:0,(Cn=_e?.screenHeight)!==null&&Cn!==void 0?Cn:0)/((Le=_e?.devicePixelRatio)!==null&&Le!==void 0?Le:1)?lt:pi:"Desktop"),$timezone:dh(),$timezone_offset:Zm()}),{$current_url:dr(S?wn(we?.href):we?.href,J,fr),$host:we?.host,$pathname:we?.pathname,$raw_user_agent:Je.length>1e3?Je.substring(0,997)+"...":Je,$browser_version:Kg(Je,navigator.vendor,ie,B),$browser_language:ku(),$browser_language_prefix:(je=ku(),typeof je=="string"?je.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:oe.LIB_NAME,$lib_version:oe.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return oe.SDK_DIST_CHANNEL&&(Dt.$sdk_dist_channel=oe.SDK_DIST_CHANNEL),Dt})(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&&ge(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ge(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===Za&&(a.$lib_custom_api_host=this.config.api_host),u=e!==ri||s?e!==qo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=ge(a,u),e===ri&&F&&(a.title=F.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}Je&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ae(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var b of this._n.slice())try{ge(v,b())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=ge({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ae(this.config.property_denylist,(function(x){delete a[x]})):A.error(Rh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(A.error(Du),a=w(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=ge({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(Du),a=l(a,"$set_once")),n&&(this.mn=!0),rn(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||!Ie.N())Ie.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?Ie.F(this.bn,n):Ie.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:Oi}),()=>{})}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:Oi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Oi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=yv),(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:Oi}}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:Oi})}Jn(e){return!e||ba(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Or?(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(Ae(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(cr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(Wi)&&(this.unregister(Wi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ft)||Qn)===Qn,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ft,Pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(zo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=na(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ft,Pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=na(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Bn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=na(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=>ee(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(uu,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var p,h=this.get_property(cr),g=this.get_property(Wo),m=this.get_property(Dn),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(p=this.persistence)==null||p.register({[Dn]: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(ft,Qn),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Xt)this.register_once({distinct_id:Or,$device_id:null},"");else{var b=this.config.get_device_id(Yt());this.register_once({distinct_id:b,$device_id:e?b:h},""),e||C(g)||this.register({[Wo]: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 ce((function*(){var i,r,s,o,a,l,u;if(n.__loaded){(i=n.Un)==null||i.stop(),(r=n.jn)==null||r.dispose(),(s=n.sessionRecording)==null||s.dispose(),(o=n.logs)==null||o.flushLogs("sendBeacon"),(a=n.metrics)==null||a.flush("sendBeacon"),(l=n.In)==null||l.unload(),(u=n.Rn)==null||u.unload();try{var c;(c=n.featureFlags)==null||c.destroy()}catch(d){A.error("Error while destroying feature flags",d)}}else A.uninitializedWarning("posthog.shutdown")}))()}setIdentity(e,n){var i;this.config.identity_distinct_id=e,this.config.identity_hash=n,this.alias(e),(i=this.conversations)==null||i.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var n=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=n.sessionStartTimestamp,r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n.sessionId);if(e!=null&&e.withTimestamp&&i){var s,o=(s=e.timestampLookBack)!==null&&s!==void 0?s:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(Tf)?(A.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(C(n)&&(n=this.get_distinct_id()),e!==n?(this.Kn(Wi,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(me(e)){var i,r,s,o,a,l,u,c,d,f,p,h;ge(this.config,ju(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 Jo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);wt(m)&&(this.config.debug=m),wt(this.config.debug)&&(this.config.debug?(oe.DEBUG=!0,de.N()&&de.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(oe.DEBUG=!1,de.N()&&de.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){oe.LIB_NAME=e,oe.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:tt.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:si;return n!==si&&(n=si+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ft))===Pn||((n=this.sessionPersistence)==null?void 0:n.get_property(ft))===Pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===Ua&&!this._isIdentified()&&rn(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Wi])&&((n=this.persistence)==null||(n=n.props)==null||!n[bs]))}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(bs,!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!==On)}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!==Xt){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 Lu(this),this.pageViewManager=new Iu(this),this.persistence&&(this.sessionPropsManager=new $u(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=tt.__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==On&&((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(Bu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Xt?(this.config.cookieless_mode===On&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===On&&(this.register({distinct_id:Or,$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(Bu)}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===Xt||(this.config.cookieless_mode===On?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return qe?xh(qe,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(ri,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(Es,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),be(F,Es,this.kn)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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&&!q(n[i]),l=r in n&&!q(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(q(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Ng),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),q(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Lg(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!rn(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&&q(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=wt(e)&&!e,i=de.N()&&de.P("ph_debug")==="true";return!n&&(!!i||e)}}tt.__defaultExtensionClasses={},tt.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]]=xm(t.prototype[e[n]])})(tt,["identify"]);class Uu{constructor(e){this.disabled=e===!1;var n=me(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 sa="$copy_autocapture",oa=ve("[AutoCapture]");function aa(t,e){return e.length>t?e.slice(0,t)+"...":e}function Pv(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!bn(e));return e}function Av(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!bn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!rt(f,"body")&&Kf>c.length;)if(Gf(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!bn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},b=!1,w=!1;if(ae(c,(S=>{var P=qa(S);if(rt(S,"a")){var R=S.getAttribute("href");b=!!(P&&R&&tr(R))&&(u?wn(R):R)}j(Is(S),"ph-no-capture")&&(w=!0),m.push((function($,O,J,G,M){M===void 0&&(M=!1);var K=$.tagName.toLowerCase(),ie={tag_name:K};Wl.indexOf(K)>-1&&!J&&(ie.$el_text=K.toLowerCase()==="a"||K.toLowerCase()==="button"?aa(1024,Eu($)):aa(1024,ur($)));var B=Is($);B.length>0&&(ie.classes=B.filter((function(Q){return Q!==""}))),ae($.attributes,(function(Q){var ue;if((!Qf($)||["name","id","class","aria-label"].indexOf(Q.name)!==-1)&&(G==null||!G.includes(Q.name))&&!O&&tr(Q.value)&&(!ee(ue=Q.name)||ue.substring(0,10)!=="_ngcontent"&&ue.substring(0,7)!=="_nghost")){var ye=Q.value;Q.name==="class"&&(ye=Hl(ye).join(" ")),ie["attr__"+Q.name]=aa(1024,Q.name==="href"&&M?wn(ye):ye)}}));for(var Z=1,se=1,Ce=$;Ce=Pv(Ce);)Z++,Ce.tagName===$.tagName&&se++;return ie.nth_child=Z,ie.nth_of_type=se,ie})(S,s,o,a,u));var L=(function($){if(!qa($))return{};var O={};return ae($.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var G=J.name.replace("data-ph-capture-attribute-",""),M=J.value;G&&M&&tr(M)&&(O[G]=M)}})),O})(S);ge(v,L)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=rt(t,"a")||rt(t,"button")?Eu(t):ur(t)),b){var _,x;m[0].attr__href=b;var I=(_=ks(b))==null?void 0:_.host,T=E==null||(x=E.location)==null?void 0:x.host;I&&T&&I!==T&&(h=b)}return{props:ge({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((P=>{var R,L,$="";if(P.tag_name&&($+=P.tag_name),P.attr_class)for(var O of(P.attr_class.sort(),P.attr_class))$+="."+O.replace(/"/g,"");var J=k({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(L=P.nth_of_type)!==null&&L!==void 0?L:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),G={};return es(J).sort(((M,K)=>M[0].localeCompare(K[0]))).forEach((M=>{var K=M[1];return G[Su(M[0].toString())]=Su(K.toString())})),($+=":")+es(G).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(S){return S.map((P=>{var R,L,$={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(L=P.attr__href)==null?void 0:L.slice(0,2048),attr_class:Wm(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return es(P).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>$.attributes[O[0]]=O[1])),$}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var Bi=ve("[ExceptionAutocapture]"),Hu=()=>{},Fv=ve("[TracingHeaders]"),Rn=ve("[Web Vitals]"),Wu=9e5,qu="disabled",zu="lazy_loading",Di="awaiting_config",qr="missing_config";ve("[SessionRecording]"),ve("[SessionRecording]");var Xa="[SessionRecording]",zt=ve(Xa),Rv=ve("[Heatmaps]");function la(t){return me(t)&&"clientX"in t&&"clientY"in t&&Ae(t.clientX)&&Ae(t.clientY)}var zr=ve("[Product Tours]"),ca=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Bl))},Tv=["$set_once","$set"],kt=ve("[SiteApps]"),Vu="Error while initializing PostHog app with config id ";function ni(t,e,n){if(q(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 Mv{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"||!ni(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=>ni(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&ni((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=>ni(u.text,n.text,n.text_matching||"exact")||ni(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;!q(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=>ni(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||Ch(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 $v{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&&Ch(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===Mi.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 Mv(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,Mi.Activation),this.ks=this.Ps(e,Mi.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,Mi.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,Mi.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&&(rn(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Ae(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=>Ae(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 Lv extends $v{constructor(e){super(e)}Js(){return Na}Ys(){return Zr}Ms(){return Xr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Xr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Xr)}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 Ae(r)&&r>0}ra(){return en.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 te}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Na]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Zr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Zr)}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 Ph(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===en.SHOWN?"consume":"ignore":e===en.SHOWN?"persist":e===en.DISMISSED||e===en.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Vr="SDK is not enabled or survey functionality is not yet loaded",Gu="Disabled. Not loading surveys.",Nv=E!=null&&E.location?Cs(E.location.hash,"__posthog")||Cs(location.hash,"state"):null,Ku="_postHogToolbarParams",Yu=ve("[Toolbar]"),Ju=ve("[FeatureFlags]");class Ov{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||(Ju.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)||Ju.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Zu=ve("[FeatureFlags]"),Tn=ve("[FeatureFlags]",{debugEnabled:!0}),ua=`" failed. Feature flags didn't load in time.`,Xu="connection_error",Qu=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},ed=t=>{var e={};for(var n of es(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},Ct=ve("[Error tracking]"),td="Refusing to render web experiment since the viewer is a likely bot",Bv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Fs(e,t),not_regex:(t,e)=>!Fs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Oe{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Oe.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Oe.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);ee(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];Oe.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())Oe.aa(td);else if(!this.Ne.disable_web_experiments){if(q(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Oe.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=Oe.getWindowLocation();if(e!=null&&e.search){var n=vi(e?.search,"__experiment_id"),i=vi(e?.search,"__experiment_variant");n&&i&&(Oe.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&&(Oe.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!q(e.conditions)&&Oe.da(e,n)&&Oe.va(e)}static da(e,n){var i;if(q(e.conditions)||q((i=e.conditions)==null?void 0:i.url))return!0;var r=Oe.getWindowLocation();if(r){var s,o,a,l=qf(n,r.href);return(s=e.conditions)==null||!s.url||Bv[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return E?.location}static va(e){var n;if(q(e.conditions)||q((n=e.conditions)==null?void 0:n.utm))return!0;var i=sh();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,h=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&h&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Oe.aa(td):n!=="control"?i.forEach((r=>{if(r.selector){var s;Oe.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)}))}})):Oe.aa("Control variants leave the page unmodified.")}_is_bot(){return qe&&this._instance?xh(qe,this.Ne.custom_blocked_useragents):void 0}}var dt=ve("[Conversations]"),Mn="Conversations not available yet.",nd="console",Mh="__posthogHandledLogsRequestError",da=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Mh]=!0,n},id=t=>!!t&&typeof t=="object"&&t[Mh]===!0,Xs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Zu,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 Ov(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 E&&be(E,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){E?.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=[],E?.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[zi,Vi,Jr,At]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa($n);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(er);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($n))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Vi))!==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:Yc(f),variant:Jc(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($a),e=this.Oa(At),n=this.Oa(Ln);if(!n&&!e)return t||{};var i=ge({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],p=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Yc(i),variant:Jc(i),payload:Kc(e[n])}}))}getFlagVariants(){var t=this.Oa($n),e=this.Oa(At);if(!e)return t||{};for(var n=ge({},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(Vi),e=this.Oa(Ln);if(!e)return t||{};for(var n=ge({},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(Bn)}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(Gt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Nn),timezone:dh()};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({[Qr]:[Xu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?He.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Xu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[Qr]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(p,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return ih(this.Sa,3)}Ua(t){this.Sa=rh(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+ua)}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(Jr)||void 0,u=this.Oa(er)||void 0,c=this.Oa(Bn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Ki);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Bn]:c,[Ki]:n});else{var h,g,m,v,b,w,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Bn]:c},n?{[Ki]:n}:{}));var S=this.getFeatureFlagDetails(t),P=[...(h=this.Oa(Qr))!==null&&h!==void 0?h:[]];C(s)&&P.push("flag_missing");var R={$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(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),C(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var L,$=(w=S==null||(_=S.reason)==null?void 0:_.description)!==null&&w!==void 0?w:S==null||(x=S.reason)==null?void 0:x.code;$&&(R.$feature_flag_reason=$),S!=null&&(I=S.metadata)!=null&&I.id&&(R.$feature_flag_id=S.metadata.id),C(S?.original_variant)&&C(S?.original_enabled)||(R.$feature_flag_original_response=C(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(T=S.metadata)!=null&&T.original_payload&&(R.$feature_flag_original_payload=S==null||(L=S.metadata)==null?void 0:L.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[Bn]:c,[Ki]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Kc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+ua)}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 ce((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"?He.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+ua),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=Zu);var c=((I,T)=>{var S=I.flags;return S?k({},I,{featureFlags:Object.fromEntries(Object.keys(S).map((P=>{var R;return[P,(R=S[P].variant)!==null&&R!==void 0?R:S[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((P=>S[P].enabled)).filter((P=>{var R;return(R=S[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=S[P].metadata)==null?void 0:R.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,p=c.featureFlagPayloads;if(f){var h=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[zi]:f,[$n]:m,[ys]:!1}}var b=f,w=p,_=d;if(l!=null&&l.partialResponse)b=k({},s,b),w=k({},o,w),_=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)})));b=k({},s,Object.fromEntries(Object.entries(b).filter((I=>x.has(I[0]))))),w=k({},o,Object.fromEntries(Object.entries(w||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else b=k({},s,b),w=k({},o,w),_=k({},a,_);return k({[zi]:Object.keys(ed(b)),[$n]:b||{},[Vi]:w||{},[$a]:_||{},[ys]:r.minimalFlagCalledEvents===!0},h?{[Jr]:h}:{},g?{[er]: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([At,Ln]),this.Va(),void Tn.info("All overrides cleared");if(U(t))return this.F({[At]:Qu(t)}),this.Va(),void Tn.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[At]=U(r)?Qu(r):r),s&&(i[Ln]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([At,Ln]):r===!1?this.q(At):s===!1&&this.q(Ln),this.Va(),r===!1?Tn.info("Flag overrides cleared"):r&&Tn.info("Flag overrides set",{flags:r}),void(s===!1?Tn.info("Payload overrides cleared"):s&&Tn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[At]:t}),this.Va(),void Tn.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(Yr)||[]).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({[zi]:Object.keys(ed(o)),[$n]:o,[Gt]:k({},this.Oa(Gt)||{},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(Yr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return ce((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({[Yr]: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(Gt)||{},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({[Gt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Gt)||{});t.forEach((i=>{delete n[i]})),this.F({[Gt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Gt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(Nn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[Nn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Nn)||{};this.F({[Nn]:k({},e,{[t]:{}})})}else this.q(Nn)}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}}},Dv={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===Di||this.Ya===qr?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=qu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=E==null||(e=E.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 zt.error("started without valid sessionManager"),new Error(Xa+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Xt)throw new Error(Xa+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&be(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(Dn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return E&&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),zt.info("starting")):(this.Ya=qu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Di&&this.Ya!==qr&&(this.Ya=zu),N!=null&&(e=N.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=N.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return zt.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(Mf)}uo(t,e){if(q(t))return null;var n,i=Ae(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(zt.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;q(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[Dn]: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===Di&&(this.Ya=qr,zt.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):zt.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(Dn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(Dn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return zt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!q(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=N.__PosthogExtensions__)==null||!e.initSessionRecording)return zt.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=N.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===qr||this.Ya===Di?void 0:(this.Ya=Di,zt.info("persisted remote config is stale, requesting fresh config before starting"),void new fh(this._instance).load());this.Ya=zu,(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({[Lf]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[$f]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Nf: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))}}},jv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Uu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=me(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(E&&F){var t=n=>{n=n||E?.event;try{this.bo(n)}catch(i){oa.error("Failed to capture event",i)}};if(be(F,"submit",t,{capture:!0}),be(F,"change",t,{capture:!0}),be(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||E?.event;try{this.bo(n,sa)}catch(i){oa.error("Failed to capture copy/cut event",i)}};be(F,"copy",e,{capture:!0}),be(F,"cut",e,{capture:!0})}}}else oa.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;wt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Ca]: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[Ca],i=this.co,r=this.instance.Qi()&&!this.fo;if(Qe(i)&&!wt(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=Go(t);Vf(i)&&(i=i.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&vu(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===sa;if(i&&(function(d,f,p,h,g,m){var v;if(!E||ql(d)||p!=null&&p.url_allowlist&&!pu(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&pu(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>f.type===S)))return!1}var w=Xf(d,h),_=w.parentIsUsefulElement,x=w.targetElementList;if(!(function(S,P){var R=P?.element_allowlist;if(C(R))return!0;var L,$=function(J){if(R.some((G=>J.tagName.toLowerCase()===G)))return{v:!0}};for(var O of S)if(L=$(O))return L.v;return!1})(x,p)||!Wa(x,p?.css_selector_allowlist)||Wa(x,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Om))return!1;try{var I=E.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&&(Wl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Av(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===sa){var l,u=Yf(E==null||(l=E.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 Ue(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(E==null||(e=E.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(){E&&E.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(E&&((e=E.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return Hu;var o={next:i[r]},a=s((function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)}));return Ue(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];Ue(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else i[r]=o.next}}catch{return Hu}})(E.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=E==null||(e=E.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(ri,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};be(E,"popstate",t),this.wo=()=>{E&&E.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[Pa]),this.rageclicks=new Uu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return me(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return q(this.Ne.capture_heatmaps)?q(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Rv.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({[Pa]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){la(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(){E&&F&&(this.Po=this.cr.bind(this),be(E,Ss,this.Po),this.Ro=t=>this.ke(t||E?.event),be(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||E?.event),be(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new xu(this.instance,qm,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),be(F,Es,this.Oo),this.vo=!0)}Eo(){var t;E&&F&&(this.Po&&E.removeEventListener(Ss,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&&bn(u)&&!rt(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:E)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=Jf(u)}return!1})(Go(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"),!hu(t.target)&&la(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&vu(Go(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!hu(t.target)&&la(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(E){var e=this.Ne.disable_capture_url_hashes?wn(E.location.href):E.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...yi,...n||[]]:[],r=dr(e,i,fr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!rn(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:xu,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},q(n?.name)||q(n?.value))Rn.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=Ae(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 Rn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=N.__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 Rn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Ta]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=me(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return q(n)?((e=this._instance.persistence)==null?void 0:e.props[Ma])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(me(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=me(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=me(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=me(this.Wo)&&Ae(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Wu;return t>0&&6e4>=t?Wu:t}get isEnabled(){var t=we?.protocol;if(t!=="http:"&&t!=="https:")return Rn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=me(this.Wo)?this.Wo.web_vitals:wt(this.Wo)?this.Wo:void 0;return wt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Rn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=me(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=me(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Ta]:n}),this._instance.persistence.register({[Ma]: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=N.__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?Rn.error("failed to load script",r):t()}))}Bo(t){var e=t||E?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?wn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...yi,...i||[]]:[];return dr(n,r,fr)}Rn.error("Could not determine current URL")}}},Uv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(E&&this.isEnabled&&(n=N.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=N.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=N.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=N.__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){Bi.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Aa]),this.Jo=new Dg(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:Bi})),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 me(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?(Bi.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Bi.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({[Aa]: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)?Bi.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 nm([new um,new _m,new fm,new dm,new vm,new mm,new pm,new ym],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var p=cu.test(f)?f.replace(cu,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((b=>{return k({},b,{filename:b.filename||(w=v,w[w.length-1]||{}).filename,function:b.function||mi});var w}))})(u)}})("web:javascript",om,cm)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(Fa))!==null&&e!==void 0?e:[],this.el=vs(this.il()),this.rl=new bm(this.el)}onConfigChange(){this.el=vs(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({[Fa]: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(!ee(t)||t.trim().length===0)return void Ct.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)=>wm.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&&Ct.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[gs]:t,[ms]:new Date().toISOString()},i))}catch(s){Ct.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 Ct.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 Ct.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 Ct.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&q(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 Ct.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Ct.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 Ct.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[gs]:t,[ms]:new Date().toISOString()})}sl(t){return me(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 ee(r)&&r.length>0&&n.$exception_types.push(r),ee(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=kh[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 Ct.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!q(t)&&U(t)}}},Hv=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({[Bl]:!!e.productTours}),!ca(this._instance))return!this.vl&&q((n=this.Mr)==null?void 0:n.props[Gi])||zr.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&&ca(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?zr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=N.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=N.__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[Gi];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(ca(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||zr.warn(o):zr.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({[Gi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){q(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(Gi)}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)}}},Xs),Wv={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=N._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var p=t.$set_once,h=t.$set;return{event:k({},Jd(t,Tv),{properties:k({},t.properties,h?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(kt.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)||(kt.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,p=(m,v,b)=>{if(m!=null&&m[v]){var w=m[v];m[v]=b(w),c.push((()=>{m[v]=w}))}},h=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:h(v))).filter((v=>!Qe(v)));return p(u,"appendChild",(m=>function(v){var b=h(v);return b?m.call(this,b):v})),p(u,"insertBefore",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):v})),p(u,"replaceChild",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):b})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];var x=g(w);return w.length&&!x.length?void 0:v.apply(this,x)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,b){var w=h(b);return w?m.call(this,v,w):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&&(kt.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,kt.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){kt.error(Vu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){kt.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){kt.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 kt.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;N["__$$ph_site_app_"+u]=r._instance,(l=N.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return kt.error(Vu+u,d)}))};for(var a of s.siteApps)o()}else kt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},qv={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=N.__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=N.__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=N.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Fv.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()}}},zv=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 te.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(q(e))return te.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,te.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)te.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)te.info(Gu);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())te.info("Not loading surveys in cookieless mode without consent.");else{var t=N?.__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(jl);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 te.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Lv(this._instance),te.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){te.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 te.info(Gu),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?te.error(a):r.error||te.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&(Ph(p)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[La]:c,[_s]: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(_s);return Ae(t)&&Date.now()-t>3e5}Bl(){return Ae(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};Fh(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){te.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!q(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);te.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(q(this._surveyManager))return{eligible:!1,reason:Vr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(q(this._surveyManager))return{eligible:!1,reason:Vr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(q(this._surveyManager))return te.warn("init was not called"),{visible:!1,disabledReason:Vr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return q(this._surveyManager)?(te.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Vr})):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(q(this._surveyManager))te.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(vv.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(te.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;te.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),te.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);te.warn("Survey element not found")}else te.warn("Surveys of type "+r.type+" cannot be rendered in the app");else te.warn("Survey not found")}}displaySurvey(t,e){var n;if(q(this._surveyManager))te.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!==za.Popover&&e.initialResponses&&te.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 te.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==za.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else te.warn("Survey not found")}}cancelPendingSurvey(t){q(this._surveyManager)?te.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Xs),Vv={toolbar:class{constructor(t){this.instance=t}Wl(t){N.ph_toolbar_state=t}Vl(){var t;return(t=N.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),Ha(this.instance.config)||!E||!F)return!1;t=t??E.location,n=n??E.history;try{if(!e){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}e=E?.localStorage}var i,r=Nv||Cs(t.hash,"__posthog")||Cs(t.hash,"state"),s=r?du((()=>JSON.parse(atob(decodeURIComponent(r)))))||du((()=>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(Ku)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=N.ph_load_toolbar||N.ph_load_editor;!q(e)&&Ue(e)?e(t,this.instance):Yu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(zf));if(!E||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(E.localStorage.setItem(Ku,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=N.__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)})),be(E,"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)}}},Gv=k({experiments:Oe},Xs),Kv={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;q(e)||(wt(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||Ha(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=N?.__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(jl);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 dt.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,dt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else dt.error("Cannot complete initialization: remote config is null")}eu(t,e){dt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():dt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Qe(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Ha(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?q(this.Jl)||!this.Jl.token?"missing_token":N!=null&&N.__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 ce((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(dt.warn(Mn),null)}))()}getMessages(t,e){var n=this;return ce((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(dt.warn(Mn),null)}))()}markAsRead(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(dt.warn(Mn),null)}))()}getTickets(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(dt.warn(Mn),null)}))()}requestRestoreLink(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(dt.warn(Mn),null)}))()}restoreFromToken(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(dt.warn(Mn),null)}))()}restoreFromUrlToken(){var t=this;return ce((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(dt.warn(Mn),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()}}},Yv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ve("[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(id)||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),E&&be(E,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=C(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(f=w?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=w?.["deployment.environment"])!==null&&h!==void 0?h:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,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 Qg(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},nd);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;!q(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){id(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=N?.__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(jl)}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===Kt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Kt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.LIB_VERSION}}Ot(t){return new Promise((e=>{if(ih(this.Sa,3))e({kind:"fatal",error:da(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:da(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:da(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=rh(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,oe.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,nd,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Pf(s,Cf(n,oe.LIB_NAME,oe.LIB_VERSION),i,oe.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,q(r)||(e.sessionStartTimestamp=r),q(s)||(e.lastActivityTimestamp=s)}if(N!=null&&(t=N.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?wn(N.location.href):N.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Jv={metrics:class{constructor(t){this.rt=ve("[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 em(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:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.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)}}},Zv=k({},Xs,Dv,jv,Uv,Hv,Wv,zv,qv,Vv,Gv,Kv,Yv,Jv);tt.__defaultExtensionClasses=k({},Zv);(function(){oe.SDK_DIST_CHANNEL="npm";var t=ir[si]=new tt;return(function(){function e(){e.done||(e.done=!0,Th=!1,ae(ir,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():be(F,"DOMContentLoaded",e,{capture:!1}):E&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const Xv=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let nt=null,Ts=null,$h="";const Qa=new Map;function Lh(t){return[...t.querySelectorAll(Xv)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function Qv(t){for(const n of document.body.children)n===t||n.tagName==="SCRIPT"||(Qa.set(n,{inert:n.inert,ariaHidden:n.getAttribute("aria-hidden")}),n.inert=!0,n.setAttribute("aria-hidden","true"));const e=document.activeElement;e&&e!==document.body&&!t.contains(e)&&e.blur()}function ey(){for(const[t,e]of Qa)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);Qa.clear()}function Nh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=nt&&nt!==n?nt:null,r=Ts;if(i&&Ge(i,{restoreFocus:!1,force:!0}),nt!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),Ts=a,$h=document.body.style.overflow,Qv(n),document.body.style.overflow="hidden"}nt=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(nt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Lh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function Ge(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Nh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==nt)return!0;ey(),document.body.style.overflow=$h,nt=null;const i=Ts;return Ts=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function rd(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 ty(t){if(!Nh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ge(t)}document.addEventListener("keydown",t=>{if(!nt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),ty(nt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Lh(nt);if(!e.length){t.preventDefault(),(nt.querySelector(".modal-content")||nt).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 ny(){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 Kl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),iy=Object.freeze({free:2,professional:50,power:2e3}),ry="(contact us)",sy=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 ${ry}`])}),Oh="CodeFile",Bh="GeneratedCode",oy={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function vn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function el(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ay(t={},e=0){const n=el(t.artifactType||t.type||Oh),i=el(t.artifactName||t.name||t.fileName||`${Bh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Dh(t={},e=0){const n=vn(t),i=n.artifactType||n.type||Oh,r=n.artifactName||n.name||Bh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:el(n.id)||ay({...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:jh(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:vn(n.metadata),codeType:n.codeType||oy[i]||"O"}}function jh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=vn(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(vn(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=vn(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 tl(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 hr(t,e={}){const n=[],i=typeof t=="string"?tl(t):t,s=vn(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)=>Dh(d,f)),l=new Map(o.map((d,f)=>[vn(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:jh(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:vn(s.metadata)}}function wi(t){return hr(t).artifacts[0]||Dh()}function an(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function bi(t){return JSON.stringify(t,null,2)}function ly(t){return bi({task:"architect",userRequest:String(t??"")})}function cy(t){const e=an(t);return e&&typeof e=="object"&&typeof e.task=="string"?bi(e):bi({task:"generate_bundle",bundleSpec:e})}function uy(t){return bi({task:"review_bundle",generatedBundle:an(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=an(e)),n}function dy({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return bi({task:"regenerate_artifact",artifactId:i,bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(r)})}function Hh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return bi({task:"regenerate_bundle",bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(i??"")})}const sd={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"},fy=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function st(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function hy(t){return st(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||st(t.filterSummary)||st(t.filterResults):!1}function Wh(t,e=0){if(!st(t)||e>3)return null;if(hy(t))return t;for(const n of fy){const i=t[n];if(st(i)){const r=Wh(i,e+1);if(r)return r}}return null}function Ms(t){return Array.isArray(t)?t.some(Ms):st(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(Ms):!1}function nl(t){return Array.isArray(t)?t.some(nl):st(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(nl):!1}function qh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function py(t,e){if(st(t))for(const[n,i]of Object.entries(t)){if(!st(i))continue;const r=st(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>st(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(qh(n))}}function gy(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>st(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!Ms(r))continue;const s=qh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=st(o)?Object.entries(o).filter(([,l])=>Ms(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function my(t){return sd[t]?sd[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function od(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 vy(t){const e=Wh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);py(e.filterSummary,n),gy(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=nl(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function yy(t,e){const n=vy(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(my))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${od(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 ${od(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 _y(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ad(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of _y(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 Jl(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 ld(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 wy(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=Jl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await ld(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await ld(c)),n[o]=u,a.type==="F"){const d=ad(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const r=new Set(ad(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 by=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),cd={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Ey=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Sy=["Struct","Record"],xy=[{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=>fa(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=>fa(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=>ha(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=>fa(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,56 +24,56 @@ 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 Ct(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function gr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Cy(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;rPy(t).usable);function Fy(t=""){const e=gr(t);return Ay.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Ry(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=ky(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rdd(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function eo(t=""){return Array.from(gr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Ty(t="",e=""){return Xl(t,e)?.returnType||null}function fd(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 My(t,e){const n=eo(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>fd(l)===r)||n.length>1)return null;const[o]=n,a=`${fd(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 Ql(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function $y(t,e,n=""){const i=Xl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Zl(r,"A");if(s===i)return null;const o=`${Ql(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 Ly(t="",e=""){return Xl(t,e)!==null}function Ny(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Sy.has(i)?!1:!xy.some(s=>i.endsWith(s))||e.has(i))}function Oy(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Ty(t,e),r=Ny(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 By(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Ey.has(t.artifactType)||n.push(Ct(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(Ct(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(Ct(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(Ct(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Fy(r))n.push(Ct(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Ly(r,t.artifactName)&&n.push(Ct(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(eo(r)),o=Oy(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(Ct(t,"error",o));const a=$y(i,r,t.artifactName);a&&n.push(Ct(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(Ct(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=My(i,r);s&&n.push(Ct(t,"info",s))}return n}function Dy(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>eo(s.code||""))),i=e.flatMap(s=>By(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:ud[s.artifactType]||ud.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const hd="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function pd(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function jy(t=""){const e=t.indexOf(hd);return e===-1?t:t.slice(e+hd.length).replace(/^\s*\n/,"")}const Uy=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Hy(t="",e=""){const n=jy(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(pd).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=pd(s);return o===null||!i.has(o)?!0:!Uy.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Wy=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","flutter_web_plugins","integration_test","sky_engine"]);function qy(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 Zy(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 Xy(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(p=>p.id)).map(p=>n.find(h=>h.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(p=>{const h=Jy(p),g=p.fixedCode||p.code||"",m=p.codeType||Ky[p.artifactType]||it.OTHER;g.trim()||s.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:h,content:g,type:m,path:p.deployPath||Yy(h,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,h)=>({entry:p,index:h})).filter(({entry:p})=>p.type===it.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],h={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Pt(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function pr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function ky(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;rCy(t).usable);function Ay(t=""){const e=pr(t);return Py.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Fy(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=Iy(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rud(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function Qs(t=""){return Array.from(pr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Ry(t="",e=""){return Zl(t,e)?.returnType||null}function dd(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 Ty(t,e){const n=Qs(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>dd(l)===r)||n.length>1)return null;const[o]=n,a=`${dd(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 My(t,e,n=""){const i=Zl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Jl(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 $y(t="",e=""){return Zl(t,e)!==null}function Ly(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Ey.has(i)?!1:!Sy.some(s=>i.endsWith(s))||e.has(i))}function Ny(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Ry(t,e),r=Ly(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 Oy(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(by.has(t.artifactType)||n.push(Pt(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(Pt(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(Pt(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(Pt(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ay(r))n.push(Pt(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!$y(r,t.artifactName)&&n.push(Pt(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(Qs(r)),o=Ny(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(Pt(t,"error",o));const a=My(i,r,t.artifactName);a&&n.push(Pt(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(Pt(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Ty(i,r);s&&n.push(Pt(t,"info",s))}return n}function By(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>Qs(s.code||""))),i=e.flatMap(s=>Oy(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:cd[s.artifactType]||cd.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const fd="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function hd(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Dy(t=""){const e=t.indexOf(fd);return e===-1?t:t.slice(e+fd.length).replace(/^\s*\n/,"")}const jy=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Uy(t="",e=""){const n=Dy(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(hd).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=hd(s);return o===null||!i.has(o)?!0:!jy.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Hy=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","flutter_web_plugins","integration_test","sky_engine"]);function Wy(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 Jy(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 Zy(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(p=>p.id)).map(p=>n.find(h=>h.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(p=>{const h=Yy(p),g=p.fixedCode||p.code||"",m=p.codeType||Gy[p.artifactType]||it.OTHER;g.trim()||s.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:h,content:g,type:m,path:p.deployPath||Ky(h,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,h)=>({entry:p,index:h})).filter(({entry:p})=>p.type===it.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],h={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=h}const u={...gd(t?.dependencies),...r.reduce((p,h)=>({...p,...gd(h.dependencies)}),{})},c={};r.forEach(p=>{ec(p.fixedCode||p.code||"").forEach(h=>{h in u||(c[h]="")})});const d={...c,...u},f=Zy(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 Qy(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),Qy(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=new Map){const n=[],i=[];for(const r of t)(e.has(r.path)?n:i).push(r);return{landed:n,notLanded:i}}function rl(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}function r_(t){return t?t.notLanded.length===0&&t.landed.length>0:!1}function s_(t,e,n){const i=rl(t,e),r=new Map(i);return r.set("pubspec.yaml",{content:n,type:"D",path:"pubspec.yaml"}),r}const md={pass:0,warning:1,fail:2},o_=["manualActions"];function ct(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tn(...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 At(t){return t==null?[]:Array.isArray(t)?t:[t]}function a_(t){const e=ct(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return vd(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?vd(Number(i[1])):null}function vd(t){return t>=0&&t<=100?t:null}function ht(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function tc(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 sl(...t){return t.filter(Boolean).reduce((e,n)=>md[n]>md[e]?n:e,"pass")}function Zh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ct(t),r=tn(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:tc(i.severity||i.status||i.level)||e,message:r,suggestion:tn(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function ol(t,e="review"){const n=ct(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>At(n[r]).map(o=>Zh(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=ct(t),r=tn(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:tn(i.detail,i.instructions,i.description),location:tn(i.location,i.flutterFlowPath,i.path),timing:tn(i.timing,i.phase)||"unspecified",artifactId:n,source:tn(i.source)||"Code Review"}:null}function al(t,e=null){const n=ct(t);return o_.flatMap(i=>At(n[i])).map((i,r)=>l_(i,r,e)).filter(Boolean)}function c_(t){let e=typeof t=="string"?nl(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ct(e);typeof n.content=="string"&&(e=nl(n.content)||e);const i=ct(e),r=ct(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(ht);return t.find(i=>{const r=ct(i);return[r.id,r.fileName,r.artifactName,r.name].map(ht).some(s=>s&&n.includes(s))})||null}function d_(t,e){return At(t?.metadata?.compatibility?.deployHints).find(r=>ht(r?.artifactId)===ht(e.id)||ht(r?.fileName)===ht(e.fileName))?.pathHint||""}function f_(t,e){return At(t?.relationships).filter(n=>ht(n?.from)===ht(e.id)||ht(n?.to)===ht(e.id))}function h_(t,e){return At(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ht(n.artifactId)===ht(e.id)).map(n=>Zh(n,"warning","Compatibility check")).filter(Boolean)}function p_(t,e,n,i){const r=u_(e,n),s=ct(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...ol(s),...h_(t,n)],l=al(s,n.id),u=tc(s.status||s.verdict||s.outcome||s.result),c=a.length?sl(...a.map(f=>f.severity)):null,d=sl(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?tn(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=ct(t),i=At(n.artifacts),{root:r,rawText:s}=c_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ct).find(w=>Object.keys(w).length)||{},a=At(r.artifacts||r.files||r.reviews),l=i.map((w,_)=>p_(n,a,w,_)),u=ol(r),d=[...ol(o),...u],f=[...al(o),...al(r),...l.flatMap(w=>w.manualSteps)].filter((w,_,x)=>x.findIndex(I=>I.title===w.title&&I.artifactId===w.artifactId)===_),p=tc(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=sl(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??r.score??r.overallScore??s,m=a_(g),v=tn(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:h,score:m,artifactPresentations:l,manualSteps:f}),b=l.reduce((w,_)=>(w[_.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:At(n.deployOrder),relationships:At(n.relationships),warnings:At(n.warnings),compatibility:ct(n.metadata?.compatibility)}}const v_="x-ff-api-key",yd="dr_",y_=/^[A-Za-z0-9_-]{1,120}$/;function __(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`${yd}${t.randomUUID()}`;if(t&&typeof t.getRandomValues=="function"){const e=t.getRandomValues(new Uint8Array(16));return`${yd}${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}return null}function w_(t){return typeof t=="string"&&y_.test(t)}function b_(t,e){return`${String(t).replace(/\/deployCustomClasses$/,"")}/runStatus/${encodeURIComponent(e)}`}function E_(t){if(!t||typeof t!="object")return null;const{status:e}=t;return e!=="running"&&e!=="done"&&e!=="failed"?null:{status:e,phase:typeof t.phase=="string"?t.phase:"",message:typeof t.message=="string"?t.message:"",error:typeof t.error=="string"?t.error:null,deployed:Array.isArray(t.deployed)?t.deployed:[],dryRun:t.dryRun===!0}}const S_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function x_(t){return!t||!t.status?{definitive:null}:t.status==="done"?{definitive:"success",deployed:Array.isArray(t.deployed)?t.deployed:[]}:t.status==="failed"&&S_.has(t.phase)?{definitive:"failed",error:t.error||"The deploy failed before writing anything to FlutterFlow."}:{definitive:null}}async function I_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,timeoutMs:r=8e3}){if(!w_(e))return null;const s=i||globalThis.fetch;if(!s)return null;const o=new AbortController,a=setTimeout(()=>o.abort(),r);try{const l=await s(b_(t,e),{method:"GET",headers:{[v_]:String(n||"")},signal:o.signal});if(!l.ok)return null;const u=await l.json();return E_(u)}catch{return null}finally{clearTimeout(a)}}async function k_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,budgetMs:r=12e3,intervalMs:s=2e3}){const o=Date.now()+r;let a=0;for(;Date.now()=2)return{definitive:null};const u=o-Date.now();if(u<=0)break;await new Promise(c=>setTimeout(c,Math.min(s,u)))}return{definitive:null}}const C_=/^\uFEFF/;function Ui(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(C_,"");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 Ui(n);{const c=ll(e);if(!c.error&&o.every(f=>wd(f,c.commentAndStringRanges)))return Ui(n)}if(r===1){const c=Ui(n.slice(0,s)),d=Ui(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[p.index]=h}const u={...pd(t?.dependencies),...r.reduce((p,h)=>({...p,...pd(h.dependencies)}),{})},c={};r.forEach(p=>{Ql(p.fixedCode||p.code||"").forEach(h=>{h in u||(c[h]="")})});const d={...c,...u},f=Jy(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 Xy(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function Qy(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 e_(t,e){const i=[Qy(t),Xy(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 t_(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:e_(i,r),content:r.content,fileName:i,path:r.path});return n}function n_(t,e=new Map){const n=[],i=[];for(const r of t)(e.has(r.path)?n:i).push(r);return{landed:n,notLanded:i}}function il(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}function i_(t){return t?t.notLanded.length===0&&t.landed.length>0:!1}function r_(t,e,n){const i=il(t,e),r=new Map(i);return r.set("pubspec.yaml",{content:n,type:"D",path:"pubspec.yaml"}),r}const gd={pass:0,warning:1,fail:2},s_=["manualActions"];function ct(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tn(...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 Ft(t){return t==null?[]:Array.isArray(t)?t:[t]}function o_(t){const e=ct(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return md(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?md(Number(i[1])):null}function md(t){return t>=0&&t<=100?t:null}function ht(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ec(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 rl(...t){return t.filter(Boolean).reduce((e,n)=>gd[n]>gd[e]?n:e,"pass")}function Kh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ct(t),r=tn(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:ec(i.severity||i.status||i.level)||e,message:r,suggestion:tn(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function sl(t,e="review"){const n=ct(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>Ft(n[r]).map(o=>Kh(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=ct(t),r=tn(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:tn(i.detail,i.instructions,i.description),location:tn(i.location,i.flutterFlowPath,i.path),timing:tn(i.timing,i.phase)||"unspecified",artifactId:n,source:tn(i.source)||"Code Review"}:null}function ol(t,e=null){const n=ct(t);return s_.flatMap(i=>Ft(n[i])).map((i,r)=>a_(i,r,e)).filter(Boolean)}function l_(t){let e=typeof t=="string"?tl(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ct(e);typeof n.content=="string"&&(e=tl(n.content)||e);const i=ct(e),r=ct(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(ht);return t.find(i=>{const r=ct(i);return[r.id,r.fileName,r.artifactName,r.name].map(ht).some(s=>s&&n.includes(s))})||null}function u_(t,e){return Ft(t?.metadata?.compatibility?.deployHints).find(r=>ht(r?.artifactId)===ht(e.id)||ht(r?.fileName)===ht(e.fileName))?.pathHint||""}function d_(t,e){return Ft(t?.relationships).filter(n=>ht(n?.from)===ht(e.id)||ht(n?.to)===ht(e.id))}function f_(t,e){return Ft(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ht(n.artifactId)===ht(e.id)).map(n=>Kh(n,"warning","Compatibility check")).filter(Boolean)}function h_(t,e,n,i){const r=c_(e,n),s=ct(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...sl(s),...f_(t,n)],l=ol(s,n.id),u=ec(s.status||s.verdict||s.outcome||s.result),c=a.length?rl(...a.map(f=>f.severity)):null,d=rl(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?tn(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=ct(t),i=Ft(n.artifacts),{root:r,rawText:s}=l_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ct).find(w=>Object.keys(w).length)||{},a=Ft(r.artifacts||r.files||r.reviews),l=i.map((w,_)=>h_(n,a,w,_)),u=sl(r),d=[...sl(o),...u],f=[...ol(o),...ol(r),...l.flatMap(w=>w.manualSteps)].filter((w,_,x)=>x.findIndex(I=>I.title===w.title&&I.artifactId===w.artifactId)===_),p=ec(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=rl(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??r.score??r.overallScore??s,m=o_(g),v=tn(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:h,score:m,artifactPresentations:l,manualSteps:f}),b=l.reduce((w,_)=>(w[_.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:Ft(n.deployOrder),relationships:Ft(n.relationships),warnings:Ft(n.warnings),compatibility:ct(n.metadata?.compatibility)}}const m_="x-ff-api-key",vd="dr_",v_=/^[A-Za-z0-9_-]{1,120}$/;function y_(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`${vd}${t.randomUUID()}`;if(t&&typeof t.getRandomValues=="function"){const e=t.getRandomValues(new Uint8Array(16));return`${vd}${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}return null}function __(t){return typeof t=="string"&&v_.test(t)}function w_(t,e){return`${String(t).replace(/\/deployCustomClasses$/,"")}/runStatus/${encodeURIComponent(e)}`}function b_(t){if(!t||typeof t!="object")return null;const{status:e}=t;return e!=="running"&&e!=="done"&&e!=="failed"?null:{status:e,phase:typeof t.phase=="string"?t.phase:"",message:typeof t.message=="string"?t.message:"",error:typeof t.error=="string"?t.error:null,deployed:Array.isArray(t.deployed)?t.deployed:[],dryRun:t.dryRun===!0}}const E_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function S_(t){return!t||!t.status?{definitive:null}:t.status==="done"?{definitive:"success",deployed:Array.isArray(t.deployed)?t.deployed:[]}:t.status==="failed"&&E_.has(t.phase)?{definitive:"failed",error:t.error||"The deploy failed before writing anything to FlutterFlow."}:{definitive:null}}async function x_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,timeoutMs:r=8e3}){if(!__(e))return null;const s=i||globalThis.fetch;if(!s)return null;const o=new AbortController,a=setTimeout(()=>o.abort(),r);try{const l=await s(w_(t,e),{method:"GET",headers:{[m_]:String(n||"")},signal:o.signal});if(!l.ok)return null;const u=await l.json();return b_(u)}catch{return null}finally{clearTimeout(a)}}async function I_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,budgetMs:r=12e3,intervalMs:s=2e3}){const o=Date.now()+r;let a=0;for(;Date.now()=2)return{definitive:null};const u=o-Date.now();if(u<=0)break;await new Promise(c=>setTimeout(c,Math.min(s,u)))}return{definitive:null}}const k_=/^\uFEFF/;function ji(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` +`)}function C_(t){const e=String(t??"").replace(k_,"");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 ji(n);{const c=al(e);if(!c.error&&o.every(f=>_d(f,c.commentAndStringRanges)))return ji(n)}if(r===1){const c=ji(n.slice(0,s)),d=ji(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}=al(h),m=p.length+1+f;if(_d(m,g)){l.push(d);continue}a.push(ji(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` -`)}function A_(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 Xh(t){const e=A_(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 Qh(t){return`${Ql(t)}.dart`}function F_(t){return Zl(t,"W")}const _d={"(":")","[":"]","{":"}"},R_={")":"(","]":"[","}":"{"},T_=/[A-Za-z0-9_]/;function ll(t){const e=[{kind:"code",opener:null,openedLine:0}],n=[];let i=1,r=0;const s=(c,d)=>{(c===` +`)}function P_(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function Yh(t){const e=P_(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 Jh(t){return`${Xl(t)}.dart`}function A_(t){return Jl(t,"W")}const yd={"(":")","[":"]","{":"}"},F_={")":"(","]":"[","}":"{"},R_=/[A-Za-z0-9_]/;function al(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]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!T_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(_d[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(R_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&_d[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function M_(t){return ll(String(t??"")).error}function wd(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 $_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],L_="MAGIC_LINK_SENT",N_="PLUS_ALIAS_REJECTED",O_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",to={allowlistedDomains:$_,successCode:L_,validationCode:N_,messageTemplate:O_},B_=new Set(to.allowlistedDomains),D_=to.successCode,j_=to.validationCode;function no(t){return typeof t=="string"?t.trim():""}function U_(t){const e=no(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 B_.has(r)?i.includes("+"):!1}function H_(t,e){return to.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ep(t){if(!U_(t))return null;const e=no(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return H_(e,i)}function ic(t){return!t||typeof t!="object"||Array.isArray(t)||t.success===!1||t.error?!1:t.code?t.code===D_:t.success===!0||typeof t.message=="string"}function tp(t,e){return t?.code===j_?t.message||ep(e)||"Please enter your primary email address.":ic(t)?`Check your email — we sent a link to ${no(e)}`:t?.message||"Something went wrong. Please try again."}const W_="ccc_auth_session",q_="ccc_subscription",z_=Object.freeze(["hasSeenWalkthrough"]);function V_(t){const e=[];for(const n of z_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function G_(){return[W_,q_]}function K_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of G_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function Y_(t){const e=t?.message||t?.error;return typeof e=="string"&&e.trim()?e.trim():"The server could not send the link."}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());if(!ic(o))throw new Error(Y_(o));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 Z_=/^dependencies\s*:\s*(?:#.*)?$/,X_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function xr(t){const e=t.match(X_);return e?e[1]??e[2]??e[3]:null}function Ir(t){const e=t.trim();return e===""||e.startsWith("#")}function En(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function rc(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;sc&&/\s/.test(s[d-1]);)d-=1}return t[r]=s.slice(0,c)+oc(n)+s.slice(d),!0}return!1}function bd(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?oc(i):">=0.0.0"}`]}function n0(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(ap(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=sc(r);if(l){const u=o.flatMap(([c,d])=>bd(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(...bd(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function i0(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=io(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l),d=c&&!c.isScalar&&c.sourceKey===null&&c.version!==null;if(!c||!c.isScalar&&!d||!String(u||"").trim()){a.push(l);continue}if(d){t0(r,c,String(u).trim())?o.push({name:l,from:c.version,to:u}):a.push(l);continue}const f=" ".repeat(En(r[c.lineIndex]));r[c.lineIndex]=`${f}${l}: ${oc(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function cp(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),sc(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),ap(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 r0=">=3.0.0 <4.0.0";function cl(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 s0(t=""){const e=Jh(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Ed(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=cl(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=cl(s.version);continue}i.push(r)}return i}function o0(t){const e=new Set,n=new Set,i={},r={},s=Ed(io(t),i,e),o=Ed(Q_(t,"dependency_overrides"),r,n),a=[...s,...o],l=new Set([...Object.keys(i),...e]),{sdk:u}=lp(t);return{sdkConstraint:cl(u)||r0,dependencies:i,dependencyOverrides:r,sdkPackages:[...e].sort(),sdkOverrides:[...n].sort(),availablePackages:l,unrepresentable:a,unrepresentableOverrides:o}}function a0(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 l0(t,e){const{sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o,availablePackages:a,unrepresentable:l,unrepresentableOverrides:u}=o0(e),c={sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o},d=[],f=[],p=[];for(const h of t){const{className:g,content:m}=h,v=ec(m),b=Jh(m).some(x=>x.startsWith("package:"));if(l.length>0&&b){const x=v.filter(T=>l.includes(T));let I;if(x.length>0)I=`${g} was not compiled before deploying: it imports or exports ${x.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`;else{const T=l.filter(P=>!u.includes(P)),S=[T.length>0?`your project's pubspec.yaml declares ${T.join(", ")} from a source that cannot be reproduced outside it`:null,u.length>0?`your project's dependency_overrides redirects ${u.join(", ")} to a source that cannot be reproduced outside it`:null].filter(Boolean).join(", and ");I=`${g} was not compiled before deploying: ${S}, and an entry like that can change what every package depending on it resolves to - including packages this class reaches transitively - so package resolution could not be matched exactly.`}f.push({className:g,reason:I});continue}const{unresolvableImports:w}=s0(m),_=v.filter(x=>!a.has(x));if(w.length>0||_.length>0){f.push({className:g,reason:a0(g,w,_)});continue}d.push({fileName:`${Ql(g)}.dart`,content:m})}return{manifest:c,sources:d,skipped:f,approximate:p}}function Sd(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=up(s);o&&r.push(o)}return{events:r,buffer:i}}function c0(t){const e=up(t);return e?[e]:[]}function up(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 Ne=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),dp=84e4,fp=1e4;function hp(t){return t?.unconfirmed===!0||t?.outcome===Ne.UNCONFIRMED?Ne.UNCONFIRMED:t?.partial===!0||t?.outcome===Ne.PARTIAL?Ne.PARTIAL:t?.success===!0?Ne.COMMITTED:Ne.FAILED}class We extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Ne.UNCONFIRMED}}function xd({httpStatus:t}={}){return new We(`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 u0(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}if(u.event==="result"){r=u;return}u.event===void 0&&typeof u.success=="boolean"&&(r=u)};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const p=Sd(o,c.decode(f,{stream:!0}));o=p.buffer,p.events.forEach(a)}}else{const u=Sd("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return c0(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 d0=new Set(["connected","workspace_init","workspace_ready","verifying"]);function pp(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?d0.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Id(t){if(t?.finalResultReceived){const e=hp(t);return e===Ne.FAILED&&!pp(t)?Ne.UNCONFIRMED:e}return t?.httpRejected&&typeof t.httpStatus=="number"&&t.httpStatus>=400&&t.httpStatus<500?Ne.FAILED:Ne.UNCONFIRMED}function f0(){let t=document.getElementById("fx-grid");if(!t)return null;const e=window.matchMedia("(prefers-reduced-motion: reduce)"),n=window.matchMedia("(pointer: none)");let i=t.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!0,powerPreference:"low-power"}),r=i?null:t.getContext("2d");if(!i&&!r)return null;const s='',o=`#version 300 es +`){n.push({start:d.startIndex,end:r}),o??=`line ${i}: string starting on line ${d.openedLine} is never closed`,e.pop();continue}if(!d.raw&&c==="\\"){s(t[r+1]??"",t[r+2]??""),r+=2;continue}if(!d.raw&&c==="$"&&t[r+1]==="{"){e.push({kind:"code",opener:null,interpolation:!0}),r+=2;continue}const f=d.triple?3:1;if(c===d.quote&&t.slice(r,r+f)===d.quote.repeat(f)){n.push({start:d.startIndex,end:r+f}),e.pop(),r+=f;continue}s(c,t[r+1]),r++;continue}if(c==="/"&&t[r+1]==="/"){e.push({kind:"line-comment",startIndex:r}),r+=2;continue}if(c==="/"&&t[r+1]==="*"){e.push({kind:"block-comment",startIndex:r,openedLine:i,depth:1}),r+=2;continue}if(c==="'"||c==='"'){const f=t.slice(r,r+3)===c.repeat(3),p=r>0?t[r-1]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!R_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(yd[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(F_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&yd[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function T_(t){return al(String(t??"")).error}function _d(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 M_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],$_="MAGIC_LINK_SENT",L_="PLUS_ALIAS_REJECTED",N_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",eo={allowlistedDomains:M_,successCode:$_,validationCode:L_,messageTemplate:N_},O_=new Set(eo.allowlistedDomains),B_=eo.successCode,D_=eo.validationCode;function to(t){return typeof t=="string"?t.trim():""}function j_(t){const e=to(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 O_.has(r)?i.includes("+"):!1}function U_(t,e){return eo.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function Zh(t){if(!j_(t))return null;const e=to(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return U_(e,i)}function nc(t){return!t||typeof t!="object"||Array.isArray(t)||t.success===!1||t.error?!1:t.code?t.code===B_:t.success===!0||typeof t.message=="string"}function Xh(t,e){return t?.code===D_?t.message||Zh(e)||"Please enter your primary email address.":nc(t)?`Check your email — we sent a link to ${to(e)}`:t?.message||"Something went wrong. Please try again."}const H_="ccc_auth_session",W_="ccc_subscription",q_=Object.freeze(["hasSeenWalkthrough"]);function z_(t){const e=[];for(const n of q_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function V_(){return[H_,W_]}function G_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of V_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function K_(t){const e=t?.message||t?.error;return typeof e=="string"&&e.trim()?e.trim():"The server could not send the link."}function Y_({sendLink:t,getEmail:e,onState:n}){let i=!1;return async function(){if(i)return{status:"busy"};i=!0;let s;try{n({status:"pending",error:null});const o=await t(e());if(!nc(o))throw new Error(K_(o));return s={status:"sent",data:o},n({status:"sent",data:o}),s}catch(o){return s={status:"error",error:o},n({status:"error",error:o}),s}finally{i=!1}}}const J_=/^dependencies\s*:\s*(?:#.*)?$/,Z_=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Sr(t){const e=t.match(Z_);return e?e[1]??e[2]??e[3]:null}function xr(t){const e=t.trim();return e===""||e.startsWith("#")}function En(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function ic(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;sc&&/\s/.test(s[d-1]);)d-=1}return t[r]=s.slice(0,c)+sc(n)+s.slice(d),!0}return!1}function wd(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?sc(i):">=0.0.0"}`]}function t0(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(rp(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=rc(r);if(l){const u=o.flatMap(([c,d])=>wd(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(...wd(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function n0(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=no(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l),d=c&&!c.isScalar&&c.sourceKey===null&&c.version!==null;if(!c||!c.isScalar&&!d||!String(u||"").trim()){a.push(l);continue}if(d){e0(r,c,String(u).trim())?o.push({name:l,from:c.version,to:u}):a.push(l);continue}const f=" ".repeat(En(r[c.lineIndex]));r[c.lineIndex]=`${f}${l}: ${sc(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function op(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),rc(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),rp(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 i0=">=3.0.0 <4.0.0";function ll(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 r0(t=""){const e=Gh(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function bd(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=ll(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=ll(s.version);continue}i.push(r)}return i}function s0(t){const e=new Set,n=new Set,i={},r={},s=bd(no(t),i,e),o=bd(X_(t,"dependency_overrides"),r,n),a=[...s,...o],l=new Set([...Object.keys(i),...e]),{sdk:u}=sp(t);return{sdkConstraint:ll(u)||i0,dependencies:i,dependencyOverrides:r,sdkPackages:[...e].sort(),sdkOverrides:[...n].sort(),availablePackages:l,unrepresentable:a,unrepresentableOverrides:o}}function o0(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 a0(t,e){const{sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o,availablePackages:a,unrepresentable:l,unrepresentableOverrides:u}=s0(e),c={sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o},d=[],f=[],p=[];for(const h of t){const{className:g,content:m}=h,v=Ql(m),b=Gh(m).some(x=>x.startsWith("package:"));if(l.length>0&&b){const x=v.filter(T=>l.includes(T));let I;if(x.length>0)I=`${g} was not compiled before deploying: it imports or exports ${x.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`;else{const T=l.filter(P=>!u.includes(P)),S=[T.length>0?`your project's pubspec.yaml declares ${T.join(", ")} from a source that cannot be reproduced outside it`:null,u.length>0?`your project's dependency_overrides redirects ${u.join(", ")} to a source that cannot be reproduced outside it`:null].filter(Boolean).join(", and ");I=`${g} was not compiled before deploying: ${S}, and an entry like that can change what every package depending on it resolves to - including packages this class reaches transitively - so package resolution could not be matched exactly.`}f.push({className:g,reason:I});continue}const{unresolvableImports:w}=r0(m),_=v.filter(x=>!a.has(x));if(w.length>0||_.length>0){f.push({className:g,reason:o0(g,w,_)});continue}d.push({fileName:`${Xl(g)}.dart`,content:m})}return{manifest:c,sources:d,skipped:f,approximate:p}}function Ed(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=ap(s);o&&r.push(o)}return{events:r,buffer:i}}function l0(t){const e=ap(t);return e?[e]:[]}function ap(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 Ne=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),lp=84e4,cp=1e4;function up(t){return t?.unconfirmed===!0||t?.outcome===Ne.UNCONFIRMED?Ne.UNCONFIRMED:t?.partial===!0||t?.outcome===Ne.PARTIAL?Ne.PARTIAL:t?.success===!0?Ne.COMMITTED:Ne.FAILED}class We extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Ne.UNCONFIRMED}}function Sd({httpStatus:t}={}){return new We(`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 c0(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}if(u.event==="result"){r=u;return}u.event===void 0&&typeof u.success=="boolean"&&(r=u)};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const p=Ed(o,c.decode(f,{stream:!0}));o=p.buffer,p.events.forEach(a)}}else{const u=Ed("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return l0(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 u0=new Set(["connected","workspace_init","workspace_ready","verifying"]);function dp(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?u0.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function xd(t){if(t?.finalResultReceived){const e=up(t);return e===Ne.FAILED&&!dp(t)?Ne.UNCONFIRMED:e}return t?.httpRejected&&typeof t.httpStatus=="number"&&t.httpStatus>=400&&t.httpStatus<500?Ne.FAILED:Ne.UNCONFIRMED}function d0(){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,p,h,g,m,v;function b(V,z){if(!i)return null;const D=i.createShader(V);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const V=b(i.VERTEX_SHADER,o),z=b(i.FRAGMENT_SHADER,a());if(V&&z&&(l=i.createProgram(),i.attachShader(l,V),i.attachShader(l,z),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),p=i.getUniformLocation(l,"parallax"),h=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function w(V){if(!V)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(V);if(z){let D=z[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const he=D.getContext("2d");he.fillStyle="rgb(9, 8, 7)";const Pe=String(he.fillStyle);he.fillStyle=V;const Te=String(he.fillStyle);if(Te===Pe)return null;const mt=/^#([0-9a-f]{6})$/i.exec(Te);if(mt){const vt=mt[1];return[parseInt(vt.slice(0,2),16)/255,parseInt(vt.slice(2,4),16)/255,parseInt(vt.slice(4,6),16)/255]}const Wt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Te);if(Wt)return[Number(Wt[1])/255,Number(Wt[2])/255,Number(Wt[3])/255]}catch{}return null}function _(){let V="";try{const z=getComputedStyle(document.documentElement);V=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return w(V)||[.56,.68,.88]}const x=_();let I=1920,T=1080,S=960,P=540,R=960,L=540,$=.66,O=0,J=-1e9,G=!1,M=0,K=0,ie=null,B=!1,Z=!1,se=!1;const Ce=64,Q=15.2;let ue=0,ye=0;const je=.0032,St=0,_e=.56,et=.26,xt=.32,Cn=.16,Le=.349;let Re=St;function Dt(){const V=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!V.width||!z||!D)return;const he=Math.min(window.devicePixelRatio||1,2),Pe=Math.max(.2,Math.min(2,V.width/z*he)),Te=Math.max(2,Math.round(z*Pe)),mt=Math.max(2,Math.round(D*Pe));(Te!==t.width||mt!==t.height)&&(t.width=Te,t.height=mt,i&&i.viewport(0,0,Te,mt)),I=z,T=D,G||(S=R=I/2,P=L=T/2,G=!0)}function Zn(V){!l||!B||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,S,P),i.uniform1f(f,$),i.uniform1f(p,O),i.uniform2f(v,Math.cos(Re),Math.sin(Re)),i.uniform1f(h,V),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Ke(V,z,D){const he=Math.max(0,Math.min(1,(D-V)/(z-V)));return he*he*(3-2*he)}function Xn(V){if(!ie||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/I;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const he=Math.min(I,T),Pe=Math.max(64,Math.min(118,he/10)),Te=Pe*2.9,mt=2*Te*Te,Wt=Math.sin(V*.11)*7,vt=Math.cos(V*.09)*7-O,Mr=S+Wt,$r=P+vt,Fo=Te*Math.sqrt(2*Math.log(1/.06)),Fi=Fo+je*Fo*Fo+Pe,xg=Math.floor((Mr-Fi)/Pe)-1,Ig=Math.ceil((Mr+Fi)/Pe)+1,kg=Math.floor(($r-Fi)/Pe)-1,Cg=Math.ceil(($r+Fi)/Pe)+1;for(let Ro=kg;Ro<=Cg;Ro++){const Pg=(Ro+.5)*Pe;for(let To=xg;To<=Ig;To++){const Mo=(To+.5)*Pe-Mr,$o=Pg-$r,Lo=Math.sqrt(Mo*Mo+$o*$o)+1e-5;if(Lo>Fi)continue;const Lr=(-1+Math.sqrt(1+4*je*Lo))/(2*je),qc=Math.exp(-(Lr*Lr)/mt),zc=Ke(.06,.8,qc)*$*.26;if(zc<.004)continue;const gn=Pe/(1+2*je*Lr)*.26*(.32+1.1*qc),Vc=Lr/Lo,No=Mr+Mo*Vc,Oo=$r+$o*Vc;No<-gn*1.6||No>I+gn*1.6||Oo<-gn*1.6||Oo>T+gn*1.6||(z.globalAlpha=zc,z.save(),z.translate(No,Oo),z.rotate(Re),z.drawImage(ie,-gn,-gn,gn*2,gn*2),z.restore())}}z.globalAlpha=1}function jt(V){if(!Z)return;const z=K?Math.min(.05,(V-K)/1e3):.016;K=V;const he=V-J>2400?.6:1;$+=(he-$)*Math.min(1,z*3.2);const Pe=Math.min(.05,z);ue+=((R-S)*Ce-ue*Q)*Pe,ye+=((L-P)*Ce-ye*Q)*Pe,S+=ue*Pe,P+=ye*Pe,O=(window.scrollY||window.pageYOffset||0)*.55;const Te=V/1e3,mt=S/(I||1)-.5,Wt=P/(T||1)-.5;let vt=mt*(mt>=0?_e:et)+Wt*(Wt>=0?xt:Cn);vt>Le?vt=Le:vt<-Le&&(vt=-Le),Re=St+vt-O*6e-4,Dt(),i?Zn(Te):Xn(Te),M=requestAnimationFrame(jt)}function Ut(V){if(!Z)return;const z=t.getBoundingClientRect();!z.width||!I||!T||(R=(V.clientX-z.left)/z.width*I,L=(V.clientY-z.top)/z.height*T,J=performance.now())}function ut(){Z||Ao||e.matches||n.matches||!se||document.hidden||(Z=!0,K=0,M=requestAnimationFrame(jt))}function Ht(){Z=!1,M&&(cancelAnimationFrame(M),M=0),K=0}function Ai(){e.matches?(Ht(),t.classList.remove("is-ready")):se&&ut()}function Qn(){n.matches?Ht():se&&ut()}function Uc(){document.hidden?Ht():se&&ut()}const Hc=new IntersectionObserver(V=>{se=V[0]?.isIntersecting||!1,se?ut():Ht()},{threshold:0});Hc.observe(t),window.addEventListener("pointermove",Ut,{passive:!0,capture:!0}),window.addEventListener("resize",Dt),e.addEventListener("change",Ai),n.addEventListener("change",Qn),document.addEventListener("visibilitychange",Uc);function Sg(){const V=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(V&&window.Path2D){const he=Math.min(8.533333333333333,8.421052631578947);D.setTransform(he,0,0,he,he+(256-30*he)/2,-6.4*he),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(V),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const he=D.getImageData(0,0,256,256),Pe=he.data;for(let Te=3;Te{V.persisted?Ht():Wc()}),window.addEventListener("pageshow",V=>{V.persisted&&ut()}),{dispose:Wc,isRunning:()=>Z}}const h0=120;function p0(t,e,n){return tn?n:t}function pe(t,e,n){return p0((t-e)/(n-e),0,1)}function g0(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function pa(t){return 1-Math.pow(1-t,3)}function Ye(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 kd(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function re(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(pe(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=re(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),h=re(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ye}]),d=re(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ye},{t:10.6,v:0}]),p=re(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ye}]),o=re(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=re(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=pe(_,.45,2.2);a=x>0?-2.6*(1-kd(x)):0,g=re(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=pe(_,.67,2.42);f=I>0?-2.6*(1-kd(I)):0,s=1-.05*(Math.sin(pe(_,1.9,2.5)*Math.PI)+Math.sin(pe(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[re(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}]),re(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 w=x;const _=t-60,I=1-pe(_,12,14),T=x(pe(_,0,12)),S=x(pe(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(S[0]-T[0])*.6*I,a=(S[1]-T[1])*.6*I,p=(S[0]-T[0])*30*I,b=pe(_,0,.4)*I}else if(t<85.4){const _=t-74,x=re(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ye},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=re(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ye},{t:11.4,v:0}]),p=-l*.7,a=re(_,[{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=pe(_,0,5.6),I=pe(_,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,p=x*360*(1-I);const S=re(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:pa},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*S,d+=.16*S,l=-6*S,p+=6*S,s=1+.05*S,m=1+.9*S}else if(t<108.6){const _=t-96.4,x=pe(_,9.6,12.2);n=re(_,[{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(pe(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,h=1-.12*I,l=I*8,p=-I*8,o=.06*I,d=-.06*I,b=pe(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(pe(_,0,8)*Math.PI),I=1-pe(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(pe(_,0,6)*Math.PI),v=1+.1*Math.sin(pe(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=b,e}function m0(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=h0;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function p(M){const K=Math.min(1,Math.max(0,M.x))*c,ie=M.y*d;n.style.transform="translate3d("+K.toFixed(2)+"px,"+ie.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("+K.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,b=!1,w=!1,_=0;function x(){return w||a.matches||document.hidden||!e.offsetParent?!1:b}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){S();return}const K=g?(M-g)/1e3:0;g=M,h=(h+Math.min(K,.1))%l,_+=1,p(Hi(h))}function T(){v||w||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function S(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():S()}function R(){a.matches?(S(),p(Hi(0))):P()}function L(){f(),v&&p(Hi(h))}function $(){g=0,P()}const O=new IntersectionObserver(M=>{b=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});O.observe(e),window.addEventListener("resize",L),a.addEventListener("change",R),document.addEventListener("visibilitychange",$);function J(){w||(w=!0,S(),O.disconnect(),window.removeEventListener("resize",L),a.removeEventListener("change",R),document.removeEventListener("visibilitychange",$))}window.addEventListener("pagehide",M=>{M.persisted?S():J()}),window.addEventListener("pageshow",M=>{M.persisted&&P()});function G(M){h=(M%l+l)%l,p(Hi(h))}return f(),p(Hi(0)),P(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:G,dispose:J}}const v0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ln(t){const e=String(t||"").trim().match(v0);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function y0(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 w0(t){const e=ln(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ac(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 ln(o)?{min:o,minInclusive:!0,max:w0(o),maxInclusive:!1}:null}if(ln(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(!ln(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Cd(t,e){const n=ac(t);if(!n||!ln(e))return!1;if(n.min!==null){const i=Ls(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=Ls(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function b0(t,e){const n=ac(t);if(!n||!ln(e))return!1;if(n.max===null)return!0;const i=Ls(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ri(t){const e=ac(t);return e?e.min:null}const E0="https://pub.dev/api/packages/",S0=8e3;function x0(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||_0(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Cd(l.sdk,n)||i&&l.flutter&&!Cd(l.flutter,i)||(!s||Ls(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function I0(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${E0}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(S0)});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=x0(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 k0(t,e={}){const n=await Promise.all(t.map(i=>I0(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function C0(t,e={},n={}){const{resolveVersions:i=k0}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=lp(t),o={dartSdkFloor:ri(s.sdk),flutterSdkFloor:ri(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=io(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(Wy.has(d)?c:u).push(d);continue}const h=ri(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:d,constraint:p.constraint});continue}if(b0(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(ri(h)){a.additions[f]=`^${ri(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${ri(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const P0={"&":"&","<":"<",">":">",'"':""","'":"'"};function cn(t){return String(t??"").replace(/[&<>"']/g,e=>P0[e])}function W(t){return t?cn(t).replace(/\n/g,"
    "):""}function on(t){return cn(t).replace(/\r?\n/g," ")}function ro(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 mp(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 A0(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 F0(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 R0(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 Si(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 Pd(t){return t=cn(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 vp(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=Si(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 cn(i)}}}function so(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=R0(o),u=vp(o.trim(),l,n);i+=`
    +`)}let l=null,u,c,d,f,p,h,g,m,v;function b(V,z){if(!i)return null;const D=i.createShader(V);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const V=b(i.VERTEX_SHADER,o),z=b(i.FRAGMENT_SHADER,a());if(V&&z&&(l=i.createProgram(),i.attachShader(l,V),i.attachShader(l,z),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),p=i.getUniformLocation(l,"parallax"),h=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function w(V){if(!V)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(V);if(z){let D=z[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const he=D.getContext("2d");he.fillStyle="rgb(9, 8, 7)";const Pe=String(he.fillStyle);he.fillStyle=V;const Te=String(he.fillStyle);if(Te===Pe)return null;const mt=/^#([0-9a-f]{6})$/i.exec(Te);if(mt){const vt=mt[1];return[parseInt(vt.slice(0,2),16)/255,parseInt(vt.slice(2,4),16)/255,parseInt(vt.slice(4,6),16)/255]}const Wt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Te);if(Wt)return[Number(Wt[1])/255,Number(Wt[2])/255,Number(Wt[3])/255]}catch{}return null}function _(){let V="";try{const z=getComputedStyle(document.documentElement);V=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return w(V)||[.56,.68,.88]}const x=_();let I=1920,T=1080,S=960,P=540,R=960,L=540,$=.66,O=0,J=-1e9,G=!1,M=0,K=0,ie=null,B=!1,Z=!1,se=!1;const Ce=64,Q=15.2;let ue=0,ye=0;const je=.0032,xt=0,_e=.56,et=.26,It=.32,Cn=.16,Le=.349;let Re=xt;function Dt(){const V=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!V.width||!z||!D)return;const he=Math.min(window.devicePixelRatio||1,2),Pe=Math.max(.2,Math.min(2,V.width/z*he)),Te=Math.max(2,Math.round(z*Pe)),mt=Math.max(2,Math.round(D*Pe));(Te!==t.width||mt!==t.height)&&(t.width=Te,t.height=mt,i&&i.viewport(0,0,Te,mt)),I=z,T=D,G||(S=R=I/2,P=L=T/2,G=!0)}function Jn(V){!l||!B||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,S,P),i.uniform1f(f,$),i.uniform1f(p,O),i.uniform2f(v,Math.cos(Re),Math.sin(Re)),i.uniform1f(h,V),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Ke(V,z,D){const he=Math.max(0,Math.min(1,(D-V)/(z-V)));return he*he*(3-2*he)}function Zn(V){if(!ie||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/I;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const he=Math.min(I,T),Pe=Math.max(64,Math.min(118,he/10)),Te=Pe*2.9,mt=2*Te*Te,Wt=Math.sin(V*.11)*7,vt=Math.cos(V*.09)*7-O,Tr=S+Wt,Mr=P+vt,Ao=Te*Math.sqrt(2*Math.log(1/.06)),Ai=Ao+je*Ao*Ao+Pe,Sg=Math.floor((Tr-Ai)/Pe)-1,xg=Math.ceil((Tr+Ai)/Pe)+1,Ig=Math.floor((Mr-Ai)/Pe)-1,kg=Math.ceil((Mr+Ai)/Pe)+1;for(let Fo=Ig;Fo<=kg;Fo++){const Cg=(Fo+.5)*Pe;for(let Ro=Sg;Ro<=xg;Ro++){const To=(Ro+.5)*Pe-Tr,Mo=Cg-Mr,$o=Math.sqrt(To*To+Mo*Mo)+1e-5;if($o>Ai)continue;const $r=(-1+Math.sqrt(1+4*je*$o))/(2*je),Wc=Math.exp(-($r*$r)/mt),qc=Ke(.06,.8,Wc)*$*.26;if(qc<.004)continue;const gn=Pe/(1+2*je*$r)*.26*(.32+1.1*Wc),zc=$r/$o,Lo=Tr+To*zc,No=Mr+Mo*zc;Lo<-gn*1.6||Lo>I+gn*1.6||No<-gn*1.6||No>T+gn*1.6||(z.globalAlpha=qc,z.save(),z.translate(Lo,No),z.rotate(Re),z.drawImage(ie,-gn,-gn,gn*2,gn*2),z.restore())}}z.globalAlpha=1}function jt(V){if(!Z)return;const z=K?Math.min(.05,(V-K)/1e3):.016;K=V;const he=V-J>2400?.6:1;$+=(he-$)*Math.min(1,z*3.2);const Pe=Math.min(.05,z);ue+=((R-S)*Ce-ue*Q)*Pe,ye+=((L-P)*Ce-ye*Q)*Pe,S+=ue*Pe,P+=ye*Pe,O=(window.scrollY||window.pageYOffset||0)*.55;const Te=V/1e3,mt=S/(I||1)-.5,Wt=P/(T||1)-.5;let vt=mt*(mt>=0?_e:et)+Wt*(Wt>=0?It:Cn);vt>Le?vt=Le:vt<-Le&&(vt=-Le),Re=xt+vt-O*6e-4,Dt(),i?Jn(Te):Zn(Te),M=requestAnimationFrame(jt)}function Ut(V){if(!Z)return;const z=t.getBoundingClientRect();!z.width||!I||!T||(R=(V.clientX-z.left)/z.width*I,L=(V.clientY-z.top)/z.height*T,J=performance.now())}function ut(){Z||Po||e.matches||n.matches||!se||document.hidden||(Z=!0,K=0,M=requestAnimationFrame(jt))}function Ht(){Z=!1,M&&(cancelAnimationFrame(M),M=0),K=0}function Pi(){e.matches?(Ht(),t.classList.remove("is-ready")):se&&ut()}function Xn(){n.matches?Ht():se&&ut()}function jc(){document.hidden?Ht():se&&ut()}const Uc=new IntersectionObserver(V=>{se=V[0]?.isIntersecting||!1,se?ut():Ht()},{threshold:0});Uc.observe(t),window.addEventListener("pointermove",Ut,{passive:!0,capture:!0}),window.addEventListener("resize",Dt),e.addEventListener("change",Pi),n.addEventListener("change",Xn),document.addEventListener("visibilitychange",jc);function Eg(){const V=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(V&&window.Path2D){const he=Math.min(8.533333333333333,8.421052631578947);D.setTransform(he,0,0,he,he+(256-30*he)/2,-6.4*he),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(V),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const he=D.getImageData(0,0,256,256),Pe=he.data;for(let Te=3;Te{V.persisted?Ht():Hc()}),window.addEventListener("pageshow",V=>{V.persisted&&ut()}),{dispose:Hc,isRunning:()=>Z}}const f0=120;function h0(t,e,n){return tn?n:t}function pe(t,e,n){return h0((t-e)/(n-e),0,1)}function p0(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function ha(t){return 1-Math.pow(1-t,3)}function Ye(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 Id(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function re(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(pe(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=re(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),h=re(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ye}]),d=re(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ye},{t:10.6,v:0}]),p=re(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ye}]),o=re(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=re(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=pe(_,.45,2.2);a=x>0?-2.6*(1-Id(x)):0,g=re(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=pe(_,.67,2.42);f=I>0?-2.6*(1-Id(I)):0,s=1-.05*(Math.sin(pe(_,1.9,2.5)*Math.PI)+Math.sin(pe(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[re(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}]),re(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 w=x;const _=t-60,I=1-pe(_,12,14),T=x(pe(_,0,12)),S=x(pe(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(S[0]-T[0])*.6*I,a=(S[1]-T[1])*.6*I,p=(S[0]-T[0])*30*I,b=pe(_,0,.4)*I}else if(t<85.4){const _=t-74,x=re(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ye},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=re(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ye},{t:11.4,v:0}]),p=-l*.7,a=re(_,[{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=pe(_,0,5.6),I=pe(_,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,p=x*360*(1-I);const S=re(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:ha},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*S,d+=.16*S,l=-6*S,p+=6*S,s=1+.05*S,m=1+.9*S}else if(t<108.6){const _=t-96.4,x=pe(_,9.6,12.2);n=re(_,[{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(pe(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,h=1-.12*I,l=I*8,p=-I*8,o=.06*I,d=-.06*I,b=pe(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(pe(_,0,8)*Math.PI),I=1-pe(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(pe(_,0,6)*Math.PI),v=1+.1*Math.sin(pe(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=b,e}function g0(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=f0;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function p(M){const K=Math.min(1,Math.max(0,M.x))*c,ie=M.y*d;n.style.transform="translate3d("+K.toFixed(2)+"px,"+ie.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("+K.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,b=!1,w=!1,_=0;function x(){return w||a.matches||document.hidden||!e.offsetParent?!1:b}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){S();return}const K=g?(M-g)/1e3:0;g=M,h=(h+Math.min(K,.1))%l,_+=1,p(Ui(h))}function T(){v||w||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function S(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():S()}function R(){a.matches?(S(),p(Ui(0))):P()}function L(){f(),v&&p(Ui(h))}function $(){g=0,P()}const O=new IntersectionObserver(M=>{b=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});O.observe(e),window.addEventListener("resize",L),a.addEventListener("change",R),document.addEventListener("visibilitychange",$);function J(){w||(w=!0,S(),O.disconnect(),window.removeEventListener("resize",L),a.removeEventListener("change",R),document.removeEventListener("visibilitychange",$))}window.addEventListener("pagehide",M=>{M.persisted?S():J()}),window.addEventListener("pageshow",M=>{M.persisted&&P()});function G(M){h=(M%l+l)%l,p(Ui(h))}return f(),p(Ui(0)),P(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:G,dispose:J}}const m0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ln(t){const e=String(t||"").trim().match(m0);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function v0(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 _0(t){const e=ln(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function oc(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 ln(o)?{min:o,minInclusive:!0,max:_0(o),maxInclusive:!1}:null}if(ln(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(!ln(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function kd(t,e){const n=oc(t);if(!n||!ln(e))return!1;if(n.min!==null){const i=$s(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=$s(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function w0(t,e){const n=oc(t);if(!n||!ln(e))return!1;if(n.max===null)return!0;const i=$s(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ii(t){const e=oc(t);return e?e.min:null}const b0="https://pub.dev/api/packages/",E0=8e3;function S0(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||y0(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!kd(l.sdk,n)||i&&l.flutter&&!kd(l.flutter,i)||(!s||$s(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function x0(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${b0}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(E0)});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=S0(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 I0(t,e={}){const n=await Promise.all(t.map(i=>x0(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function k0(t,e={},n={}){const{resolveVersions:i=I0}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=sp(t),o={dartSdkFloor:ii(s.sdk),flutterSdkFloor:ii(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=no(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(Hy.has(d)?c:u).push(d);continue}const h=ii(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:d,constraint:p.constraint});continue}if(w0(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(ii(h)){a.additions[f]=`^${ii(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${ii(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const C0={"&":"&","<":"<",">":">",'"':""","'":"'"};function cn(t){return String(t??"").replace(/[&<>"']/g,e=>C0[e])}function W(t){return t?cn(t).replace(/\n/g,"
    "):""}function on(t){return cn(t).replace(/\r?\n/g," ")}function io(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 hp(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 P0(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 A0(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 F0(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 Ei(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 Cd(t){return t=cn(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 pp(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=Ei(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 cn(i)}}}function ro(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=F0(o),u=pp(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+=`

    - ${A0(l)} + ${P0(l)} ${cn(l)}

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

    - ${F0(l)} + ${A0(l)} ${cn(l)}

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

    ${Pd(a)}

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

    ${Cd(a)}

    `)}return i+="
    ",`
    @@ -81,14 +81,14 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
    ${i}
    - `}const T0=5200,M0=73,$0=1600,L0=35,ga=new WeakMap;function Ad(t,e){return!!(t&&t.trim())&&!e}function N0({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=Array.from(document.querySelectorAll("#example-chips .chip")),o=document.getElementById("btn-add-images"),a=document.getElementById("prompt-image-input"),l=window.matchMedia("(prefers-reduced-motion: reduce)");let u=!1,c=!1,d=!1,f=!1,p=!1,h=null,g=null;const m=n.dataset.demoPrompt||"";function v(){return c||d||f||p}function b(){i.disabled=!Ad(n.value,v())}function w(){r&&(r.textContent=n.value)}function _(B){c=B,e.classList.toggle("is-busy",B),i.classList.toggle("is-busy",B),i.setAttribute("aria-label",B?"Generating":"Generate"),n.readOnly=B,s.forEach(Z=>{Z.disabled=B}),o&&(o.disabled=B),a&&(a.disabled=B),b()}async function x(){if(Ad(n.value,v())){_(!0);try{await t()}finally{_(!1)}}}function I(){f&&(f=!1,g&&(clearTimeout(g),g=null),e.classList.remove("is-demo-typing","is-demo-keying"),n.placeholder="Describe the widget or action you need",b())}function T(){if(l.matches||!m.trim())return;const B=window.location.hash.replace(/^#/,"");if(B&&B!=="home")return;f=!0,n.placeholder="",n.value="",w(),b(),e.classList.add("is-demo-typing");let Z=0;const se=(ue,ye)=>{Z+=ue,n.value=m.slice(0,Z),w(),e.classList.toggle("is-demo-keying",ye)},Ce=()=>{f&&(se(-1,!0),Z>0?g=setTimeout(Ce,L0):I())},Q=()=>{if(!f)return;const ue=Z+1B.classList.contains("is-active"))?.dataset.prompt||n.value,w(),R())}function $(){s.forEach(B=>{B.classList.remove("is-active"),B.setAttribute("aria-pressed","false")})}function O(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function J(B){const Z=B.dataset.prompt||"";if(I(),R(),s.forEach(Ce=>{const Q=Ce===B;Ce.classList.toggle("is-active",Q),Ce.setAttribute("aria-pressed",String(Q))}),l.matches||!Z){n.value=Z,w(),b(),O();return}n.value="",w(),d=!0,b(),e.classList.add("is-demo-typing","is-demo-keying");let se=0;h=setInterval(()=>{se+=1,n.value=Z.slice(0,se),w(),se>=Z.length?(R(),O()):b()},22)}s.forEach(B=>{B.setAttribute("aria-pressed","false"),B.addEventListener("click",()=>J(B))}),n.addEventListener("keydown",B=>{if((f||d)&&B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u){B.preventDefault();return}S(),L(),B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u&&(B.preventDefault(),x())}),n.addEventListener("beforeinput",()=>S()),n.addEventListener("input",()=>{I(),R(),$(),w(),b()}),n.addEventListener("compositionstart",()=>{u=!0}),n.addEventListener("compositionend",()=>{u=!1,b()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),i.addEventListener("click",x),n.addEventListener("pointerdown",()=>{S(),L(),$()}),n.addEventListener("focus",()=>S());const G=ga.get(e);G&&G.mql.removeEventListener("change",G.handler),l.addEventListener("change",P),ga.set(e,{mql:l,handler:P});function M(){K(),l.removeEventListener("change",P),ga.delete(e),document.removeEventListener("visibilitychange",ie)}function K(){S(),L()}function ie(){document.hidden&&K()}return document.addEventListener("visibilitychange",ie),w(),b(),T(),{setAttachmentsPending(B){p=!!B,b()},dispose:M,cancelTyping:K}}const mr=window.matchMedia("(prefers-reduced-motion: reduce)");let fi=null,Jt=null;const Ns=new Map;function yp(){for(const[t,e]of Ns)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Ns.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Gn(){if(yp(),fi){const t=fi;fi=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Jt&&(Jt.animation.cancel(),Jt.hero.classList.remove("is-exiting"),Jt.hero.style.cssText=Jt.style,Jt=null)}function O0(t){return(fi?.ghost||t)?.getBoundingClientRect()}function B0(t){yp(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",mr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Ns.delete(e))}Ns.set(e,i),e.addEventListener("animationend",i)})}function D0(t,e){if(!t||!e||mr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Jt={hero:t,animation:i,style:n},i.onfinish=()=>{Jt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Jt=null)}}function _p(t,e,n,{results:i=!1}={}){if(Gn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,B0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(mr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};fi=h,p.onfinish=()=>{fi===h&&(Gn(),s())}}window.addEventListener("resize",Gn);window.addEventListener("pagehide",Gn);document.addEventListener("visibilitychange",()=>{document.hidden&&Gn()});mr.addEventListener("change",()=>{mr.matches&&Gn()});const Fd="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",j0="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",U0="https://us.i.posthog.com";Nh.init(j0,{api_host:U0,person_profiles:"identified_only"});function Dn(t,e={}){try{Nh.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const Et="https://4tgke4.buildship.run",wp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Os="ccc_auth_session",ul="ccc_signin_return",H0=1800*1e3,Rd=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=Kn({isResolved:!0}),dl=Promise.resolve();const W0=`${Et}/service/runpipeline`,q0="bs_user_id",z0="bs_identity_token",V0=`${Et}/authUserCheck`;let yt={userId:null,token:null,status:null,resolved:!1};const Bs=ry,Ds="ccc_subscription",Td=3,G0=new Set(["active","trialing","paid"]),js="google/gemini-3.7-flash",rs=["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"],K0={"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 nn(t){return K0[t]||t}const Y0=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 bp(t){return Y0.has(t)}const fl=4,ma=8*1024*1024,J0="https://4tgke4.buildship.run/service/runpipeline-image";let De=[];const Sn=[],Z0=3e4;let lc=null;function X0(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function Q0(t,e){const n=new FormData;return n.append("file",t),(await fetch(J0,{method:"POST",body:n,signal:e})).json()}function ew(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 tw(t,e,n){const i=await X0(t,n);i&&De.includes(e)&&(e.dataUrl=i,yn());let r="";if(i)try{r=ew(await Q0(t,n))}catch{r=""}return De.includes(e)?!i||!r?(De.splice(De.indexOf(e),1),yn(),"failed"):(e.url=r,yn(),"added"):"dropped"}function Ep(t){const e=Sn.indexOf(t);e>=0&&Sn.splice(e,1),xp()}function Sp(t){t.controller.abort(),Ep(t);const e=De.indexOf(t.slot);e>=0&&(De.splice(e,1),yn())}function xp(){lc?.setAttachmentsPending(Sn.length>0)}async function nw(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Se("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>ma);n.length&&Se(`Skipped ${n.length} image(s) over the ${(ma/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ma);if(!i.length)return;const r=fl-De.length,s=i.slice(0,r);if(i.length>r&&Se(`You can attach up to ${fl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};De.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Z0);return d.job=tw(u,c,d.controller.signal),Sn.push(d),d.job.finally(()=>{clearTimeout(f),Ep(d)}),d.job});yn(),xp();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Se(`${l} image(s) could not be uploaded and were not attached.`,"error")}function iw(t){if(y.isRunning){Se("Wait for the current generation to finish before removing images.","info");return}const e=De[t],n=Sn.find(i=>i.slot===e);if(n){Sp(n);return}De.splice(t,1),yn()}function yn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",De.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=De.length>=fl?"Image limit reached":"Add images"))}function cc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=bp(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(Sp),De=[],yn())}const Wn="ccc_usage",Ip="google/gemini-3.7-flash",kp="google/gemini-3.7-flash",Kr="google/gemini-3.7-flash",Ji={professional:11,power:49},hl={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"},ss={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 os={...ss};async function rw(){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(ss),...Object.values(pl),...Object.values(hl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:ss[a]&&(s[a]=ss[a]));os=s}catch{}finally{clearTimeout(e)}}const pl={"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 uc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&pl[s])return pl[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=hl[e];if(n)return n;const i=e.split("_")[0],r=hl[i];return r||"USD"}function Zi(t,e){const n=os[e]??os.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*os.USD)}}const _t="ccc_api_key_",Tt="ccc_session_api_key_",Nt="ccc_encryption_key",vr="ccc_encryption_key_scope",sw="ccc_keystore",Us="keys",yr="ccc_encryption_key_version";let gl=null,Hs=null,_r=!1,Ws=!1,Md=!1;class qs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function $d(){if(Md)return;Md=!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&&Se(t,"warning")}function Cp(){return localStorage.getItem(yr)||""}function ml(){return crypto.randomUUID?.()||Ap(crypto.getRandomValues(new Uint8Array(16)))}function ow(){const t=Cp();if(t)return t;const e=ml();return localStorage.setItem(yr,e),e}function xi(){gl=null,Hs=null,_r=!1,Ws=!1}window.addEventListener("storage",t=>{t.key===yr&&xi()});function aw(){return new Promise((t,e)=>{const n=indexedDB.open(sw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Us)||i.createObjectStore(Us)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function dc(t,e){const n=await aw();return new Promise((i,r)=>{const s=n.transaction(Us,t);let o;try{o=e(s.objectStore(Us))}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 lw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function cw(){const t=await dc("readonly",e=>e.get(Nt));return lw(t)?t:null}async function Pp(t){await dc("readwrite",e=>e.put(t,Nt))}async function uw(){xi();try{await dc("readwrite",t=>t.delete(Nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function dw(){const t=sessionStorage.getItem(Nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(e),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),e}async function Ld(t){const e=sessionStorage.getItem(Nt);if(e)return Ws=sessionStorage.getItem(vr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new qs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Nt,JSON.stringify(i)),sessionStorage.setItem(vr,"session"),Ws=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function fw(t){if(sessionStorage.getItem(vr)==="session"&&sessionStorage.getItem(Nt))return $d(),_r=!0,Ld(t);try{const e=await cw();if(e)return e;const n=await dw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),$d(),_r=!0,Ld(t)}}async function fc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=ow();Hs!==n&&xi();const i=gl||fw(e);gl=i,Hs=n;try{return await i}catch(r){throw xi(),r}}async function hw(t){const e=await fc(),n=Hs,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:Ap(o),keyVersion:n,sessionFallback:_r}}async function pw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await fc({allowSessionFallbackCreation:!1});if(_r&&!n&&!Ws)throw new qs;const r=gw(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 qs)throw i;return console.error("Decryption failed:",i),null}}function Ap(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let ke="",Mt="",sr=null,Od=0,ot="not-configured",gt=0,vl=0,yl=0,oo=0,Zt=0,un=0,Ze=null,$t=null,wr=null;function vw(){return vl+=1,vl}function yw(){return yl+=1,yl}function br(t,e,n){Ze=t?{projectId:t,key:e,generation:n}:null}function _l(t,e=ke){if(!t)return!1;const n=Ze;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function hc(t,e,n){if(!Mt||Ze&&Ze.projectId!==Mt)return;(t||[]).some(r=>(r.id||r.projectId)===Mt)?br(Mt,e,n):Ze&&br("",null,null)}function Fp({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===ke||r===ke}async function pc(){sessionStorage.getItem(Nt)&&await fc(),ke=await Me("flutterflow"),Mt=await Me("flutterflow_project_id"),xw(),pn(),ke?yc():(ot="not-configured",bt())}let Er=!1;function Rp(){const t=document.getElementById("api-keys-modal");Ve(t),vc(),ke&&co(ke)}function gc(){Er=!1,Rp()}function _w(){Er=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Rp()}let Bd=!1;function Dd(){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 jd(){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=nn(t.value),r=bp(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.`),cc()}function Tp(){if(Er=!1,Dd(),jd(),!Bd){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")),Dd(),jd()}),Bd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function ww(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Mp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=Er;if(Er=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&mc(),Ve(i))}}let dn=1;function $p(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function ao(){const t=$p();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,ao())}function bw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,ao(),Ve(t))}function Ew(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Lp(){if(H.isVerified&&Ot()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,ao(),Ve(e))}}async function vc(){const t=document.getElementById("flutterflow-api-key-input");ke?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Sw()}function Sw(){Ud("flutterflow","flutterflow-key-status"),Ud("flutterflow_project_id","flutterflow-project-status")}function Ud(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ft(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function xw(){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"?Ft("flutterflow")&&Ft("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ft("flutterflow")||Ft("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)"):Ft(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)")}),pn()}async function Iw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==ke,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await Nd("flutterflow",n),n!==l&&!r&&as()}const s=n||ke;if(r){if(!lo(r)){Se("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}_l(r,s)?await Nd("flutterflow_project_id",r):(i?as():Ze=null,e.value="",s&&!($t&&$t.key===s&&$t.generation===gt)&&co(s))}else i&&as();await pc(),n&&await yc(),vc();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Mp()},1e3)}async function kw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(yr,ml()),xi(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),await uw(),localStorage.setItem(yr,ml()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),Ze=null,$t=null,wr=null,await pc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),vc()}function lo(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Mt||"—"),!e)return;let r,s;if(!Ft("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 yc(){const t=yw(),e=++oo,n=gt,i=ke,r=await Me("flutterflow"),s=()=>Fp({seq:t,currentSeq:yl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Ft("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&hc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function as(){Mt="",Ze=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow_project_id")}function Cw(){gt+=1,$t=null,wr=null,as();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ft("flutterflow")?(ot="validating",co(ke)):ot="not-configured",bt()}function Pw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Aw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Pw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Fw(async n=>{const i=n.target.value.trim();i&&await co(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&$t?br(n,$t.key,$t.generation):br("",null,null)})}function Fw(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function co(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=vw(),r=++oo,s=gt,o=ke,a=()=>Fp({seq:i,currentSeq:vl,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};$t=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===ke&&(Ft("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;$t={key:t,generation:s};const f=t===ke,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,hc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Mt&&(e.value=Mt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===ke&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Rw(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const R0=5200,T0=73,M0=1600,$0=35,pa=new WeakMap;function Pd(t,e){return!!(t&&t.trim())&&!e}function L0({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=Array.from(document.querySelectorAll("#example-chips .chip")),o=document.getElementById("btn-add-images"),a=document.getElementById("prompt-image-input"),l=window.matchMedia("(prefers-reduced-motion: reduce)");let u=!1,c=!1,d=!1,f=!1,p=!1,h=null,g=null;const m=n.dataset.demoPrompt||"";function v(){return c||d||f||p}function b(){i.disabled=!Pd(n.value,v())}function w(){r&&(r.textContent=n.value)}function _(B){c=B,e.classList.toggle("is-busy",B),i.classList.toggle("is-busy",B),i.setAttribute("aria-label",B?"Generating":"Generate"),n.readOnly=B,s.forEach(Z=>{Z.disabled=B}),o&&(o.disabled=B),a&&(a.disabled=B),b()}async function x(){if(Pd(n.value,v())){_(!0);try{await t()}finally{_(!1)}}}function I(){f&&(f=!1,g&&(clearTimeout(g),g=null),e.classList.remove("is-demo-typing","is-demo-keying"),n.placeholder="Describe the widget or action you need",b())}function T(){if(l.matches||!m.trim())return;const B=window.location.hash.replace(/^#/,"");if(B&&B!=="home")return;f=!0,n.placeholder="",n.value="",w(),b(),e.classList.add("is-demo-typing");let Z=0;const se=(ue,ye)=>{Z+=ue,n.value=m.slice(0,Z),w(),e.classList.toggle("is-demo-keying",ye)},Ce=()=>{f&&(se(-1,!0),Z>0?g=setTimeout(Ce,$0):I())},Q=()=>{if(!f)return;const ue=Z+1B.classList.contains("is-active"))?.dataset.prompt||n.value,w(),R())}function $(){s.forEach(B=>{B.classList.remove("is-active"),B.setAttribute("aria-pressed","false")})}function O(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function J(B){const Z=B.dataset.prompt||"";if(I(),R(),s.forEach(Ce=>{const Q=Ce===B;Ce.classList.toggle("is-active",Q),Ce.setAttribute("aria-pressed",String(Q))}),l.matches||!Z){n.value=Z,w(),b(),O();return}n.value="",w(),d=!0,b(),e.classList.add("is-demo-typing","is-demo-keying");let se=0;h=setInterval(()=>{se+=1,n.value=Z.slice(0,se),w(),se>=Z.length?(R(),O()):b()},22)}s.forEach(B=>{B.setAttribute("aria-pressed","false"),B.addEventListener("click",()=>J(B))}),n.addEventListener("keydown",B=>{if((f||d)&&B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u){B.preventDefault();return}S(),L(),B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u&&(B.preventDefault(),x())}),n.addEventListener("beforeinput",()=>S()),n.addEventListener("input",()=>{I(),R(),$(),w(),b()}),n.addEventListener("compositionstart",()=>{u=!0}),n.addEventListener("compositionend",()=>{u=!1,b()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),i.addEventListener("click",x),n.addEventListener("pointerdown",()=>{S(),L(),$()}),n.addEventListener("focus",()=>S());const G=pa.get(e);G&&G.mql.removeEventListener("change",G.handler),l.addEventListener("change",P),pa.set(e,{mql:l,handler:P});function M(){K(),l.removeEventListener("change",P),pa.delete(e),document.removeEventListener("visibilitychange",ie)}function K(){S(),L()}function ie(){document.hidden&&K()}return document.addEventListener("visibilitychange",ie),w(),b(),T(),{setAttachmentsPending(B){p=!!B,b()},dispose:M,cancelTyping:K}}const gr=window.matchMedia("(prefers-reduced-motion: reduce)");let di=null,Jt=null;const Ls=new Map;function gp(){for(const[t,e]of Ls)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Ls.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Vn(){if(gp(),di){const t=di;di=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Jt&&(Jt.animation.cancel(),Jt.hero.classList.remove("is-exiting"),Jt.hero.style.cssText=Jt.style,Jt=null)}function N0(t){return(di?.ghost||t)?.getBoundingClientRect()}function O0(t){gp(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",gr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Ls.delete(e))}Ls.set(e,i),e.addEventListener("animationend",i)})}function B0(t,e){if(!t||!e||gr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Jt={hero:t,animation:i,style:n},i.onfinish=()=>{Jt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Jt=null)}}function mp(t,e,n,{results:i=!1}={}){if(Vn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,O0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(gr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};di=h,p.onfinish=()=>{di===h&&(Vn(),s())}}window.addEventListener("resize",Vn);window.addEventListener("pagehide",Vn);document.addEventListener("visibilitychange",()=>{document.hidden&&Vn()});gr.addEventListener("change",()=>{gr.matches&&Vn()});const Ad="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses";const Et="https://4tgke4.buildship.run",vp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Ns="ccc_auth_session",cl="ccc_signin_return",D0=1800*1e3,Fd=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Gn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=Gn({isResolved:!0}),ul=Promise.resolve();const j0=`${Et}/service/runpipeline`,U0="bs_user_id",H0="bs_identity_token",W0=`${Et}/authUserCheck`;let yt={userId:null,token:null,status:null,resolved:!1};const Os=iy,Bs="ccc_subscription",Rd=3,q0=new Set(["active","trialing","paid"]),Ds="google/gemini-3.7-flash",is=["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"],z0={"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 nn(t){return z0[t]||t}const V0=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 yp(t){return V0.has(t)}const dl=4,ga=8*1024*1024,G0="https://4tgke4.buildship.run/service/runpipeline-image";let De=[];const Sn=[],K0=3e4;let ac=null;function Y0(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function J0(t,e){const n=new FormData;return n.append("file",t),(await fetch(G0,{method:"POST",body:n,signal:e})).json()}function Z0(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 X0(t,e,n){const i=await Y0(t,n);i&&De.includes(e)&&(e.dataUrl=i,yn());let r="";if(i)try{r=Z0(await J0(t,n))}catch{r=""}return De.includes(e)?!i||!r?(De.splice(De.indexOf(e),1),yn(),"failed"):(e.url=r,yn(),"added"):"dropped"}function _p(t){const e=Sn.indexOf(t);e>=0&&Sn.splice(e,1),bp()}function wp(t){t.controller.abort(),_p(t);const e=De.indexOf(t.slot);e>=0&&(De.splice(e,1),yn())}function bp(){ac?.setAttachmentsPending(Sn.length>0)}async function Q0(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Se("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>ga);n.length&&Se(`Skipped ${n.length} image(s) over the ${(ga/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ga);if(!i.length)return;const r=dl-De.length,s=i.slice(0,r);if(i.length>r&&Se(`You can attach up to ${dl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};De.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),K0);return d.job=X0(u,c,d.controller.signal),Sn.push(d),d.job.finally(()=>{clearTimeout(f),_p(d)}),d.job});yn(),bp();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Se(`${l} image(s) could not be uploaded and were not attached.`,"error")}function ew(t){if(y.isRunning){Se("Wait for the current generation to finish before removing images.","info");return}const e=De[t],n=Sn.find(i=>i.slot===e);if(n){wp(n);return}De.splice(t,1),yn()}function yn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",De.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=De.length>=dl?"Image limit reached":"Add images"))}function lc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=yp(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(wp),De=[],yn())}const Hn="ccc_usage",Ep="google/gemini-3.7-flash",Sp="google/gemini-3.7-flash",Gr="google/gemini-3.7-flash",Yi={professional:11,power:49},fl={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"},rs={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 ss={...rs};async function tw(){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(rs),...Object.values(hl),...Object.values(fl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:rs[a]&&(s[a]=rs[a]));ss=s}catch{}finally{clearTimeout(e)}}const hl={"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 cc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&hl[s])return hl[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=fl[e];if(n)return n;const i=e.split("_")[0],r=fl[i];return r||"USD"}function Ji(t,e){const n=ss[e]??ss.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*ss.USD)}}const _t="ccc_api_key_",Mt="ccc_session_api_key_",Ot="ccc_encryption_key",mr="ccc_encryption_key_scope",nw="ccc_keystore",js="keys",vr="ccc_encryption_key_version";let pl=null,Us=null,yr=!1,Hs=!1,Td=!1;class Ws extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Md(){if(Td)return;Td=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&Se(t,"warning")}function xp(){return localStorage.getItem(vr)||""}function gl(){return crypto.randomUUID?.()||kp(crypto.getRandomValues(new Uint8Array(16)))}function iw(){const t=xp();if(t)return t;const e=gl();return localStorage.setItem(vr,e),e}function Si(){pl=null,Us=null,yr=!1,Hs=!1}window.addEventListener("storage",t=>{t.key===vr&&Si()});function rw(){return new Promise((t,e)=>{const n=indexedDB.open(nw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(js)||i.createObjectStore(js)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function uc(t,e){const n=await rw();return new Promise((i,r)=>{const s=n.transaction(js,t);let o;try{o=e(s.objectStore(js))}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 sw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function ow(){const t=await uc("readonly",e=>e.get(Ot));return sw(t)?t:null}async function Ip(t){await uc("readwrite",e=>e.put(t,Ot))}async function aw(){Si();try{await uc("readwrite",t=>t.delete(Ot))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function lw(){const t=sessionStorage.getItem(Ot);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ip(e),sessionStorage.removeItem(Ot),sessionStorage.removeItem(mr),localStorage.removeItem(_t+"salt"),e}async function $d(t){const e=sessionStorage.getItem(Ot);if(e)return Hs=sessionStorage.getItem(mr)!=="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(Ot,JSON.stringify(i)),sessionStorage.setItem(mr,"session"),Hs=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function cw(t){if(sessionStorage.getItem(mr)==="session"&&sessionStorage.getItem(Ot))return Md(),yr=!0,$d(t);try{const e=await ow();if(e)return e;const n=await lw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Ip(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Md(),yr=!0,$d(t)}}async function dc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=iw();Us!==n&&Si();const i=pl||cw(e);pl=i,Us=n;try{return await i}catch(r){throw Si(),r}}async function uw(t){const e=await dc(),n=Us,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:kp(o),keyVersion:n,sessionFallback:yr}}async function dw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await dc({allowSessionFallbackCreation:!1});if(yr&&!n&&!Hs)throw new Ws;const r=fw(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 kp(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let ke="",$t="",rr=null,Nd=0,ot="not-configured",gt=0,ml=0,vl=0,so=0,Zt=0,un=0,Ze=null,Lt=null,_r=null;function pw(){return ml+=1,ml}function gw(){return vl+=1,vl}function wr(t,e,n){Ze=t?{projectId:t,key:e,generation:n}:null}function yl(t,e=ke){if(!t)return!1;const n=Ze;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function fc(t,e,n){if(!$t||Ze&&Ze.projectId!==$t)return;(t||[]).some(r=>(r.id||r.projectId)===$t)?wr($t,e,n):Ze&&wr("",null,null)}function Cp({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===ke||r===ke}async function hc(){sessionStorage.getItem(Ot)&&await dc(),ke=await Me("flutterflow"),$t=await Me("flutterflow_project_id"),bw(),pn(),ke?vc():(ot="not-configured",bt())}let br=!1;function Pp(){const t=document.getElementById("api-keys-modal");Ve(t),mc(),ke&&lo(ke)}function pc(){br=!1,Pp()}function mw(){br=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Pp()}let Od=!1;function Bd(){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 Dd(){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=nn(t.value),r=yp(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.`),lc()}function Ap(){if(br=!1,Bd(),Dd(),!Od){const e=document.getElementById("composer-settings-model");e&&e.addEventListener("change",()=>{const n=document.getElementById("code-generator-model");n.value=e.value,n.dispatchEvent(new Event("change")),Bd(),Dd()}),Od=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function vw(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Fp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=br;if(br=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&gc(),Ve(i))}}let dn=1;function Rp(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function oo(){const t=Rp();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,oo())}function yw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,oo(),Ve(t))}function _w(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Tp(){if(H.isVerified&&Bt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,oo(),Ve(e))}}async function mc(){const t=document.getElementById("flutterflow-api-key-input");ke?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",ww()}function ww(){jd("flutterflow","flutterflow-key-status"),jd("flutterflow_project_id","flutterflow-project-status")}function jd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Rt(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function bw(){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"?Rt("flutterflow")&&Rt("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Rt("flutterflow")||Rt("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)"):Rt(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)")}),pn()}async function Ew(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==ke,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await Ld("flutterflow",n),n!==l&&!r&&os()}const s=n||ke;if(r){if(!ao(r)){Se("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}yl(r,s)?await Ld("flutterflow_project_id",r):(i?os():Ze=null,e.value="",s&&!(Lt&&Lt.key===s&&Lt.generation===gt)&&lo(s))}else i&&os();await hc(),n&&await vc(),mc();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Fp()},1e3)}async function Sw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(vr,gl()),Si(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Mt+"flutterflow"),sessionStorage.removeItem(Mt+"flutterflow_project_id"),sessionStorage.removeItem(Ot),sessionStorage.removeItem(mr),localStorage.removeItem(_t+"salt"),await aw(),localStorage.setItem(vr,gl()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Mt+"flutterflow"),sessionStorage.removeItem(Mt+"flutterflow_project_id"),Ze=null,Lt=null,_r=null,await hc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),mc()}function ao(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=$t||"—"),!e)return;let r,s;if(!Rt("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 vc(){const t=gw(),e=++so,n=gt,i=ke,r=await Me("flutterflow"),s=()=>Cp({seq:t,currentSeq:vl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Rt("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&fc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function os(){$t="",Ze=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Mt+"flutterflow_project_id")}function xw(){gt+=1,Lt=null,_r=null,os();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Rt("flutterflow")?(ot="validating",lo(ke)):ot="not-configured",bt()}function Iw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function kw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Iw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Cw(async n=>{const i=n.target.value.trim();i&&await lo(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&Lt?wr(n,Lt.key,Lt.generation):wr("",null,null)})}function Cw(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function lo(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=pw(),r=++so,s=gt,o=ke,a=()=>Cp({seq:i,currentSeq:ml,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};Lt=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===ke&&(Rt("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;Lt={key:t,generation:s};const f=t===ke,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,fc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),$t&&(e.value=$t)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===ke&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Pw(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 Tw(){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 Mw(){y.bundleSpec=pr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function uo(){const t=bi(y.bundleSpec);y.artifactBundle=pr(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=Dy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=bi(y.artifactBundle).id}function fo(){const t=pr(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=pr({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Np(){const t=_c();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _c(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||bi(t)}function wc(){return _c().code||y.step2Result||""}async function $w(){try{await pc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const ls={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Lw(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 In{constructor(e,n,i="main",r=ls.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=[ls.production,ls.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(wl(f?d.clone():d,fp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 xd({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(Lw(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 wl(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 bc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Nw(t,e=fp){const n=t.clone();let i;try{i=JSON.parse(await wl(t,e))}catch{let o="";try{o=await wl(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 ho(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 X={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Op=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Bp=/extends\s+State<\w+>/;function Ow(t,e=""){if(t==="pubspec.yaml")return X.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return X.OTHER;if(t==="custom_functions.dart")return X.FUNCTION;if(e){const n=Op.test(e),i=Bp.test(e);if(n||i)return X.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return X.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return X.FUNCTION}return X.CODE_FILE}function Dp(t,e){switch(e){case X.ACTION:return`lib/custom_code/actions/${t}`;case X.WIDGET:return`lib/custom_code/widgets/${t}`;case X.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case X.CODE_FILE:return`lib/custom_code/${t}`;case X.DEPENDENCIES:return"pubspec.yaml";case X.OTHER:return`lib/custom_code/${t}`;default:return t}}async function po(t,e=new Map){return by(t,e)}const bl=new Map,hi=new Map,pi=new Map;function Cr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){bl.delete(Cr(t))}function Xi(t,e,n){const i=Cr(t),r=hi.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?hi.delete(i):hi.set(i,r)}function Bw(t,e){Xi(t,e,{uncertain:1})}function Dw(t){const e=Cr(t);pi.set(e,(pi.get(e)??0)+1)}function Hd(t){const e=Cr(t),n=(pi.get(e)??0)-1;n<=0?pi.delete(e):pi.set(e,n)}function bc(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 go(t,e,n=dp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Nw(s)})();return bc(r,n,(s,o)=>{i.stop=!0,Yn(t),Dw(t),r.then(()=>Hd(t),()=>Hd(t)),o(new We("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 jw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=i_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function Ec(t,e,n,i,r="",s=dp){const o=n_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=__();let l=!1;const u=l0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch(Fd,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 u0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await bc(g,s,(m,v)=>{p=!1,v(new We("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(Id(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Id(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Yn(t),Bw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Xi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&pp(w)&&Xi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await k_({provisionEndpoint:Fd,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Xi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await jw(t,o,m);throw r_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Yn(t),Xi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Sc(t,e={}){const n=Cr(t);let i=bl.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=cp(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=hi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&hi.delete(n)}!hi.has(n)&&!pi.has(n)&&bl.set(n,i)}const r=await C0(i.pubspecYaml,e),s=i0(i.pubspecYaml,r.overrides),o=n0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Uw(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===X.ACTION&&n.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&n.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&n.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const r=t.content.match(/print\s*\(/g);r&&r.length>3&&n.push(`Code contains ${r.length} print statements. Consider removing debug prints before committing.`);const s=M_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===X.WIDGET){const o=Xh(t.content),a=F_(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=`${Qh(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 jp(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=Xh(s)[0],c=u?Qh(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=X.CODE_FILE;switch(n){case"CustomAction":a=X.ACTION;break;case"CustomWidget":a=X.WIDGET;break;case"CustomFunction":a=X.FUNCTION;break;case"CustomClass":case"CodeFile":a=X.CODE_FILE;break}let l="";return a===X.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 Aw(){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 Fw(){y.bundleSpec=hr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function co(){const t=wi(y.bundleSpec);y.artifactBundle=hr(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=By(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=wi(y.artifactBundle).id}function uo(){const t=hr(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=hr({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 Mp(){const t=yc();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function yc(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||wi(t)}function _c(){return yc().code||y.step2Result||""}async function Rw(){try{await hc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const as={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Tw(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 In{constructor(e,n,i="main",r=as.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=[as.production,as.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(_l(f?d.clone():d,cp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 Sd({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(Tw(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 _l(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 wc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Mw(t,e=cp){const n=t.clone();let i;try{i=JSON.parse(await _l(t,e))}catch{let o="";try{o=await _l(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 fo(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 X={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},$p=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Lp=/extends\s+State<\w+>/;function $w(t,e=""){if(t==="pubspec.yaml")return X.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return X.OTHER;if(t==="custom_functions.dart")return X.FUNCTION;if(e){const n=$p.test(e),i=Lp.test(e);if(n||i)return X.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return X.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return X.FUNCTION}return X.CODE_FILE}function Np(t,e){switch(e){case X.ACTION:return`lib/custom_code/actions/${t}`;case X.WIDGET:return`lib/custom_code/widgets/${t}`;case X.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case X.CODE_FILE:return`lib/custom_code/${t}`;case X.DEPENDENCIES:return"pubspec.yaml";case X.OTHER:return`lib/custom_code/${t}`;default:return t}}async function ho(t,e=new Map){return wy(t,e)}const wl=new Map,fi=new Map,hi=new Map;function kr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Kn(t){wl.delete(kr(t))}function Zi(t,e,n){const i=kr(t),r=fi.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?fi.delete(i):fi.set(i,r)}function Lw(t,e){Zi(t,e,{uncertain:1})}function Nw(t){const e=kr(t);hi.set(e,(hi.get(e)??0)+1)}function Ud(t){const e=kr(t),n=(hi.get(e)??0)-1;n<=0?hi.delete(e):hi.set(e,n)}function wc(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 po(t,e,n=lp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Mw(s)})();return wc(r,n,(s,o)=>{i.stop=!0,Kn(t),Nw(t),r.then(()=>Ud(t),()=>Ud(t)),o(new We("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 Ow(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=n_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function bc(t,e,n,i,r="",s=lp){const o=t_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=y_();let l=!1;const u=a0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch(Ad,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 c0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await wc(g,s,(m,v)=>{p=!1,v(new We("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(xd(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(xd(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Kn(t),Lw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Zi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&dp(w)&&Zi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await I_({provisionEndpoint:Ad,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Zi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:il(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await Ow(t,o,m);throw i_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Kn(t),Zi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:il(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Ec(t,e={}){const n=kr(t);let i=wl.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=op(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=fi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&fi.delete(n)}!fi.has(n)&&!hi.has(n)&&wl.set(n,i)}const r=await k0(i.pubspecYaml,e),s=n0(i.pubspecYaml,r.overrides),o=t0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Bw(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===X.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=T_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===X.WIDGET){const o=Yh(t.content),a=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=`${Jh(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:n}}function Op(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=C_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Yh(s)[0],c=u?Jh(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=X.CODE_FILE;switch(n){case"CustomAction":a=X.ACTION;break;case"CustomWidget":a=X.WIDGET;break;case"CustomFunction":a=X.FUNCTION;break;case"CustomClass":case"CodeFile":a=X.CODE_FILE;break}let l="";return a===X.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; @@ -114,15 +114,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Hy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Hw(t){const e={};for(const n of ec(t))e[n]="";return e}function Ww(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 qw(t,e,n,i=new Set,r=""){const s=[],o=Op.test(e),a=Bp.test(e);return n===X.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function mo(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=>eo(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=qw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=cp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function xc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(_l(n,e))return n;const i=++oo,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==ke||i<=un||(un=i,!s)?"":Ze&&Ze.projectId!==n&&_l(Ze.projectId,e)?Ze.projectId:((!Ze||Ze.projectId===n)&&br(n,e,r),n)}async function zw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=X.WIDGET),i==="CustomAction"&&(i=X.ACTION),i==="CustomFunction"&&(i=X.FUNCTION),i==="CustomClass"&&(i=X.CODE_FILE),i==="CodeFile"&&(i=X.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await xc(o);if((o!==ke||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!lo(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||Ow(e,t),f=Dp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=mo(c);if(!p.valid)throw new Error(`Validation failed: +`),{content:Uy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Dw(t){const e={};for(const n of Ql(t))e[n]="";return e}function jw(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 Uw(t,e,n,i=new Set,r=""){const s=[],o=$p.test(e),a=Lp.test(e);return n===X.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function go(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=>Qs(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=Uw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=op(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function Sc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(yl(n,e))return n;const i=++so,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==ke||i<=un||(un=i,!s)?"":Ze&&Ze.projectId!==n&&yl(Ze.projectId,e)?Ze.projectId:((!Ze||Ze.projectId===n)&&wr(n,e,r),n)}async function Hw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=X.WIDGET),i==="CustomAction"&&(i=X.ACTION),i==="CustomFunction"&&(i=X.FUNCTION),i==="CustomClass"&&(i=X.CODE_FILE),i==="CodeFile"&&(i=X.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await Sc(o);if((o!==ke||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!ao(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||$w(e,t),f=Np(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=go(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const h=await Sc(u,r),g=h.yaml,m=await Ec(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await po(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await vo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Yn(u),$e.set("push");const x=await go(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||ho(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function vo(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 Vw(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=jp(t,{artifactType:n,artifactName:i,fileName:r}),u=Hw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=sr||await xc(c);if((c!==ke||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Dp(l.fileName,l.codeType),functionName:l.codeType===X.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=mo(h);if(!g.valid)throw new Error(`File validation failed: +`)}`);const h=await Ec(u,r),g=h.yaml,m=await bc(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await ho(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await mo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Kn(u),$e.set("push");const x=await po(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||fo(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function mo(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 Ww(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=Op(t,{artifactType:n,artifactName:i,fileName:r}),u=Dw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=rr||await Sc(c);if((c!==ke||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!ao(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Np(l.fileName,l.codeType),functionName:l.codeType===X.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=go(h);if(!g.valid)throw new Error(`File validation failed: ${g.errors.join(` -`)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),Y.setState(ne.PUSHING);const m=new In(c,p,"main",d),v=await Sc(m,u),b=v.yaml,w=await Ec(m,h,v.remoteFiles,`Provision ${i} custom class`,b);o=w.provisionSucceeded===!0;const _=await po(w.syncFileMap,w.remoteFiles),x=new Map(w.syncFileMap);x.set("pubspec.yaml",{content:b,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const I=await vo(x),T={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:b,file_map:_.fileMapContents,functions_map:_.functionsMapContents};Y.setProgress(1,h.size),Yn(m),$e.set("push");const S=await go(m,T);if(S.success){const P={...Ww(l,s),projectId:p};return Y.setSuccess({...P,fileCount:h.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:w.unverified,approximate:w.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=S.errorMessage||ho(S.responseCode),R=new Error(P);throw R.errorMap=S.errorMap,R.remoteRefusal=!0,R}}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 We?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...l.finishDeploy?{finishDeploy:lg(l.finishDeploy,a,Y)}:{}}: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,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function Gw(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:ze(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ne.PREPARING),t.errors?.length>0)throw new Error(`Bundle validation failed: +`)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),Y.setState(ne.PUSHING);const m=new In(c,p,"main",d),v=await Ec(m,u),b=v.yaml,w=await bc(m,h,v.remoteFiles,`Provision ${i} custom class`,b);o=w.provisionSucceeded===!0;const _=await ho(w.syncFileMap,w.remoteFiles),x=new Map(w.syncFileMap);x.set("pubspec.yaml",{content:b,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const I=await mo(x),T={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:b,file_map:_.fileMapContents,functions_map:_.functionsMapContents};Y.setProgress(1,h.size),Kn(m),$e.set("push");const S=await po(m,T);if(S.success){const P={...jw(l,s),projectId:p};return Y.setSuccess({...P,fileCount:h.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:w.unverified,approximate:w.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=S.errorMessage||fo(S.responseCode),R=new Error(P);throw R.errorMap=S.errorMap,R.remoteRefusal=!0,R}}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 We?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...l.finishDeploy?{finishDeploy:og(l.finishDeploy,a,Y)}:{}}: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,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function qw(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:ze(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ne.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===X.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=mo(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===X.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=go(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=sr||await xc(a);if((a!==ke||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Sc(d,t.dependencies),p=f.yaml,h=await Ec(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await po(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await vo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Yn(d),$e.set("push");const w=await go(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||ho(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:lg(s.finishDeploy,r,Y)}:{}}: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 Kw(t,e=[]){const n=Jl("architect");try{return await Gs("architect",Ip,cy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function yo(t,e,n=[],i){const r=uy(t),s=Jl("generator",y.bundleSpec);try{return await Gs("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),eE(e,Kr,i);try{return await Gs("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 _o(t,e=null){const n={...Jl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Gs("review",kp,dy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function zs(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=` +`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=rr||await Sc(a);if((a!==ke||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!ao(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Ec(d,t.dependencies),p=f.yaml,h=await bc(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await ho(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await mo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Kn(d),$e.set("push");const w=await po(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||fo(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:og(s.finishDeploy,r,Y)}:{}}: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 zw(t,e=[]){const n=Yl("architect");try{return await Vs("architect",Ep,ly(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function vo(t,e,n=[],i){const r=cy(t),s=Yl("generator",y.bundleSpec);try{return await Vs("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Gr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),Zb(e,Gr,i);try{return await Vs("generator",Gr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Gr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function yo(t,e=null){const n={...Yl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Vs("review",Sp,uy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function qs(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=` @@ -130,12 +130,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),zs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),zs(t,"completed"))}function Yw(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 Jw(t){at(parseInt(t.replace("step","")))}function at(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"),Jn();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 Zw(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 El(t){const e=Sl(t);console.log(`Step 1 (Prompt Architect): ${nn(Ip)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(kp)}`)}function Up(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function Xw(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=bi(y.artifactBundle)?.id||null)}const Hp="results-replacement-error";function Qw(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Hp);if(!r)return;const s=mp(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=`${So[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=()=>Ii(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Ic(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Ic(){const t=document.getElementById(Hp);t&&(t.hidden=!0)}function Wp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),Xw(e),Pi(),Bt(!0),Tr(),y.resultsViewMode=e.resultsViewMode||"summary",Rr(),kn(),Qw(t,{stage:n,runId:i,retry:r}),pn())}async function qp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=xo();kc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Up();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),qs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),qs(t,"completed"))}function Vw(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 Gw(t){at(parseInt(t.replace("step","")))}function at(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"),Yn();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 Kw(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 bl(t){const e=El(t);console.log(`Step 1 (Prompt Architect): ${nn(Ep)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(Sp)}`)}function Bp(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function Yw(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=wi(y.artifactBundle)?.id||null)}const Dp="results-replacement-error";function Jw(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Dp);if(!r)return;const s=hp(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=`${Eo[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=()=>xi(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{xc(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function xc(){const t=document.getElementById(Dp);t&&(t.hidden=!0)}function jp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),Yw(e),Ci(),St(!0),Rr(),y.resultsViewMode=e.resultsViewMode||"summary",Fr(),kn(),Jw(t,{stage:n,runId:i,retry:r}),pn())}async function Up(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=So();Ic("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Bp();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{Ic();const r=_c(),s=r.id,o=fy({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."});Co({runId:e}),Lt(2,e),at(2),Fe(2,!0);const a=await yo(o,t,[],e);if(!le(e))return;y.step2Result=a,uo(),fn(2,e);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,e),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,fo(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=bi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=ro(r,{architect:2,generator:2,review:3});Wp(r,{previous:i,stage:s,runId:e,retry:qp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function kc(t,e,n){const i=`${Et}/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 eb(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function zp(){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){Se("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=xo();kc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{xc();const r=yc(),s=r.id,o=dy({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."});ko({runId:e}),Nt(2,e),at(2),Fe(2,!0);const a=await vo(o,t,[],e);if(!le(e))return;y.step2Result=a,co(),fn(2,e);const l=document.getElementById("step2-output"),u=Ei(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Nt(3,e),Fe(3,!0);const c=await yo(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,uo(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=wi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ci();const f=ro(y.step3Result);Rr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=io(r,{architect:2,generator:2,review:3});jp(r,{previous:i,stage:s,runId:e,retry:Up})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function Ic(t,e,n){const i=`${Et}/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 Zw(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Hp(){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){Se("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=So();Ic("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=Up();try{Ic();const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});wg(),Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=ro(o,{architect:2,generator:2,review:3});Wp(o,{previous:s,stage:a,runId:i,retry:zp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}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=De.slice();if(!t.trim()){Se("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=xo();try{if(await dl,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await xb(t)||!le(i)||(await yb(),!le(i)))return;const r=Sl(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),Tw(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Ys(!0),El(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Co({prompt:t,runId:i}),rE(a,l),at(1),Lt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await Kw(t,u);if(!le(i))return;y.step1Result=c,Mw(),fn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=Si(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Lt(2,i),Fe(2,!0);const p=await yo(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,uo(),fn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=Si(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const m=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,fo(),fn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Pi();const b=so(y.step3Result);Tr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=ro(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():Dn("Pipeline Failed",{error:r.message,effectiveModel:Sl(document.getElementById("code-generator-model").value)}),at(s),Fe(s,!1),mg(r,{stage:s,runId:i}),zs(s,"error")}finally{le(i)&&(y.isRunning=!1,Ys(!1),pn())}}function tb(){const t=document.getElementById("code-generator-model").value,e=[js,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=Bp();try{xc();const o=Hh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});yg(),ko({runId:i}),Nt(2,i),at(2),Fe(2,!0);const a=await vo(o,n,[],i);if(!le(i))return;y.step2Result=a,co(),fn(2,i);const l=document.getElementById("step2-output"),u=Ei(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Nt(3,i),Fe(3,!0);const c=await yo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,uo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ci();const f=ro(y.step3Result);Rr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=io(o,{architect:2,generator:2,review:3});jp(o,{previous:s,stage:a,runId:i,retry:Hp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function Er(){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=De.slice();if(!t.trim()){Se("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=So();try{if(await ul,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await bb(t)||!le(i)||(await gb(),!le(i)))return;const r=El(e);t.length,Aw(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Ks(!0),bl(r),Yn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();ko({prompt:t,runId:i}),tE(a,l),at(1),Nt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await zw(t,u);if(!le(i))return;y.step1Result=c,Fw(),fn(1,i);const d=document.getElementById("step1-output"),f=Ei(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Nt(2,i),Fe(2,!0);const p=await vo(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,co(),fn(2,i);const h=document.getElementById("step2-output"),g=Ei(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Nt(3,i),Fe(3,!0);const m=await yo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,uo(),fn(3,i);const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Ci();const b=ro(y.step3Result);Rr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=io(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():(r.message,El(document.getElementById("code-generator-model").value),void 0),at(s),Fe(s,!1),pg(r,{stage:s,runId:i}),qs(s,"error")}finally{le(i)&&(y.isRunning=!1,Ks(!1),pn())}}function Xw(){const t=document.getElementById("code-generator-model").value,e=[Ds,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -143,14 +143,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 nb(){const t=wc();if(!t){Se("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}if(y.artifactBundle?.artifacts?.length>1){await ib();return}const{artifactType:i,artifactName:r,fileName:s}=Np(),o=jp(t,{artifactType:i,artifactName:r,fileName:s}),a=Uw(o);if(!a.canProceed){Se(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Ac(o,a,null,null)}async function ib(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}const n=Xy(y.artifactBundle);if(n.errors.length>0){Se(`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=mo(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Se(`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],Er()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],Er())}async function Qw(){const t=_c();if(!t){Se("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),pc();return}if(y.artifactBundle?.artifacts?.length>1){await eb();return}const{artifactType:i,artifactName:r,fileName:s}=Mp(),o=Op(t,{artifactType:i,artifactName:r,fileName:s}),a=Bw(o);if(!a.canProceed){Se(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Pc(o,a,null,null)}async function eb(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),pc();return}const n=Zy(y.artifactBundle);if(n.errors.length>0){Se(`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=go(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Se(`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};Ac(o,s,n.dependencies,n)}function rb(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};Pc(o,s,n.dependencies,n)}function tb(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`

    FlutterFlow Commit Failed

    ${W(t.error)}

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

    Errors:

    -
      `;for(const[r,s]of e.entries()){const o=nc(s);n+=`
    • +
        `;for(const[r,s]of e.entries()){const o=tc(s);n+=`
      • ${W(r)}: ${W(o)}
      • `}n+="
    "}n+="
    ",n+=`
    -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Vp(t.error,e)}))}async function Vp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=xo(),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",()=>{Wp(t.error,e)}))}async function Wp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=So(),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[p,h]of e.entries()){const g=nc(h);s+=`File: ${p} +`;if(e&&e.size>0)for(const[p,h]of e.entries()){const g=tc(h);s+=`File: ${p} Error: ${g} `}else s+=`${t} -`;const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=ro(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),mg(s,{stage:o,runId:i,retry:()=>Vp(t,e)}),zs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function sb(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 Gp(t){try{const e=await fetch(`${Et}/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 ob(t){try{const n=await(await fetch(`${Et}/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 ab(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Wd(t,e){const n=Yp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,fe=Kn({isLoading:!0}),localStorage.setItem(Os,JSON.stringify({email:t,sessionToken:e})),i&&eg()}function Kp(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),localStorage.removeItem(Os),localStorage.removeItem(Ds)}function Yp(){try{const t=localStorage.getItem(Os);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(Os),{email:null,sessionToken:null}}}async function lb(){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 ob(e);Wd(n,i),Jp();const r=qd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){qd();const i=n.message||"Sign-in link invalid or expired.";Se(i,"error"),wo(),ci(i,"error")}}else{const{email:n,sessionToken:i}=Yp();if(n&&i){const r=await ab(i);r?Wd(r.email,r.sessionToken):Kp()}}Cc()}function cb(){try{localStorage.setItem(ul,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function qd(){try{const t=localStorage.getItem(ul);if(localStorage.removeItem(ul),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>H0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function wo(){const t=document.getElementById("signin-modal");if(!t)return;cb(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ci(""),Ve(t)}function Jp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function ci(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 ub(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=no(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"),ci("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ep(n);r&&ci(r,"error");try{const s=await Gp(n),o=ic(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ci(tp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ci("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function db(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),K_({storage:window.localStorage,onIdentityChanged:Cc,onPlanChanged:Eo})}const fb=J_({sendLink:Gp,getEmail:()=>H.email||"",onState:hb});function hb(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=tp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function pb(){await fb()}function gb(){const t=V_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Se(`${e} Your run count, identity and stored keys are kept.`,"info")}function mb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function vb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Cc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Pb(),Eo()}async function Zp(){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(V0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(q0,r.user_id),yt.token&&sessionStorage.setItem(z0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),_n()}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 va=null;function yb(t=5e3){return yt.resolved?Promise.resolve():(va||(va=Zp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([va,new Promise(e=>setTimeout(e,t))]))}function Xp(){const t=xn();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Pr(){const t=Xp();return t.month!==xn()?{count:0,month:xn()}:t}function _b(){const e={count:Pr().count+1,month:xn()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Ci(){return!!fe.isLoading}function Ot(){return!!fe.isResolved}function wb(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(Bs,e)?e:null}function bb(t){return t&&Object.entries(wp).find(([,e])=>e===t)?.[0]||null}function Yr(...t){return t.find(e=>e!=null&&e!=="")}function Eb(...t){return t.find(e=>e&&typeof e=="object")||{}}function Sb(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=Eb(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=Yr(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=Yr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=wb(Yr(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=G0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||bb(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Yr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function bo(){return Bs[fe.tier]??Bs.free}async function xb(t){if(H.isVerified&&(!Ot()||Ci())&&(await Qp({force:!0}),Eo()),H.isVerified&&!Ot())return Se("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:e}=Pr(),n=bo();if(e>=n)return Ib(e,n,{openModal:!0,prompt:t}),!1;const i=Math.floor(n*.8);if(e>=i){const r=n-e;Se(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function zd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ib(t,e,n={}){Bt(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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){Se(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ii();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=fe.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");if(d&&d.classList.toggle("hidden",H.isVerified),n.prompt!=null){y.submittedPrompt=n.prompt;const f=document.getElementById("pipeline-submitted-prompt");f&&(f.textContent=n.prompt)}u.classList.remove("hidden"),n.openModal&&Ii()}function Sl(t){return fe.tier==="free"&&rs.includes(t)?js:t}function kb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=fe.tier,r=!(H.isVerified&&!Ot())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=rs.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&rs.includes(e.value)&&(e.value=js),e.disabled=!1,Rd.has(e)||(e.addEventListener("change",()=>{Ot()&&fe.tier==="free"&&rs.includes(e.value)&&(e.value=js,Ii()),El(e.value),cc()}),Rd.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(),El(e.value)}function Pc(){const t=H.isVerified&&!!H.email,e=t&&Ci(),n=!t||Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Yl,u=n?fe.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Xp(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Bs.free} generations used`}}Cb()}function Cb(){if(!(H.isVerified&&!!H.email))return;const e=Ci(),n=Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=n?fe.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Zi(Ji[a]??0,uc());h.textContent=`${S} / 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 S=Date.parse(fe.periodEnd||""),P=n&&a!=="free"&&!!fe.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Pc(),H.isVerified&&(Ci()||!Ot())){zd();return}const{count:t}=Pr();tString(s.error).toLowerCase().includes(a))){Kp(),Cc();return}fe=Kn({isResolved:!1,error:s.error});return}fe=Sb(s),localStorage.setItem(Ds,JSON.stringify({version:Td,data:fe,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function eg(){localStorage.removeItem(Ds)}async function Ab(t){if(!H.isVerified||!H.sessionToken){ng(),wo();return}if(!wp[t]){Se("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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:uc()})})).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"),Se("Could not start checkout. Please try again.","error")}}async function Fb(t){if(!H.isVerified||!H.sessionToken){wo();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Se("Could not open billing portal. Please try again.","error")}}const Vs=new Set;function tg(){Vs.forEach(t=>t.abort()),Vs.clear()}async function Gs(t,e,n,i={},r=[]){const o=new AbortController;Vs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(W0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Wn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=_y(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),_n())}else _b(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Vs.delete(o)}}let xl=!1;function Rb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),eg(),xl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Se("Checkout cancelled.","info")),e}function Tb(){if(!xl)return;xl=!1;const t=fe.tier!=="free";Se(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Eo(){const t=H.isVerified&&!!H.email,e=fe.tier,n=t&&Ci(),i=!t||Ot(),r=document.getElementById("subscription-tier-badge");if(r){const a=Yl,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"),Mb(i?e:null),kb(),cc(),_n(),bg()}function Mb(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 $b(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=oy[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 Il(){const t=uc(),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=Zi(Ji.professional,t)),n&&(n.textContent=Zi(Ji.power,t)),i&&(i.textContent=Zi(Ji.professional,t)),r&&(r.textContent=Zi(Ji.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ii(){Il();const t=document.getElementById("pricing-modal");t&&Ve(t),rw().then(()=>Il())}function ng(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Se(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()=>{iy(),Yb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Lb(),window.__heroField=f0(),window.__pipelineLogo=m0(),mE(),lc=N0({onSubmit:Sr}),dl=(async()=>{try{await lb(),Rb(),await Qp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await dl,Tb(),Eo(),Il(),$b(),await $w(),Aw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Lp(),Zp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(mc(),ao())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(ug(),$e.phaseId||Rc(),Gd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(Gd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,Tc()},1e3))}),jc()});function Lb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Nb(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Lp()}let or=null;async function kl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Od,n=++oo,i=()=>e===Od,r=gt;wr=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==ke)return kl();if(n>un&&(un=n,hc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),wr={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==ke)return kl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function Ob(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=wr;return!n||n.key!==ke||n.generation!==gt?null:e}function Ac(t,e,n,i=null){or={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,kl();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function ig(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),or=null}function Bb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 rg(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function sg(t){Tc(),rb(t);const e=t.remoteRefusal===!0;Fc(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 Fc(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(nc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function og(t){Fc(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 ag(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Cl=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Fc(t,{heading:e,title:n,guidance:i})}let Cl=null;function lg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function Db(){const t=Cl;if(!t||Mc)return;Cl=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);cg(),$c(!0),Rc();try{$e.set("package");const n=s_(t.fileMap,t.landed,t.serializedYaml),i=await po(n,new Map),r=await vo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),$e.set("push");const o=await go(e,s);if(o.success){Ks({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||ho(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ks({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function cg(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function jb(){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 Vd={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}},Ub=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function ug(){Un&&clearTimeout(Un),Un=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){ug(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(sd(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Vd[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=Vd[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=Ub.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(Hb(e)),dg(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&&(sd(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function Hb(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 Rc(t){$e.start(t)}function Tc(){$e.stop()}function dg(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Gd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,dg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function Wb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===X.CODE_FILE):t.codeInfo?.codeType===X.CODE_FILE}let Mc=!1;function $c(t){Mc=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 Ks(t){Tc(),$c(!1);const e=hp(t);e===Ne.COMMITTED?rg(t):e===Ne.PARTIAL?og(t):e===Ne.UNCONFIRMED?ag(t):sg(t)}async function qb(){if(!or){console.error("No pending commit data");return}if(Mc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=or;if(or=null,sr=Ob(),ig(),$c(!0),Rc({withProvisioning:Wb(t)}),t.bundlePlan){const o=await Gw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Np(),s=await Vw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(s)}window.runThinkingPipeline=Sr;window.toggleStep=Jw;window.toggleSection=Yw;window.selectWorkflowStep=at;window.copyCode=Zw;window.retryWithDifferentModel=tb;window.openApiKeysModal=gc;window.closeApiKeysModal=Mp;window.openComposerSettings=Tp;window.closeComposerSettings=ww;window.walkthroughConnectAccount=_w;window.closeWalkthroughModal=Ew;window.openWalkthroughModal=bw;window.advanceWalkthrough=mc;window.commitToFlutterFlow=zw;function zb(){y.isRunning||Bt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Vb(){Tp();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=zb;window.openModelSelector=Vb;window.handlePromptImageSelect=nw;window.removePromptImage=iw;window.saveApiKeys=Iw;window.validateFlutterFlowConnection=yc;window.clearAllApiKeys=kw;window.toggleKeyVisibility=Rw;window.handleWelcomeVideoEnd=Nb;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=nb;window.updateFlutterFlowCredentialStatus=sb;window.openCommitConfirmModal=Ac;window.closeCommitConfirmModal=ig;window.closeCommitSuccessModal=Bb;window.closeCommitTerminalModal=cg;window.finishProvisionedDeploy=Db;window.showCommitPartialModal=og;window.showCommitUnconfirmedModal=ag;window.showCommitSuccessModal=rg;window.showCommitFailureModal=sg;window.toggleCodePreview=jb;window.confirmCommitToFlutterFlow=qb;window.runRefinement=qp;window.regenerateFromPastedErrors=zp;window.clearErrorInput=eb;window.setFlutterFlowEndpoint=mw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=wo;window.closeSignInModal=Jp;window.handleMagicLinkRequest=ub;window.handleSignOut=db;window.handleSendNewLink=pb;window.handleClearCache=gb;window.handleDeleteAccount=mb;window.closeDeleteUnavailableModal=vb;window.startCheckout=Ab;window.openCustomerPortal=Fb;window.openPricingModal=Ii;window.closePricingModal=ng;let cs=null,fg=null,hn={1:"pending",2:"pending",3:"pending"},qn=1,Pl=null,Lc=null;const So={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Gb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Kb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function xo(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function hg(){y.runId+=1}function Nc(t){return document.getElementById(`pdot-${t}`)}const pg=window.matchMedia("(max-width: 920px)");function Kd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=pg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Yb(){Kd(),pg.addEventListener("change",Kd)}function Jb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Ys(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 Io(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){hn[t]=e;const n=Nc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=So[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 Zb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Ar(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${Xb()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function Xb(){const t=33.333333333333336,e=hn[qn];if(e==="active"&&Pl!==null){const n=(Date.now()-Pl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:Zb()/3*100}function ko(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?Kb[t]:Gb[t]),i&&(i.textContent=Jb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${So[t]}${a}`}}function Qb(t){hn[t]==="pending"||hn[t]==="skipped"||(Lc=t,[1,2,3].forEach(e=>{const n=Nc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),ko(t))}function Oc(){Lc=null,[1,2,3].forEach(t=>{const e=Nc(t);e&&e.removeAttribute("aria-pressed")})}function gg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function eE(t,e,n){le(n)&&gg(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function Bc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function tE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Gn()}function nE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function iE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=iE;function rE(t,e){_p(t,document.getElementById("main-stage-container"),nE()),D0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function Co(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Fr(),kn(),Bt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),Io("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}fg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Oc(),Bc(),gg(""),[1,2,3].forEach(a=>zn(a,"pending")),Lt(1,n),sE()}function Lt(t,e){le(e)&&(qn=t,Pl=Date.now(),Oc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),ko(t),Ar())}function fn(t,e){le(e)&&(zn(t,"done"),Lc===null&&ko(t,{done:!0}),Ar())}function mg(t,{stage:e=1,runId:n,retry:i=vg}={}){if(!le(n))return;Po(),Fr(),kn(),Io("failed"),Bt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Oc(),ko(e),Ar();const o=mp(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=`${So[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>Ii()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Al}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Al}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Al(){hg(),tg(),y.isRunning=!1,Ys(!1),pn(),Io("settled"),kn(),Po(),Fr(),Bc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Bt(!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 vg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),Bc(),Sr()}function sE(){Po(),cs=setInterval(()=>{const t=(Date.now()-fg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Ar()},250)}function Po(){cs&&(clearInterval(cs),cs=null)}let ar=null;function Fr(){ar&&(clearTimeout(ar),ar=null)}function Pi(){Po(),Fr(),Io("settled"),Ar();const t=document.getElementById("pipeline-progress-fill");ar=setTimeout(()=>{ar=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function ki(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function yg(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function oE(){return m_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function aE(t){return` +`;const o=Hh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});ko({runId:i}),Nt(2,i),at(2),Fe(2,!0);const a=await vo(o,n,[],i);if(!le(i))return;y.step2Result=a,co(),fn(2,i);const l=document.getElementById("step2-output"),u=Ei(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Nt(3,i),Fe(3,!0);const c=await yo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,uo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ci();const f=ro(y.step3Result);Rr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=io(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),pg(s,{stage:o,runId:i,retry:()=>Wp(t,e)}),qs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function nb(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 qp(t){try{const e=await fetch(`${Et}/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 ib(t){try{const n=await(await fetch(`${Et}/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 rb(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Hd(t,e){const n=Vp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,fe=Gn({isLoading:!0}),localStorage.setItem(Ns,JSON.stringify({email:t,sessionToken:e})),i&&Xp()}function zp(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Gn({isResolved:!0}),localStorage.removeItem(Ns),localStorage.removeItem(Bs)}function Vp(){try{const t=localStorage.getItem(Ns);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(Ns),{email:null,sessionToken:null}}}async function sb(){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 ib(e);Hd(n,i),Gp();const r=Wd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){Wd();const i=n.message||"Sign-in link invalid or expired.";Se(i,"error"),_o(),li(i,"error")}}else{const{email:n,sessionToken:i}=Vp();if(n&&i){const r=await rb(i);r?Hd(r.email,r.sessionToken):zp()}}kc()}function ob(){try{localStorage.setItem(cl,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function Wd(){try{const t=localStorage.getItem(cl);if(localStorage.removeItem(cl),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>D0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function _o(){const t=document.getElementById("signin-modal");if(!t)return;ob(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),li(""),Ve(t)}function Gp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function li(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 ab(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=to(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"),li("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=Zh(n);r&&li(r,"error");try{const s=await qp(n),o=nc(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),li(Xh(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),li("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function lb(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Gn({isResolved:!0}),G_({storage:window.localStorage,onIdentityChanged:kc,onPlanChanged:bo})}const cb=Y_({sendLink:qp,getEmail:()=>H.email||"",onState:ub});function ub(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=Xh(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function db(){await cb()}function fb(){const t=z_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Se(`${e} Your run count, identity and stored keys are kept.`,"info")}function hb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function pb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function kc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Ib(),bo()}async function Kp(){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(W0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(U0,r.user_id),yt.token&&sessionStorage.setItem(H0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Hn,JSON.stringify({count:a,month:s})),_n()}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 ma=null;function gb(t=5e3){return yt.resolved?Promise.resolve():(ma||(ma=Kp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([ma,new Promise(e=>setTimeout(e,t))]))}function Yp(){const t=xn();try{const e=localStorage.getItem(Hn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Hn,month:t,err:e}),localStorage.removeItem(Hn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Cr(){const t=Yp();return t.month!==xn()?{count:0,month:xn()}:t}function mb(){const e={count:Cr().count+1,month:xn()};return localStorage.setItem(Hn,JSON.stringify(e)),e}function ki(){return!!fe.isLoading}function Bt(){return!!fe.isResolved}function vb(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(Os,e)?e:null}function yb(t){return t&&Object.entries(vp).find(([,e])=>e===t)?.[0]||null}function Kr(...t){return t.find(e=>e!=null&&e!=="")}function _b(...t){return t.find(e=>e&&typeof e=="object")||{}}function wb(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=_b(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=vb(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=q0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||yb(r)||(a||l?"professional":"free");return Gn({tier:u,status:s,periodEnd:Kr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function wo(){return Os[fe.tier]??Os.free}async function bb(t){if(H.isVerified&&(!Bt()||ki())&&(await Zp({force:!0}),bo()),H.isVerified&&!Bt())return Se("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:e}=Cr(),n=wo();if(e>=n)return Eb(e,n,{openModal:!0,prompt:t}),!1;const i=Math.floor(n*.8);if(e>=i){const r=n-e;Se(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Jp(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Eb(t,e,n={}){St(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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){Se(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),xi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=fe.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");if(d&&d.classList.toggle("hidden",H.isVerified),n.prompt!=null){y.submittedPrompt=n.prompt;const f=document.getElementById("pipeline-submitted-prompt");f&&(f.textContent=n.prompt)}u.classList.remove("hidden"),n.openModal&&xi()}function El(t){return fe.tier==="free"&&is.includes(t)?Ds:t}function Sb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=fe.tier,r=!(H.isVerified&&!Bt())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=is.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&is.includes(e.value)&&(e.value=Ds),e.disabled=!1,Fd.has(e)||(e.addEventListener("change",()=>{Bt()&&fe.tier==="free"&&is.includes(e.value)&&(e.value=Ds,xi()),bl(e.value),lc()}),Fd.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(),bl(e.value)}function Cc(){const t=H.isVerified&&!!H.email,e=t&&ki(),n=!t||Bt(),i=Cr(),r=n?i.count:0,s=n?wo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Kl,u=n?fe.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Yp(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Os.free} generations used`}}xb()}function xb(){if(!(H.isVerified&&!!H.email))return;const e=ki(),n=Bt(),i=Cr(),r=n?i.count:0,s=n?wo():0,o=Math.max(0,s-r),a=n?fe.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Ji(Yi[a]??0,cc());h.textContent=`${S} / 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 S=Date.parse(fe.periodEnd||""),P=n&&a!=="free"&&!!fe.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Cc(),H.isVerified&&(ki()||!Bt())||Cr().countString(s.error).toLowerCase().includes(a))){zp(),kc();return}fe=Gn({isResolved:!1,error:s.error});return}fe=wb(s),localStorage.setItem(Bs,JSON.stringify({version:Rd,data:fe,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function Xp(){localStorage.removeItem(Bs)}async function kb(t){if(!H.isVerified||!H.sessionToken){eg(),_o();return}if(!vp[t]){Se("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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:cc()})})).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"),Se("Could not start checkout. Please try again.","error")}}async function Cb(t){if(!H.isVerified||!H.sessionToken){_o();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Se("Could not open billing portal. Please try again.","error")}}const zs=new Set;function Qp(){zs.forEach(t=>t.abort()),zs.clear()}async function Vs(t,e,n,i={},r=[]){const o=new AbortController;zs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(j0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Hn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=yy(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Hn,JSON.stringify({count:d.usage_count,month:h})),_n())}else mb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),zs.delete(o)}}let Sl=!1;function Pb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Xp(),Sl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Se("Checkout cancelled.","info")),e}function Ab(){if(!Sl)return;Sl=!1;const t=fe.tier!=="free";Se(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function bo(){const t=H.isVerified&&!!H.email,e=fe.tier,n=t&&ki(),i=!t||Bt(),r=document.getElementById("subscription-tier-badge");if(r){const a=Kl,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"),Fb(i?e:null),Sb(),lc(),_n(),wg()}function Fb(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 Rb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=sy[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 xl(){const t=cc(),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(Yi.professional,t)),n&&(n.textContent=Ji(Yi.power,t)),i&&(i.textContent=Ji(Yi.professional,t)),r&&(r.textContent=Ji(Yi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function xi(){xl();const t=document.getElementById("pricing-modal");t&&Ve(t),tw().then(()=>xl())}function eg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Se(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()=>{ny(),Vb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Tb(),window.__heroField=d0(),window.__pipelineLogo=g0(),hE(),ac=L0({onSubmit:Er}),ul=(async()=>{try{await sb(),Pb(),await Zp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await ul,Ab(),bo(),xl(),Rb(),await Rw(),kw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Tp(),Kp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(gc(),oo())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(lg(),$e.phaseId||Fc(),zd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(zd(i),jn&&clearTimeout(jn),jn=setTimeout(()=>{jn=null,Rc()},1e3))}),Dc()});function Tb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Mb(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Yn),document.addEventListener("keydown",Yn))}function Yn(){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",Yn),document.removeEventListener("keydown",Yn),Tp()}let sr=null;async function Il(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Nd,n=++so,i=()=>e===Nd,r=gt;_r=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==ke)return Il();if(n>un&&(un=n,fc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),_r={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==ke)return Il();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function $b(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=_r;return!n||n.key!==ke||n.generation!==gt?null:e}function Pc(t,e,n,i=null){sr={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,Il();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function tg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),sr=null}function Lb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 ng(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function ig(t){Rc(),tb(t);const e=t.remoteRefusal===!0;Ac(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 Ac(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(tc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function rg(t){Ac(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 sg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(kl=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Ac(t,{heading:e,title:n,guidance:i})}let kl=null;function og(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function Nb(){const t=kl;if(!t||Tc)return;kl=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);ag(),Mc(!0),Fc();try{$e.set("package");const n=r_(t.fileMap,t.landed,t.serializedYaml),i=await ho(n,new Map),r=await mo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Kn(e),$e.set("push");const o=await po(e,s);if(o.success){Gs({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||fo(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Gs({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function ag(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function Ob(){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 qd={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}},Bb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let jn=null;function lg(){jn&&clearTimeout(jn),jn=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){lg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(rd(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!qd[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=qd[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=Bb.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(Db(e)),cg(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&&(rd(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function Db(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 Fc(t){$e.start(t)}function Rc(){$e.stop()}function cg(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 zd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,cg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function jb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===X.CODE_FILE):t.codeInfo?.codeType===X.CODE_FILE}let Tc=!1;function Mc(t){Tc=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 Gs(t){Rc(),Mc(!1);const e=up(t);e===Ne.COMMITTED?ng(t):e===Ne.PARTIAL?rg(t):e===Ne.UNCONFIRMED?sg(t):ig(t)}async function Ub(){if(!sr){console.error("No pending commit data");return}if(Tc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=sr;if(sr=null,rr=$b(),tg(),Mc(!0),Fc({withProvisioning:jb(t)}),t.bundlePlan){const o=await qw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});rr=null,Gs(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Mp(),s=await Ww(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});rr=null,Gs(s)}window.runThinkingPipeline=Er;window.toggleStep=Gw;window.toggleSection=Vw;window.selectWorkflowStep=at;window.copyCode=Kw;window.retryWithDifferentModel=Xw;window.openApiKeysModal=pc;window.closeApiKeysModal=Fp;window.openComposerSettings=Ap;window.closeComposerSettings=vw;window.walkthroughConnectAccount=mw;window.closeWalkthroughModal=_w;window.openWalkthroughModal=yw;window.advanceWalkthrough=gc;window.commitToFlutterFlow=Hw;function Hb(){y.isRunning||St(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Wb(){Ap();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Hb;window.openModelSelector=Wb;window.handlePromptImageSelect=Q0;window.removePromptImage=ew;window.saveApiKeys=Ew;window.validateFlutterFlowConnection=vc;window.clearAllApiKeys=Sw;window.toggleKeyVisibility=Pw;window.handleWelcomeVideoEnd=Mb;window.dismissWelcomeVideo=Yn;window.initiateCommitToFlutterFlow=Qw;window.updateFlutterFlowCredentialStatus=nb;window.openCommitConfirmModal=Pc;window.closeCommitConfirmModal=tg;window.closeCommitSuccessModal=Lb;window.closeCommitTerminalModal=ag;window.finishProvisionedDeploy=Nb;window.showCommitPartialModal=rg;window.showCommitUnconfirmedModal=sg;window.showCommitSuccessModal=ng;window.showCommitFailureModal=ig;window.toggleCodePreview=Ob;window.confirmCommitToFlutterFlow=Ub;window.runRefinement=Up;window.regenerateFromPastedErrors=Hp;window.clearErrorInput=Zw;window.setFlutterFlowEndpoint=hw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=_o;window.closeSignInModal=Gp;window.handleMagicLinkRequest=ab;window.handleSignOut=lb;window.handleSendNewLink=db;window.handleClearCache=fb;window.handleDeleteAccount=hb;window.closeDeleteUnavailableModal=pb;window.startCheckout=kb;window.openCustomerPortal=Cb;window.openPricingModal=xi;window.closePricingModal=eg;let ls=null,ug=null,hn={1:"pending",2:"pending",3:"pending"},Wn=1,Cl=null,$c=null;const Eo={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},qb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},zb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function So(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function dg(){y.runId+=1}function Lc(t){return document.getElementById(`pdot-${t}`)}const fg=window.matchMedia("(max-width: 920px)");function Vd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=fg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Vb(){Vd(),fg.addEventListener("change",Vd)}function Gb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Ks(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 xo(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function qn(t,e){hn[t]=e;const n=Lc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Eo[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 Kb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Pr(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[Wn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${Yb()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Wn} of 3`)}function Yb(){const t=33.333333333333336,e=hn[Wn];if(e==="active"&&Cl!==null){const n=(Date.now()-Cl)/1e3;return(Wn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?Wn/3*100:Kb()/3*100}function Io(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?zb[t]:qb[t]),i&&(i.textContent=Gb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${Eo[t]}${a}`}}function Jb(t){hn[t]==="pending"||hn[t]==="skipped"||($c=t,[1,2,3].forEach(e=>{const n=Lc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Io(t))}function Nc(){$c=null,[1,2,3].forEach(t=>{const e=Lc(t);e&&e.removeAttribute("aria-pressed")})}function hg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Zb(t,e,n){le(n)&&hg(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function Oc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function Xb(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Vn()}function Qb(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function eE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=eE;function tE(t,e){mp(t,document.getElementById("main-stage-container"),Qb()),B0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function ko(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Ar(),kn(),St(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),xo("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}ug=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Nc(),Oc(),hg(""),[1,2,3].forEach(a=>qn(a,"pending")),Nt(1,n),nE()}function Nt(t,e){le(e)&&(Wn=t,Cl=Date.now(),Nc(),[1,2,3].forEach(n=>{n===t?qn(n,"active"):nt&&qn(n,"pending")}),Io(t),Pr())}function fn(t,e){le(e)&&(qn(t,"done"),$c===null&&Io(t,{done:!0}),Pr())}function pg(t,{stage:e=1,runId:n,retry:i=gg}={}){if(!le(n))return;Co(),Ar(),kn(),xo("failed"),St(!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"),qn(e,"failed"),[1,2,3].forEach(h=>{h>e&&qn(h,"pending")}),Wn=e,Nc(),Io(e),Pr();const o=hp(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=`${Eo[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>xi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Pl}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Pl}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Pl(){dg(),Qp(),y.isRunning=!1,Ks(!1),pn(),xo("settled"),kn(),Co(),Ar(),Oc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Jp(),St(!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 gg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),Oc(),Er()}function nE(){Co(),ls=setInterval(()=>{const t=(Date.now()-ug)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Pr()},250)}function Co(){ls&&(clearInterval(ls),ls=null)}let or=null;function Ar(){or&&(clearTimeout(or),or=null)}function Ci(){Co(),Ar(),xo("settled"),Pr();const t=document.getElementById("pipeline-progress-fill");or=setTimeout(()=>{or=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ii(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function mg(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function iE(){return g_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function rE(t){return`
    - ${ki(t.severity)} + ${Ii(t.severity)}
    ${W(t.message)}
    ${t.suggestion?`
    ${W(t.suggestion)}
    `:""} ${W(t.source)}
    - `}function lE(t){return` + `}function sE(t){return`
  • ${W(t.title)} ${t.detail&&t.detail!==t.title?`

    ${W(t.detail)}

    `:""}
  • - `}function cE(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 oE(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=>`
    • - ${ki(u.severity)} + ${Ii(u.severity)} ${W(u.message)} ${u.suggestion?`${W(u.suggestion)}`:""} @@ -198,7 +198,7 @@ Error: ${g}
    `:"",a=t.warnings.length?`
    -

    ${ki("warning")} Bundle

    +

    ${Ii("warning")} Bundle

      ${t.warnings.map(u=>`
    • ${W(u)}
    • `).join("")}
    @@ -251,14 +251,14 @@ Error: ${g}
    - `}function uE(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(aE).join(""):`
    ${ki(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` + `}function aE(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(rE).join(""):`
    ${Ii(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>`
  • ${W(l.name)}${l.version?` ${W(l.version)}`:""}${l.reason?`

    ${W(l.reason)}

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

    ${W(l.description)}

    `:""}
  • `).join(""):'
  • No relationships for this file
  • ';return`
    - ${ki(e.status)} ${W(yg(e.status))} + ${Ii(e.status)} ${W(mg(e.status))}

    ${W(e.artifactName)}

    ${e.description?`

    ${W(e.description)}

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

    Manual FlutterFlow steps for this file

    -
      ${e.manualSteps.map(lE).join("")}
    +
      ${e.manualSteps.map(sE).join("")}
    `:""}
    @@ -306,7 +306,7 @@ Error: ${g}
      ${a}
    - `}function dE(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=""),Yd();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 lE(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=""),Gd();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&&Dc(o.dataset.artifactId)},Yd()),e&&e.classList.add("visible")}function Yd(){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")_g();else{const a=s.dataset.artifactId;a&&Dc(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 Rr(){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=oE(),o=wc();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")}cE(s),dE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` -`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=vp(a),!tE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=uE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Tr(t,e){const n=document.getElementById("main-stage-container"),i=O0(n),r=document.body.classList.contains("results-fullscreen");Fr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),Bt(!0),y.selectedArtifactId||(y.selectedArtifactId=bi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Rr(),pn(),fE(),r||_p(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function fE(){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=""),Fl=!1}function Dc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Rr()}function _g(){y.resultsViewMode="summary",Rr()}function hE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=wc(),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 Fl=!1;async function pE(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Fl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Fl=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 kc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function gE(){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 wg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function mE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function Bt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function bg(){const t=H.isVerified&&!!H.email,e=fe.tier||"free",n=t&&Ci(),i=!t||Ot(),s=n?"Checking…":i?Yl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Pc();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 vE(){bg();const t=document.getElementById("credits-modal");t&&Ve(t)}function yE(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function Eg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),lc?.cancelTyping?.(),y.isRunning&&(hg(),tg(),y.isRunning=!1,Ys(!1),Pi(),y.artifactBundle?Rr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")Bt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&Bt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let Jd=!1;function jc(){const t=window.location.hash.replace(/^#/,"");Eg(t||"home",!1,Jd),Jd=!0}window.addEventListener("popstate",t=>{jc()});window.addEventListener("hashchange",()=>{jc()});window.copyResultsCode=hE;window.selectArtifact=Dc;window.selectResultsSummary=_g;window.submitResultsFeedback=pE;window.showErrorInputPanel=gE;window.hideErrorInputPanel=wg;window.setGenerationStageVisible=Bt;window.switchView=Eg;window.selectPipelineStage=Qb;window.editPipelinePrompt=Al;window.retryPipelineRun=vg;window.openCreditsModal=vE;window.closeCreditsModal=yE; + `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&Bc(o.dataset.artifactId)},Gd()),e&&e.classList.add("visible")}function Gd(){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")vg();else{const a=s.dataset.artifactId;a&&Bc(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 Fr(){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=iE(),o=_c();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")}oE(s),lE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` +`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=pp(a),!Xb()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=aE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Rr(t,e){const n=document.getElementById("main-stage-container"),i=N0(n),r=document.body.classList.contains("results-fullscreen");Ar(),document.getElementById("pipeline-progress")?.classList.remove("visible"),St(!0),y.selectedArtifactId||(y.selectedArtifactId=wi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Fr(),pn(),cE(),r||mp(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function cE(){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=""),Al=!1}function Bc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Fr()}function vg(){y.resultsViewMode="summary",Fr()}function uE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=_c(),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 Al=!1;async function dE(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Al)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Al=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 Ic(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 fE(){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 yg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function hE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function _g(){if(document.getElementById("pipeline-progress")?.classList.contains("visible")||document.getElementById("results-view")?.classList.contains("visible"))return!0;const n=document.getElementById("paywall-exhausted");if(n&&!n.classList.contains("hidden"))return!0;const i=document.getElementById("ready-state");return!!(i&&!i.classList.contains("hidden"))}function St(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function wg(){const t=H.isVerified&&!!H.email,e=fe.tier||"free",n=t&&ki(),i=!t||Bt(),s=n?"Checking…":i?Kl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Cc();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 pE(){wg();const t=document.getElementById("credits-modal");t&&Ve(t)}function gE(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function bg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),ac?.cancelTyping?.(),y.isRunning&&(dg(),Qp(),y.isRunning=!1,Ks(!1),Ci(),y.artifactBundle?Fr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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"||!_g())St(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&St(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let Kd=!1;function Dc(){const t=window.location.hash.replace(/^#/,"");bg(t||"home",!1,Kd),Kd=!0}window.addEventListener("popstate",t=>{Dc()});window.addEventListener("hashchange",()=>{Dc()});window.copyResultsCode=uE;window.selectArtifact=Bc;window.selectResultsSummary=vg;window.submitResultsFeedback=dE;window.showErrorInputPanel=fE;window.hideErrorInputPanel=yg;window.setGenerationStageVisible=St;window.switchView=bg;window.selectPipelineStage=Jb;window.editPipelinePrompt=Pl;window.retryPipelineRun=gg;window.openCreditsModal=pE;window.closeCreditsModal=gE; diff --git a/dist/index.html b/dist/index.html index 3c507a0..57264fb 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3273,7 +3273,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + From a45f3d0e935d7a25fabbd2c48f46e012eec2e545 Mon Sep 17 00:00:00 2001 From: Stuart Date: Sun, 11 Oct 2026 16:03:11 +1100 Subject: [PATCH 05/10] refactor(composer): drive the hero demo and chip fill from the clock Applies the animation-skill timing model (GSAP timelines, Remotion's typewriter): every frame is derived from elapsed time, built by string slicing, rather than advanced one step per timer callback. Chained timers stretch the animation when the main thread is busy. That is what made the chip-fill spec time out under parallel test load, and it would drag the demo on a slow phone. Now a late tick lands everything already due: frames drop, the timing holds. - heroDemoFrame(elapsed, length) is the demo as a pure timeline: hold, then type at 73ms/char, rest 1.6s, then erase at 35ms/char. For any moment it returns the characters showing, whether the caret is keying (solid) or idle (blinking), whether the demo is done, and the ms until the next change. The runtime renders the frame due now and sleeps until the next one. - The chip fill reads its character count off the clock the same way. Timing is unchanged when nothing runs late. The timeline is now unit tested without a browser: exact phase boundaries, a late tick catching up, and a 1ms sweep showing the count rises and falls by exactly one character at a time. --- dist/assets/index-Czz-ZZvO.js | 328 ++++++++++++++++++++++++++++++++++ dist/assets/index-DYbo9B-C.js | 328 ---------------------------------- dist/index.html | 2 +- src/composerAdapter.js | 90 ++++++---- src/composerAdapter.test.js | 82 ++++++++- 5 files changed, 470 insertions(+), 360 deletions(-) create mode 100644 dist/assets/index-Czz-ZZvO.js delete mode 100644 dist/assets/index-DYbo9B-C.js diff --git a/dist/assets/index-Czz-ZZvO.js b/dist/assets/index-Czz-ZZvO.js new file mode 100644 index 0000000..91ef702 --- /dev/null +++ b/dist/assets/index-Czz-ZZvO.js @@ -0,0 +1,328 @@ +(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 E=typeof window<"u"?window:void 0,Be=typeof globalThis<"u"?globalThis:E,qe=Be?.navigator,F=Be?.document,_e=Be?.location,Ml=Be?.fetch,wa=Be!=null&&Be.XMLHttpRequest&&"withCredentials"in new Be.XMLHttpRequest?Be.XMLHttpRequest:void 0,Yc=Be?.AbortController,$g=Be?.CompressionStream,Je=qe?.userAgent;function tf(){return!(!E||E.navigator.onLine===!1)}var Ti=typeof globalThis<"u"?globalThis:E;Ti&&typeof self>"u"&&(Ti.self=Ti),Ti&&typeof File>"u"&&(Ti.File=function(){});var N=E??{},oe={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Jc(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 ce(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){Jc(s,i,r,o,a,"next",l)}function a(l){Jc(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 nf(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 Zc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Xc(t){return typeof t=="string"||t}function Qc(t){return typeof t=="string"?t:void 0}var Mi,Lg=["$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"],Kt=(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})({}),eu=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Ng=["$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"],Og=["token"],rf="NativeGzipValidationError",ba=t=>t.length>=2&&t[0]===31&&t[1]===139,tu=(t,e)=>t===eu.GZipJS||e===eu.GZipJS||e==="gzip",nu=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Or=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=rf,e},Bg=(function(){var t=ce((function*(e,n){18>e.size&&Or("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());ba(i)&&i[2]===8||Or("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Mi)return Mi;Mi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;Mi[c]=d>>>0}return Mi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Or("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Or("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Ea(){return Ea=ce((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=ce((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 Bg(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ea.apply(this,arguments)}var Dg=["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"],iu=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Dg.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Zs=function(t){return t.trim()},Sa=function(t){return t.replace(/^\$/,"")};function sf(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 of=Object.prototype,af=of.hasOwnProperty,Xs=of.toString,U=Array.isArray||function(t){return Xs.call(t)==="[object Array]"},Ue=t=>typeof t=="function",me=t=>t===Object(t)&&!U(t),rn=t=>{if(me(t)){for(var e in t)if(af.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,Q=t=>Xs.call(t)=="[object String]",xa=t=>Q(t)&&t.trim().length===0,et=t=>t===null,q=t=>C(t)||et(t),Ae=t=>Xs.call(t)=="[object Number]"&&t==t,Vt=t=>Ae(t)&&t>0,wt=t=>Xs.call(t)==="[object Boolean]",jg=t=>t instanceof FormData,Ug=t=>j(Ng,t),Hg=t=>j(Og,t);function lf(t){return t===null||typeof t!="object"}function ds(t,e){return{}.toString.call(t)==="[object "+e+"]"}function $l(t){return typeof Event<"u"&&cf(t,Event)}function cf(t,e){try{return t instanceof e}catch{return!1}}var Wg=[!0,"true",1,"1","yes"],Do=t=>j(Wg,t),qg=[!1,"false",0,"0","no"];function Rt(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Ae(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),Rt(r||n,e,n,i))}class zg{constructor(e){this.tt={},this.et=e.et,this.it=Rt(e.bucketSize,0,100,e.rt),this.nt=Rt(e.refillRate,0,this.it,e.rt),this.st=Rt(e.refillInterval,0,864e5,e.rt)}ot(e,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 lt="Mobile",fs="iOS",sn="Android",mi="Tablet",uf=sn+" "+mi,df="iPad",ff="Apple",hf=ff+" Watch",er="Safari",vi="BlackBerry",pf="Samsung",gf=pf+"Browser",mf=pf+" Internet",Hn="Chrome",Vg=Hn+" OS",vf=Hn+" "+fs,Ll="Internet Explorer",yf=Ll+" "+lt,Nl="Opera",Gg=Nl+" Mini",Ol="Edge",_f="Microsoft "+Ol,di="Firefox",wf=di+" "+fs,cr="Nintendo",ur="PlayStation",fi="Xbox",bf=sn+" "+lt,Ef=lt+" "+er,qi="Windows",Ia=qi+" Phone",ru="Nokia",ka="Ouya",Sf="Generic",Kg=Sf+" "+lt.toLowerCase(),xf=Sf+" "+mi.toLowerCase(),Ca="Konqueror",If="Oculus Browser",hs="Vivaldi",kf="Yandex",ps="Whale",Pa="DuckDuckGo",Cf="Pale Moon",gs="Waterfox",tr="Brave",Pf="Google Search App",Se="(\\d+(\\.\\d+)?)",jo=new RegExp("Version/"+Se),Yg=new RegExp(fi,"i"),Jg=new RegExp(ur+" \\w+","i"),Zg=new RegExp(cr+" \\w+","i"),Bl=new RegExp(vi+"|PlayBook|BB10","i"),Xg={"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"},Af=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?tr:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Pf:j(t," OPR/")&&j(t,"Mini")?Gg:j(t," OPR/")?Nl:Bl.test(t)?vi:j(t,"IE"+lt)||j(t,"WPDesktop")?yf:j(t,"OculusBrowser")?If:j(t,gf)?mf:j(t,Ol)||j(t,"Edg/")?_f:j(t,hs+"/")?hs:j(t,"YaBrowser/")?kf:j(t,ps+"/")?ps:j(t,Pa+"/")||j(t,"Ddg/")?Pa:j(t,"FBIOS")?"Facebook "+lt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?vf:j(t,"CrMo")||j(t,Hn)?Hn:j(t,sn)&&j(t,er)?bf:j(t,"FxiOS")?wf:j(t.toLowerCase(),Ca.toLowerCase())?Ca:j(t,tr+"/")?tr:((s,o)=>o&&j(o,ff)||(function(a){return j(a,er)&&!j(a,Hn)&&!j(a,sn)})(s))(t,e)?j(t,lt)?Ef:er:j(t,"PaleMoon/")?Cf:j(t,gs+"/")?gs:j(t,di)?di:j(t,"MSIE")||j(t,"Trident/")?Ll:j(t,"Gecko")?di:"")},Qg={[yf]:[new RegExp("rv:"+Se)],[_f]:[new RegExp(Ol+"?\\/"+Se)],[Hn]:[new RegExp("("+Hn+"|CrMo)\\/"+Se)],[vf]:[new RegExp("CriOS\\/"+Se)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Se)],[er]:[jo],[Ef]:[jo],[Nl]:[new RegExp("(Opera|OPR)\\/"+Se)],[di]:[new RegExp(di+"\\/"+Se)],[wf]:[new RegExp("FxiOS\\/"+Se)],[Ca]:[new RegExp("Konqueror[:/]?"+Se,"i")],[vi]:[new RegExp(vi+" "+Se),jo],[bf]:[new RegExp("android\\s"+Se,"i")],[mf]:[new RegExp(gf+"\\/"+Se)],[If]:[new RegExp("OculusBrowser\\/"+Se)],[hs]:[new RegExp(hs+"\\/"+Se)],[kf]:[new RegExp("YaBrowser\\/"+Se)],[ps]:[new RegExp(ps+"\\/"+Se)],[tr]:[new RegExp(tr+"\\/"+Se)],[Pa]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Se)],[Cf]:[new RegExp("PaleMoon\\/"+Se)],[gs]:[new RegExp(gs+"\\/"+Se)],[Pf]:[new RegExp("GSA\\/"+Se)],[Ll]:[new RegExp("(rv:|MSIE )"+Se)],Mozilla:[new RegExp("rv:"+Se)]},em=function(t,e,n,i){var r=Af(t,e,n,i),s=Qg[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},su=[[new RegExp(fi+"; "+fi+" (.*?)[);]","i"),t=>[fi,t&&t[1]||""]],[new RegExp(cr,"i"),[cr,""]],[new RegExp(ur,"i"),[ur,""]],[Bl,[vi,""]],[new RegExp(qi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ia,""];if(new RegExp(lt).test(e)&&!/IEMobile\b/.test(e))return[qi+" "+lt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Xg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[qi,i]}return[qi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[fs,[t[3],t[4],t[5]||"0"].join(".")]:[fs,""]],[/(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("("+sn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+sn+")","i"),t=>t&&t[2]?[sn,[t[2],t[3],t[4]||"0"].join(".")]:[sn,""]],[/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/,[Vg,""]],[/Linux|debian/i,["Linux",""]]],ou=function(t){return Zg.test(t)?cr:Jg.test(t)?ur:Yg.test(t)?fi:new RegExp(ka,"i").test(t)?ka:new RegExp("("+Ia+"|WPDesktop)","i").test(t)?Ia:/iPad/.test(t)?df:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?hf:Bl.test(t)?vi:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(ru,"i").test(t)?ru:/(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(lt).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)?sn:uf:new RegExp("(pda|"+lt+")","i").test(t)?Kg:new RegExp(mi,"i").test(t)&&!new RegExp(mi+" pc","i").test(t)?xf:""},tm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function au(t,e){return typeof(n=t)=="string"&&tm.test(n)?t:e();var n}function wn(t){return t&&t.split("#")[0]}function Dl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function lu(t,e,n){return Ff.apply(this,arguments)}function Ff(){return(Ff=ce((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=Dl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var nm=t=>t instanceof Error,Rf={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}},im=Rf.info;function Tf(t){if(wt(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=>Tf(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function ms(t){var e=[];for(var n in t){var i=t[n];et(i)||C(i)||e.push({key:n,value:Tf(i)})}return e}function rm(t,e){var n=Rf[t.level||"info"]||im,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),q(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),q(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:ms(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 Mf(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 $f(t,e,n,i){return{resourceLogs:[{resource:{attributes:ms(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let sm=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:rm(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 ce((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return ce((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Kt.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=$f(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(Kt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return ce((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Kt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Kt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Mf(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Kt.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(Kt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Dl((()=>{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(Kt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return ce((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield lu(n,t):yield n}))()}flushWithTimeout(t){var e=this;return ce((function*(){var n=e.flush();yield lu(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 Uo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function cu(t){return String(t)+"000000"}function uu(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 om=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=ce((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=uu(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(Uo.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,Uo)]+=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=Dl((()=>{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 ce((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:ms(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=cu(Date.now()),n=new Map;for(var i of t.values()){var r,s=uu(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=ms((r=i.attributes)!==null&&r!==void 0?r:{}),l=cu(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:Uo})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var Br,du,Ho;function am(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Ho&&n.length===du||(du=n.length,Ho=n.reduce(((i,r)=>{Br||(Br={});var s=Br[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,Br[r]=[u,c];break}}return i}),{})),Ho}}class lm{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 ce((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 ce((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:am(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 yi="?";function Aa(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?yi:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Lf=(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]:yi,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},cm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,um=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,dm=/\((\S*)(?::(\d+))(?::(\d+))\)/,fm=(t,e)=>{var n=cm.exec(t);if(n)return Aa(e,n[1],yi,+n[2],+n[3]);var i=um.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=dm.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Lf(i[1]||yi,i[2]);return Aa(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},hm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,pm=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,gm=(t,e)=>{var n=hm.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=pm.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]||yi,o=Lf(s,r);return Aa(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},fu=/\(error: (.*)\)/;class mm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=Q(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 ds(e,"DOMException")}isDOMError(e){return ds(e,"DOMError")}}class vm{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 cf(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 ym{constructor(){}match(e){return!!ds(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 Q(e.message)&&e.message.length>0}pe(e){var n=e;if(Q(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 _m=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class wm{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(_m);return r&&(n=r[1],i=r[2]),[n,i]}}var bm=["fatal","error","warning","log","info","debug"];function Nf(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 Em{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 $l(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: "+Nf(e)}isSeverityLevel(e){return Q(e)&&!xa(e)&&bm.indexOf(e)>=0}getStack(e){try{return Q(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:Q(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(nm(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Sm{match(e){return $l(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Nf(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class xm{match(e){return lf(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 Im{match(e){return ds(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!$l(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 lf(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 vs="$message",ys="$timestamp",km=new Set([vs,ys]),Wo={enabled:!0,max_bytes:32768};function _s(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Wo.enabled,max_bytes:Pm(t.max_bytes,Wo.max_bytes)}:k({},Wo)}class Cm{constructor(e){this.Ke=[],this.Je=0,this.Ne=_s(e)}setConfig(e){this.Ne=_s(e),this.Xe()}add(e){var n=(function(r){var s;try{s=sf(r)}catch{return}try{var o=JSON.parse(s);if(!me(o))return;var a=o,l=a[vs],u=a[ys];return!Q(l)||l.trim().length===0||!Q(u)&&!Ae(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 Pm(t,e){if(!Ae(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Of=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(E&&(oe.DEBUG||E.POSTHOG_DEBUG||n)&&!C(E.console)&&E.console){for(var s=("__rrweb_original__"in E.console[r])?E.console[r].__rrweb_original__:E.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)=>Of(t+" "+r,s)};return i},A=Of("[PostHog.js]"),ve=A.createLogger,Am=ve("[ExternalScriptsLoader]"),qo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Am.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)};N.__PosthogExtensions__=N.__PosthogExtensions__||{},N.__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)}qo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");qo(t,o,n)}},N.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);qo(t,i,n)};oe.DEBUG=!1,oe.LIB_VERSION="1.415.7",oe.LIB_NAME="web";var Bf="$people_distinct_id",dr="$device_id",zo="$device_model",zi="__alias",Vi="__timers",Fa="$autocapture_disabled_server_side",Ra="$heatmaps_enabled_server_side",Ta="$exception_capture_enabled_server_side",Ma="$error_tracking_suppression_rules",$a="$error_tracking_capture_extension_exceptions",La="$web_vitals_enabled_server_side",jl="$dead_clicks_enabled_server_side",Ul="$product_tours_enabled_server_side",Na="$web_vitals_allowed_metrics",jn="$session_recording_remote_config",Df="$replay_sample_rate",jf="$replay_override_sampling",Uf="$replay_override_linked_flag",Hf="$replay_override_url_trigger",Wf="$replay_override_event_trigger",li="$sesid",Hl="$session_is_sampled",$n="$enabled_feature_flags",Gi="$active_feature_flags",Zr="$early_access_features",Oa="$feature_flag_details",Ki="$feature_flag_payloads",Xr="$feature_flag_request_id",ws="$minimal_flag_called_events",Pt="$override_feature_flags",Ln="$override_feature_flag_payloads",Gt="$stored_person_properties",Nn="$stored_group_properties",Ba="$surveys",bs="$surveys_loaded_at",Da="$surveys_activated",Qr="$surveys_activated_session",es="$surveys_activated_timestamps",Yi="ph_product_tours",Bn="$flag_call_reported",Ji="$flag_call_reported_session_id",ts="$feature_flag_errors",nr="$feature_flag_evaluated_at",ft="$user_state",ja="$client_session_props",Ua="$capture_rate_limit",Ha="$initial_campaign_params",Wa="$initial_referrer_info",Es="$initial_person_info",Ss="$epp",Dr="$posthog_cookieless",qf="$cookieless_mode",zf="$sdk_debug_extensions_init_method",Vf="$sdk_debug_extensions_init_time_ms",Gf="$sdk_debug_recording_script_not_loaded",Wl="PostHog loadExternalDependency extension not found.",On="on_reject",Xt="always",ei="anonymous",Pn="identified",qa="identified_only",xs="visibilitychange",Is="beforeunload",si="$pageview",Vo="$pageleave",Go="$identify",hu="$groupidentify";function jr(t,e){U(t)&&t.forEach(e)}function ae(t,e){if(!q(t))if(U(t))t.forEach(e);else if(jg(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)af.call(t,n)&&e(t[n],n)}var ge=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 ns(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 pu=function(t){try{return t()}catch{return}},Fm=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)}}},ql=function(t){var e={};return ae(t,(function(n,i){(Q(n)&&n.length>0||Ae(n))&&(e[i]=n)})),e},Rm=["herokuapp.com","vercel.app","netlify.app"];function Tm(t){var e=t?.hostname;if(!Q(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Rm)if(n===i)return!1;return!0}function we(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 za(t){return t.name==="ph_toolbar_internal"}var Kf=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 Ae(t)&&isFinite(t)&&Math.floor(t)===t});class ks{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 ks(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 ks(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 Mm{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 ks.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 $m}}var gu,Yf=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};E&&!C(E.crypto)&&crypto.getRandomValues&&(Yf=t=>crypto.getRandomValues(t));class $m{nextUint32(){return this.R.length>this.O||(Yf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Yt=()=>Lm().toString(),Lm=()=>(gu||(gu=new Mm)).generate(),$i="",Nm=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:Kf,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(h,g){if(g===void 0&&(g=F),$i)return $i;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),b="dmn_chk_"+Yt();!$i&&v--;){var w=m.slice(v).join("."),_=b+"=1;domain=."+w+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(b)&&(g.cookie=_+";max-age=0",$i=w)}return $i})(c);if(!f){var p=(h=>{var g=h.match(Nm);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}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}}},Ko=null,ue={N(){if(!et(Ko))return Ko;var t=!0;if(C(E))t=!1;else try{var e="__mplssupport__";ue.F(e,"xyz"),ue.P(e)!=='"xyz"'&&(t=!1),ue.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Ko=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return E?.localStorage.getItem(t)}catch(e){ue.j(e)}return null},H(t){try{return JSON.parse(ue.P(t))||{}}catch{}return null},F(t,e){try{return E?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ue.j(n)}return!1},q(t){try{E?.localStorage.removeItem(t)}catch(e){ue.j(e)}}},Om=[dr,"distinct_id",li,Hl,Ss,Es,ft],Ur={},Bm={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>Ur[t]||null,H:t=>Ur[t]||null,F:(t,e)=>(Ur[t]=e,!0),q(t){delete Ur[t]}},An=null,xe={N(){if(!et(An))return An;if(An=!0,C(E))An=!1;else try{var t="__support__";xe.F(t,"xyz"),xe.P(t)!=='"xyz"'&&(An=!1),xe.q(t)}catch{An=!1}return An},j(t){A.error("sessionStorage error: ",t)},P(t){try{return E?.sessionStorage.getItem(t)}catch(e){xe.j(e)}return null},H(t){try{return JSON.parse(xe.P(t))||null}catch{}return null},F(t,e){try{return E?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){xe.j(n)}return!1},q(t){try{E?.sessionStorage.removeItem(t)}catch(e){xe.j(e)}}};class Dm{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===Xt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===On}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 Do(e)?1:j(qg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?ue:Qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Qt:ue;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Do(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[qe?.doNotTrack,qe?.msDoNotTrack,N.doNotTrack].some((e=>Do(e)))}}function Jf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Ue(i))return e;try{var r=i(e);return Q(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var Zf="__POSTHOG_TOOLBAR__",jm=1,Um=3,Hm=11;function mu(t){return t instanceof Element&&(t.id===Zf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function bn(t){return!!t&&t.nodeType===jm}function rt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Xf(t){return!!t&&t.nodeType===Um}function Qf(t){return!!t&&t.nodeType===Hm&&bn(t.host)}var eh=1e3;function zl(t){return t?Zs(t).split(/\s+/):[]}function vu(t,e){var n=(function(i){var r,s=E==null||(r=E.location)==null?void 0:r.href;return C(s)?void 0:Jf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function Cs(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return zl(e)}function th(t){return q(t)?null:Zs(t).split(/(\s+)/).filter((e=>ir(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function fr(t){var e="";return Ga(t)&&!sh(t)&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;Xf(n)&&n.textContent&&(e+=(i=th(n.textContent))!==null&&i!==void 0?i:"")})),Zs(e)}function Yo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Vl=["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 nh(t){var e=t.parentNode;return!(!e||!bn(e))&&e}var Wm=[".ph-no-autocapture","[data-ph-no-autocapture]"],ih=["next","previous","prev",">","<"],qm=[...ih,"+","-","−","–"],yu=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,_u=[".ph-no-rageclick",".ph-no-capture"],zm=["","text","search","email","password","url","tel","number"];function wu(t,e){if(!E||Gl(t))return!1;var n,i,r,s,o;if(wt(e)?(n=!!e&&_u,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:_u,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!bn(l))&&(!!rt(l,"textarea")||(rt(l,"input")?j(zm,(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=rh(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=ih;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,p=d.ariaLabel;return c.some((h=>yu(f,h)||yu(p,h)))}))})(i,a.map((l=>{var u;return{safeText:fr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!Va(a,n)}var Gl=t=>!t||rt(t,"html")||!bn(t),rh=(t,e)=>{if(!E||Gl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!rt(r,"body");)if(Qf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=nh(r);if(!s)break;if(e||Vl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=E.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function Ga(t){for(var e=new Set,n=0,i=t;i.parentNode&&!rt(i,"body");i=i.parentNode){if(n++>=eh||e.has(i))return!1;e.add(i);var r=Cs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(Cs(t),"ph-include"))return!0;var s=t.type||"";if(Q(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!Q(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 sh(t){return!!(rt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||rt(t,"select")||rt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var bu=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}))$"),Eu=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Vm=[16,15,14,13],Gm=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Su=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),xu=/[0-9A-Za-z_]/;function Km(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 ir(t,e){if(e===void 0&&(e=!0),q(t))return!1;if(Q(t)){t=Zs(t);var n=e?bu.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Eu.lastIndex=0;s=Eu.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Vm){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(bu.test(d)&&Km(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Gm.test(t):(function(r){var s;for(Su.lastIndex=0;s=Su.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&xu.test(o)&&xu.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Iu(t){var e=fr(t);return ir(e=(e+" "+oh(t)).trim())?e:""}function oh(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=fr(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+oh(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function ku(t){return t.replace(/"|\\"/g,'\\"')}function Ym(t){var e=t.attr__class;if(e)return U(e)?e:zl(e)}var Hr=ve("[Dead Clicks]"),Jm=()=>!0,Zm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(jl)),i=t.instance.config.capture_dead_clicks;return wt(i)?i:!!me(i)||n};class Cu{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({[jl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=N.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Hr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=N.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=me(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=N.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),Hr.info("starting...")}}else Hr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Hr.info("stopping..."))}}var Jo=ve("[SegmentIntegration]"),ah="posthog-js";function lh(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,p,h,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,b=((d=c.exception)==null?void 0:d.values)||[],w=b.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=b[0])==null?void 0:f.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=b[0])==null?void 0:h.value)||c.message,$sentry_exception_type:(g=b[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 Xm{constructor(e,n,i,r,s,o){this.name=ah,this.setupOnce=function(a){a(lh(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Pu{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=E?.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?Rt(a/o,0,1,A):1,p=o>1?Rt(l/o,0,1,A):1,h=u>1?Rt(c/u,0,1,A):1,g=u>1?Rt(d/u,0,1,A):1;r=ge(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Zo=["flags","surveys"],Qm={[Bf]:{exposure:"hidden"},[zi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Vi]:{exposure:"hidden"},[Fa]:{exposure:"event"},[Ra]:{exposure:"hidden"},[Ta]:{exposure:"event"},[Ma]:{exposure:"hidden"},[$a]:{exposure:"event"},[La]:{exposure:"event"},[jl]:{exposure:"event"},[Ul]:{exposure:"hidden"},[Na]:{exposure:"event"},[jn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[li]:{exposure:"hidden"},[Hl]:{exposure:"event"},[Df]:{exposure:"event",shouldSkipFromEventProperties:t=>et(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"},[$n]:{exposure:"hidden",storageGroup:"flags"},[Gi]:{exposure:"hidden",storageGroup:"flags"},[Zr]:{exposure:"hidden"},[Oa]:{exposure:"hidden",storageGroup:"flags"},[Ki]:{exposure:"hidden",storageGroup:"flags"},[Xr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ws]:{exposure:"hidden",storageGroup:"flags"},[Pt]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Gt]:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[Ba]:{exposure:"hidden",storageGroup:"surveys"},[bs]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Da]:{exposure:"event"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Yi]:{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"},[Bn]:{exposure:"hidden"},[Ji]:{exposure:"hidden"},[ts]:{exposure:"hidden"},[nr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[Ua]:{exposure:"hidden"},[Ha]:{exposure:"hidden"},[Wa]:{exposure:"hidden"},[Es]:{exposure:"hidden"},[Ss]:{exposure:"hidden"},[jf]:{exposure:"event"},[Uf]:{exposure:"event"},[Hf]:{exposure:"event"},[Wf]:{exposure:"event"},[zf]:{exposure:"event"},[Vf]:{exposure:"event"},[Gf]:{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"}},ev=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Fn=t=>{var e=Qm[t];if(e)return e;for(var n of ev){var i=n[1];if(t.indexOf(n[0])===0)return i}},ci=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return sf(t)}},Ps=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},_i=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," ")},hr=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},ch=(t,e)=>t>=e&&tf(),uh=(t,e,n,i)=>{if(t===0){if(tf()){var r=e+1;return r===n&&i(),r}return e}return 0},Wr="https?://(.*)",wi=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],tv=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...wi],pr="",nv=["li_fat_id"];function dh(t,e,n){if(!F)return{};var i,r=e?[...wi,...n||[]]:[],s=fh(hr(F.URL,r,pr),t),o=(i={},ae(nv,(function(a){var l=Kf(a);i[a]=l||null})),i);return ge(o,s)}function fh(t,e){var n=tv.concat(e||[]),i={};return ae(n,(function(r){var s=_i(t,r);i[r]=s||null})),i}function hh(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(!et(e)){i.$search_engine=e;var r=F?_i(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Au(){return navigator.language||navigator.userLanguage}var Fs="$direct";function ph(){return F?.referrer||Fs}function gh(t,e,n){n===void 0&&(n=!1);var i=t?[...wi,...e||[]]:[],r=n?wn(_e?.href):_e?.href,s=r?.substring(0,1e3);return{r:ph().substring(0,1e3),u:s?hr(s,i,pr):void 0}}function mh(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?wn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==Fs?Fs:(n=Ps(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=Ps(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=fh(s);ge(o,l)}if(i){var u=hh(i);ge(o,u)}return o}function vh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function iv(){try{return new Date().getTimezoneOffset()}catch{return}}var rv={flags:nr,surveys:bs},sv=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ti="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(),E){var r=()=>this.flush();we(E,"beforeunload",r,{capture:!1}),we(E,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Ae(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){sv.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=[...Om,...o];return k({},ue,{H(u){try{var c={};try{c=Qt.H(u)||{}}catch{}var d,f=JSON.parse(ue.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];et(g)||g===""||(p[h]=g)}d=ge(f,p)}else d=ge(c,f);return ue.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=ue.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Qt.F(u,m,d,f,p,h)}catch(v){ue.j(v)}return g},q(u,c){try{E?.localStorage.removeItem(u),Qt.q(u,c)}catch(d){ue.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&ue.N()?(n=ue,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&xe.N()?n=xe:s==="memory"?n=Bm: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 ae(this.props,((n,i)=>{var r=Fn(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=ge({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Zo){var n=ue.H(this.Si(e));if(n&&!rn(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ge(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Fn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=rv[e];if(!i)return!1;var r=n[i],s=this.props[i];return Ae(r)&&Ae(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Fn(e))==null?void 0:n.storageGroup:void 0,r=i?ue.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,ti))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,ti),Zo)){var s,o=i[r];(!rn(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(ue,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ae(this.props,((i,r)=>{var s,o=(s=Fn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===ti)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ae(e,((r,s)=>{var o;i[s]=(o=Fn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===ti||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!==ti&&(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 Zo)ue.q(this.Si(r));i?delete this.ci[ti]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(me(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ae(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(me(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ae(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||me(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=dh(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);rn(ql(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?hh(e):{})}update_referrer_info(){var e;this.register_once({$referrer:ph(),$referring_domain:F!=null&&F.referrer&&((e=Ps(F.referrer))==null?void 0:e.host)||Fs},void 0)}set_initial_person_info(){this.props[Ha]||this.props[Wa]||this.register_once({[Es]:gh(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={};ae([Wa,Ha],(r=>{var s=this.props[r];s&&ae(s,(function(o,a){e["$initial_"+Sa(a)]=o}))}));var n=this.props[Es];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=mh(r,s),a={};return ae(o,(function(l,u){a["$initial_"+Sa(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ge(e,i)}return e}safe_merge(e){return ae(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,p)=>f===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Vi]||{};i[e]=n,this.Pi(Vi,i),this.save()}remove_event_timer(e){var n=this.props[Vi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Vi,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=Fn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Fn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function qr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Ue(n.then)&&n.then(void 0,(()=>{}))}}}}var He={GZipJS:"gzip-js",Base64:"base64"},Li={Activation:"events",Cancellation:"cancelEvents"},Qo={Popover:"popover",API:"api",Widget:"widget"},en={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ea={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},Ka={Popover:"popover",Inline:"inline"},ov={SHOWN:"product tour shown"},Fu={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Ru=ve("[RateLimiter]");class av{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=>{Ru.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Ru.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(Ua))!==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=(Ae(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(Ua,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")&&_e!=null&&_e.pathname)return""+((e=_e.origin)!==null&&e!==void 0?e:"")+_e.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 mn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void mn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return mn.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){mn.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||mn.warn("Failed to fetch remote config from PostHog."):mn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){mn.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){mn.error("Error loading feature flags",r)}}}var pt=Uint8Array,Qe=Uint16Array,bi=Uint32Array,Kl=new pt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Yl=new pt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Tu=new pt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_h=function(t,e){for(var n=new Qe(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]},wh=_h(Kl,2),Ya=wh[1];wh[0][28]=258,Ya[258]=28;for(var Mu=_h(Yl,0)[1],bh=new Qe(32768),be=0;32768>be;++be){var ni=(43690&be)>>>1|(21845&be)<<1;bh[be]=((65280&(ni=(61680&(ni=(52428&ni)>>>2|(13107&ni)<<2))>>>4|(3855&ni)<<4))>>>8|(255&ni)<<8)>>>1}var rr=function(t,e,n){for(var i=t.length,r=0,s=new Qe(e);i>r;++r)++s[t[r]-1];var o,a=new Qe(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Qe(i),r=0;i>r;++r)o[r]=bh[a[t[r]-1]++]>>>15-t[r];return o},Vn=new pt(288);for(be=0;144>be;++be)Vn[be]=8;for(be=144;256>be;++be)Vn[be]=9;for(be=256;280>be;++be)Vn[be]=7;for(be=280;288>be;++be)Vn[be]=8;var Rs=new pt(32);for(be=0;32>be;++be)Rs[be]=5;var lv=rr(Vn,9),cv=rr(Rs,5),Eh=function(t){return(t/8>>0)+(7&t&&1)},Sh=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Qe?Qe:t instanceof bi?bi:pt)(n-e);return i.set(t.subarray(e,n)),i},qt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ni=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},ta=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 pt(0),0];if(r==1){var o=new pt(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 p=new Qe(f+1),h=Ja(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var b=s[i].s;if(e>=p[b])break;g+=v-(1<>>=m;g>0;){var w=s[i].s;e>p[w]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new pt(p),h]},Ja=function(t,e,n){return t.s==-1?Math.max(Ja(t.l,e,n+1),Ja(t.r,e,n+1)):e[t.s]=n},$u=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Qe(++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]},Oi=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Za=function(t,e,n){var i=n.length,r=Eh(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)},Lu=function(t,e,n,i,r,s,o,a,l,u,c){qt(e,c++,n),++r[256];for(var d=ta(r,15),f=d[0],p=d[1],h=ta(s,15),g=h[0],m=h[1],v=$u(f),b=v[0],w=v[1],_=$u(g),x=_[0],I=_[1],T=new Qe(19),S=0;b.length>S;++S)T[31&b[S]]++;for(S=0;x.length>S;++S)T[31&x[S]]++;for(var P=ta(T,7),R=P[0],L=P[1],$=19;$>4&&!R[Tu[$-1]];--$);var O,J,G,M,K=u+5<<3,ie=Oi(r,Vn)+Oi(s,Rs)+o,B=Oi(r,f)+Oi(s,g)+o+14+3*$+Oi(T,R)+(2*T[16]+3*T[17]+7*T[18]);if(ie>=K&&B>=K)return Za(e,c,t.subarray(l,l+u));if(qt(e,c,1+(ie>B)),c+=2,ie>B){O=rr(f,p),J=f,G=rr(g,m),M=g;var X=rr(R,L);for(qt(e,c,w-257),qt(e,c+5,I-1),qt(e,c+10,$-4),c+=14,S=0;$>S;++S)qt(e,c+3*S,R[Tu[S]]);c+=3*$;for(var fe=[b,x],se=0;2>se;++se){var ee=fe[se];for(S=0;ee.length>S;++S)qt(e,c,X[Pe=31&ee[S]]),c+=R[Pe],Pe>15&&(qt(e,c,ee[S]>>>5&127),c+=ee[S]>>>12)}}else O=lv,J=Vn,G=cv,M=Rs;for(S=0;a>S;++S)if(i[S]>255){var Pe;Ni(e,c,O[257+(Pe=i[S]>>>18&31)]),c+=J[Pe+257],Pe>7&&(qt(e,c,i[S]>>>23&31),c+=Kl[Pe]);var ke=31&i[S];Ni(e,c,G[ke]),c+=M[ke],ke>3&&(Ni(e,c,i[S]>>>5&8191),c+=Yl[ke])}else Ni(e,c,O[i[S]]),c+=J[i[S]];return Ni(e,c,O[256]),c+J[256]},uv=new bi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),dv=(function(){for(var t=new bi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),na=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function fv(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=dv[255&p^f[h]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,p,h,g,m){var v=d.length,b=new pt(h+v+5*(1+Math.floor(v/7e3))+g),w=b.subarray(h,b.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=Za(w,_,d.subarray(x,I)):(w[x]=!0,_=Za(w,_,d.subarray(x,v)))}else{for(var T=uv[f-1],S=T>>>13,P=8191&T,R=(1<x;++x){var Pe=G(x),ke=32767&x,je=$[Pe];if(L[ke]=je,$[Pe]=ke,x>=se){var St=v-x;if((B>7e3||fe>24576)&&St>423){_=Lu(d,w,0,M,K,ie,X,fe,ee,x-ee,_),fe=B=X=0,ee=x;for(var ye=0;286>ye;++ye)K[ye]=0;for(ye=0;30>ye;++ye)ie[ye]=0}var tt=2,xt=0,Cn=P,Le=ke-je&32767;if(St>2&&Pe==G(x-Le))for(var Re=Math.min(S,St)-1,Dt=Math.min(32767,x),Zn=Math.min(258,St);Dt>=Le&&--Cn&&ke!=je;){if(d[x+tt]==d[x+tt-Le]){for(var Ke=0;Zn>Ke&&d[x+Ke]==d[x+Ke-Le];++Ke);if(Ke>tt){if(tt=Ke,xt=Le,Ke>Re)break;var Xn=Math.min(Le,Ke-2),jt=0;for(ye=0;Xn>ye;++ye){var Ut=x-Le+ye+32768&32767,ut=Ut-L[Ut]+32768&32767;ut>jt&&(jt=ut,je=Ut)}}}Le+=(ke=je)-(je=L[ke])+32768&32767}if(xt){M[fe++]=268435456|Ya[tt]<<18|Mu[xt];var Ht=31&Ya[tt],Fi=31&Mu[xt];X+=Kl[Ht]+Yl[Fi],++K[257+Ht],++ie[Fi],se=x+tt,++B}else M[fe++]=d[x],++K[d[x]]}}_=Lu(d,w,!0,M,K,ie,X,fe,ee,x-ee,_)}return Sh(b,0,h+Eh(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var p=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&na(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),na(u,c-8,n.d()),na(u,c-4,i),u}var hv=!!wa||!!Ml,xh="text/plain",is=!1,Ih=(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:"")},Qs=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("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return ae(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},ia=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===He.GZipJS){var i=fv((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new pt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new pt(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Sh(c,0,d)})(ci(e)),{mtime:0});return{contentType:xh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===He.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(ci(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:ci(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=ci(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},kh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Qs(t.url,{compression:He.Base64}),encodedBody:ia(k({},t,{compression:He.Base64,Ji:void 0}))}:{url:Ih(t.url,"compression"),encodedBody:ia(k({},t,{compression:void 0,Ji:void 0}))};try{e=ia(t)}catch(r){if(tu(t.compression,_i(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&tu(t.compression,_i(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?ba(new Uint8Array(n)):ArrayBuffer.isView(n)&&ba(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(is=!0,i()):{url:t.url,encodedBody:e}},Ch=t=>{try{return kh(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},pv=(function(){var t=ce((function*(e){var n=ci(e.data),i=yield(function(s,o,a){return Ea.apply(this,arguments)})(n,oe.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:xh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),gv=/Failed to fetch|NetworkError|Load failed/i,Ph=t=>t?.name==="TypeError"&&gv.test(t?.message||""),Ah=t=>{var e=Ch(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ae(t.headers,(function(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Yc){var d=new Yc;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||Ph(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;Ml(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(h){u&&clearTimeout(u.timeout),f(h)}}},Xa=t=>{try{var e,n=kh(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(qe.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 Xa(k({},t,{data:d(u.slice(0,c))})),void Xa(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Ah(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Nu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Qs(n===He.GZipJS?Ih(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===He.GZipJS?{}:{compression:n}))},rs=[];Ml&&rs.push({transport:"fetch",method:Ah}),wa&&rs.push({transport:"XHR",method(t){var e=Ch(t);if(e){var n=new wa,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ae(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)}}}),qe!=null&&qe.sendBeacon&&rs.push({transport:"sendBeacon",method:Xa});var Qa=3e3;class mv{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Rt(n?.flush_interval_ms||Qa,250,5e3,A.createLogger("flush interval"),Qa),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)&&ae(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 ae(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 vv=["retriesPerformedSoFar"];class yv{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(E)&&"onLine"in E.navigator&&(this.dr=E.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},we(E,"online",this.vr),we(E,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=nf(e,vv);Vt(n)&&(i.url=Qs(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(E)||(this.vr&&(E.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(E.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 _v{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(){we(E,"scroll",this.yr,{capture:!0}),we(E,"scrollend",this.yr,{capture:!0}),we(E,"resize",this.yr)}scrollElement(){if(!this._r)return E?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=E?.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 E?e==="y"?E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop||0:E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var wv=t=>gh(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Ou{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ja]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||wv,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ja]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?mh(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 ae(ql(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Sa(i)]=n})),e}}class Jl{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 Bi=ve("[SessionId]");class Bu{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 Jl,this.Lr=(u,c)=>!(!Vt(u)||!Vt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Xt)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||Yt,this.Nr=i||Yt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Bi.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=xe.H(this.jr),a=xe.H(this.Br);o&&!a?this.Or=o:xe.q(this.jr),xe.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){Bi.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&&xe.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&xe.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?xe.H(this.jr):null}Zr(e){var n=this.Pr;return!et(n)&&!et(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({[li]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Vt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(li):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!et(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({[li]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Vt(e)?e:0,i=Vt(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[li];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&&E&&(E.removeEventListener(Is,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&xe.q(this.Br)},we(E,Is,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Xt)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=Vt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||Bi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),Bi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Bi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Vt(a)&&e&&!u?a:i,v=Vt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var b={noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(s,l,b))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Fh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&iu(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>iu(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Rh(){return(Rh=ce((function*(){var t=qe?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return Q(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 Ts=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 ra(t,e,n){return ci({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Th={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=>Ts(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Ts(n,i))))),icontains:(t,e)=>e.map(zr).some((n=>t.map(zr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(zr).every((n=>t.map(zr).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 Mh(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||et(r))return!1;var s=[String(r)],o=Th[i.operator];return!!o&&o(i.values,s)}))}var el="custom",Du="i.posthog.com",bv=/^\/static\//;class Ev{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("."+Du,".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":el),this.en[this.apiHost]}rn(e){if(bv.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===el)return this.apiHost+n;var r=Du+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function $h(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var te=ve("[Surveys]"),Lh="seenSurvey_",Nh=t=>{try{var e=(n=>((i,r)=>""+Lh+(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){te.error("Failed to persist survey seen state",n)}},Sv=[Qo.Popover,Qo.Widget,Qo.API],xv={ignoreConditions:!1,ignoreDelay:!1,displayType:Ka.Popover},Iv=ve("[PostHog ExternalIntegrations]"),kv={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Cv{constructor(e){this._instance=e}ai(e,n){var i;(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return Iv.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=N.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(kv[l],(()=>{var c;(c=N.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=N.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=N.__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 Pv{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return ce((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&&Ue(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 Av{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 ju="extensionsRemoteConfig";class Fv{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Av(e),this.onEvent=n=>qr(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 qr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(ju,i);return this.un&&i(this.un),qr(r)},this.vn=new Pv(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(dr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(dr);return typeof e=="string"?e:void 0}get library(){return{name:oe.LIB_NAME,version:oe.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 ce((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 qr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(ju,e))}sendRequest(e,n){var i=this;return ce((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?Qs(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 sr={},sa=0,Ms=()=>{},Uu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Di="Surveys module not available",Hu="sanitize_properties is deprecated. Use before_send instead",Oh="Invalid value for property_denylist config: ",Rv=["token","distinct_id",qf],oi="posthog",Bh=!hv&&Je?.indexOf("MSIE")===-1&&Je?.indexOf("Mozilla")===-1,oa=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:Tm(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Ms,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:_e&&Q(_e?.search)&&_e.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:(E==null||(e=E.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:qa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Qa},error_tracking:{},_onCapture:Ms},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:qm,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))},Tv=[["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"]],Wu=t=>{var e={};for(var n of Tv){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=ge({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),Q(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(Oh+t.property_denylist)),s};class Mv{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 nt{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===Xt||this.config.cookieless_mode===On&&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 Mv,this.mn=!1,this.version=oe.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Jl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=oa(),this.SentryIntegration=Xm,this.sentryIntegration=i=>(function(r,s){var o=lh(r,s);return{name:ah,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 _v(this),this.pageViewManager=new Pu(this),this.rateLimiter=new av(this),this.requestRouter=new Ev(this),this.consent=new Dm(this),this.externalIntegrations=new Cv(this);var n=(e=nt.__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=Q(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=Q(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!==oi){var r,s=(r=sr[i])!==null&&r!==void 0?r:new nt;return s._init(e,n,i),sr[i]=s,sr[oi][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=Q(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=oa(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=oa(n.defaults),u=Wu(n),c=ge({},l,u,{name:i,token:a});me(l.rageclick)&&me(u.rageclick)&&(c.rageclick=ge({},l.rageclick,u.rageclick)),me(l.session_recording)&&me(u.session_recording)&&(c.session_recording=ge({},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:He.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&&xe.N()){var f=xe.H(this.bn);U(f)&&f.forEach((I=>{Q(I)&&this.yn.add(I)}))}else xe.q(this.bn);var p=k({},this.persistence.props),h=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new mv((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new yv(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Bu(this),this.sessionPropsManager=new Ou(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.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)),oe.DEBUG=oe.DEBUG||this.config.debug,oe.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p,s:h}),!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(),b=this.persistence.get_property(ft);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===ei)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Pn)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 w=this.config.get_device_id(Yt()),_=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(ft,n.bootstrap.isIdentifiedID?Pn:ei),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Dr,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Yt());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ft,ei)}return we(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var S=I.config.segment;if(!S)return T();(function(P,R){var L=P.config.segment;if(!L)return R();var $=J=>{var G=()=>J.anonymousId()||Yt();P.config.get_device_id=G,J.id()&&(P.register({distinct_id:J.id(),$device_id:G()}),P.persistence.set_property(ft,Pn)),R()},O=L.user();"then"in O&&Ue(O.then)?O.then($):$(O)})(I,(()=>{S.register((P=>{typeof Promise<"u"&&Promise.resolve||Jo.warn("This browser does not have Promise support, and can not use the segment integration");var R=(L,$)=>{if(!$)return L;L.event.userId||L.event.anonymousId===P.get_distinct_id()||(Jo.info("No userId set, resetting PostHog"),P.reset()),L.event.userId&&L.event.userId!==P.get_distinct_id()&&(Jo.info("UserId set, identifying with PostHog"),P.identify(L.event.userId));var O=P.calculateEventProperties($,L.event.properties);return L.event.properties=Object.assign({},O,L.event.properties),L};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:L=>R(L,L.event.event),page:L=>R(L,si),identify:L=>R(L,Go),screen:L=>R(L,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),Ue(this.config._onCapture)&&this.config._onCapture!==Ms&&(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 Rh.apply(this,arguments)})().then((I=>{I&&this.register({[zo]:I})})).catch(Ms),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=nt.__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)),Ue(this.featureFlags.onReloading)&&Ue(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({},nt.__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,Zm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[zf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Vf]: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,He.GZipJS)?He.GZipJS:j(r.supportedCompression,He.Base64)?He.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:qa}),(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&&_e!=null&&_e.hostname){var e=_e.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 yh(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()&&jr(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(Vo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(Vo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Bh?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=He.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((b=>k({},b,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Nu(o.url,o.method,o.compression,o.timestampMode);var p=rs.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var b=0;m.length>b;b++)if(m[b].transport===f)return m[b]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){Ph(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===He.GZipJS&&$g&&typeof Promise<"u"&&!is?pv(o).then((m=>{g(m)})).catch((m=>{if(nu(m))return is=!0,void g(k({},o,{compression:void 0,url:Nu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var b="name"in v?String(v.name):"";return nu(v)||b===rf})(m)&&(is=!0),g(o)})):h(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){sa++;try{var n,i=[],r=[],s=[];jr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(Ue(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&&Ue(this[n])?s.push(a):r.push(a)}));var o=function(a,l){jr(a,(function(u){try{if(U(u[0])){var c=l;ae(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{sa--}}push(e){if(sa>0&&U(e)&&Q(e[0])){var n=nt.prototype[e[0]];Ue(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)&&Q(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&&!Q(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,p=au(i?.uuid,Yt),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===si&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(ws)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,b,w,_=g?void 0:this.Vn(i?.$set_once,e!==hu,e===Go);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=$=>Q($)?$.slice(0,s):$,l=new Set,h=(function $(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var G;if(l.add(O),U(O))G=[],jr(O,(K=>{G.push($(K))}));else{var M={};ae(O,((K,ie)=>{l.has(K)||(M[ie]=$(K))})),G=M}return G}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function($,O){O===void 0&&(O=[]);var J={},G=M=>{$[M]!==void 0&&(J[M]=$[M])};return Lg.forEach(G),O.forEach(G),J})(h.properties,Rv)),e===en.DISMISSED||e===en.SENT){var x=n?.[ea.SURVEY_ID],I=n?.[ea.SURVEY_ITERATION];Nh({id:x,current_iteration:I}),h.$set=k({},h.$set,{[(v={id:x,current_iteration:I},b=e===en.SENT?"responded":"dismissed",w="$survey_"+b+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+b+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===en.SHOWN&&(h.$set=k({},h.$set,{[ea.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===ov.SHOWN){var T=n?.[Fu.TOUR_TYPE];T&&(h.$set=k({},h.$set,{[Fu.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var S=k({},h.properties.$set,h.$set);if(rn(S)||this.setPersonPropertiesForFlags(S),!q(this.config.before_send)){var P=this.Pt(h);if(!P)return;(h=P).uuid=au(h.uuid,Yt)}this.dn.emit("eventCaptured",h);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),L={method:"POST",url:R,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"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(L):this.In.enqueue(L),h}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Fv(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[qf]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!Q(a.distinct_id)&&!Ae(a.distinct_id)||xa(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,S){var P,R,L,$;if(S===void 0&&(S=!1),!Je)return{};var O,J=x?[...wi,...I||[]]:[],G=(function(Zn){for(var Ke=0;su.length>Ke;Ke++){var Xn=su[Ke],jt=Xn[1],Ut=Xn[0].exec(Zn),ut=Ut&&(Ue(jt)?jt(Ut,Zn):jt);if(ut)return ut}return["",""]})(Je),M=G[0],K=G[1],ie=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},B={};C(T)||(B.detectGoogleSearchApp=T);var X={},fe=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,se=(R=navigator)==null?void 0:R.maxTouchPoints,ee=E==null||(L=E.screen)==null?void 0:L.width,Pe=E==null||($=E.screen)==null?void 0:$.height,ke=E?.devicePixelRatio;C(fe)||(X.userAgentDataPlatform=fe),C(se)||(X.maxTouchPoints=se),C(ee)||(X.screenWidth=ee),C(Pe)||(X.screenHeight=Pe),C(ke)||(X.devicePixelRatio=ke);var je,St,ye,tt,xt,Cn,Le,Re,Dt=ge(ql({$os:M,$os_version:K,$browser:Af(Je,navigator.vendor,ie,B),$device:ou(Je),$device_type:(St=Je,ye=X,Re=ou(St),Re===df||Re===uf||Re==="Kobo"||Re==="Kindle Fire"||Re===xf?mi:Re===cr||Re===fi||Re===ur||Re===ka?"Console":Re===hf?"Wearable":Re?lt:ye?.userAgentDataPlatform==="Android"&&((tt=ye?.maxTouchPoints)!==null&&tt!==void 0?tt:0)>0?600>Math.min((xt=ye?.screenWidth)!==null&&xt!==void 0?xt:0,(Cn=ye?.screenHeight)!==null&&Cn!==void 0?Cn:0)/((Le=ye?.devicePixelRatio)!==null&&Le!==void 0?Le:1)?lt:mi:"Desktop"),$timezone:vh(),$timezone_offset:iv()}),{$current_url:hr(S?wn(_e?.href):_e?.href,J,pr),$host:_e?.host,$pathname:_e?.pathname,$raw_user_agent:Je.length>1e3?Je.substring(0,997)+"...":Je,$browser_version:em(Je,navigator.vendor,ie,B),$browser_language:Au(),$browser_language_prefix:(je=Au(),typeof je=="string"?je.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:oe.LIB_NAME,$lib_version:oe.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return oe.SDK_DIST_CHANNEL&&(Dt.$sdk_dist_channel=oe.SDK_DIST_CHANNEL),Dt})(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&&ge(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ge(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===el&&(a.$lib_custom_api_host=this.config.api_host),u=e!==si||s?e!==Vo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=ge(a,u),e===si&&F&&(a.title=F.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}Je&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ae(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var b of this._n.slice())try{ge(v,b())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=ge({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ae(this.config.property_denylist,(function(x){delete a[x]})):A.error(Oh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(A.error(Hu),a=w(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=ge({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(Hu),a=l(a,"$set_once")),n&&(this.mn=!0),rn(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||!xe.N())xe.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?xe.F(this.bn,n):xe.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:Di}),()=>{})}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:Di})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Di})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=xv),(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:Di}}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:Di})}Jn(e){return!e||xa(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Dr?(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(Ae(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(dr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(zi)&&(this.unregister(zi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ft)||ei)===ei,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ft,Pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Go,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=ra(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ft,Pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=ra(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Bn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=ra(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=>Q(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(hu,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var p,h=this.get_property(dr),g=this.get_property(zo),m=this.get_property(jn),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(p=this.persistence)==null||p.register({[jn]: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(ft,ei),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Xt)this.register_once({distinct_id:Dr,$device_id:null},"");else{var b=this.config.get_device_id(Yt());this.register_once({distinct_id:b,$device_id:e?b:h},""),e||C(g)||this.register({[zo]: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 ce((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(Bf)?(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(zi,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(me(e)){var i,r,s,o,a,l,u,c,d,f,p,h;ge(this.config,Wu(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);wt(m)&&(this.config.debug=m),wt(this.config.debug)&&(this.config.debug?(oe.DEBUG=!0,ue.N()&&ue.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(oe.DEBUG=!1,ue.N()&&ue.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){oe.LIB_NAME=e,oe.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:nt.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:oi;return n!==oi&&(n=oi+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ft))===Pn||((n=this.sessionPersistence)==null?void 0:n.get_property(ft))===Pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===qa&&!this._isIdentified()&&rn(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[zi])&&((n=this.persistence)==null||(n=n.props)==null||!n[Ss]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(Ss,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==On)}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!==Xt){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 Bu(this),this.pageViewManager=new Pu(this),this.persistence&&(this.sessionPropsManager=new Ou(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=nt.__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==On&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(Uu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Xt?(this.config.cookieless_mode===On&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===On&&(this.register({distinct_id:Dr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(Uu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Xt||(this.config.cookieless_mode===On?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return qe?Fh(qe,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(si,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(xs,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),we(F,xs,this.kn)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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&&!q(n[i]),l=r in n&&!q(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(q(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Hg),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),q(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Ug(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!rn(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&&q(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=wt(e)&&!e,i=ue.N()&&ue.P("ph_debug")==="true";return!n&&(!!i||e)}}nt.__defaultExtensionClasses={},nt.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]]=Fm(t.prototype[e[n]])})(nt,["identify"]);class qu{constructor(e){this.disabled=e===!1;var n=me(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 aa="$copy_autocapture",la=ve("[AutoCapture]");function ca(t,e){return e.length>t?e.slice(0,t)+"...":e}function $v(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!bn(e));return e}function Lv(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!bn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!rt(f,"body")&&eh>c.length;)if(Qf(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!bn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},b=!1,w=!1;if(ae(c,(S=>{var P=Ga(S);if(rt(S,"a")){var R=S.getAttribute("href");b=!!(P&&R&&ir(R))&&(u?wn(R):R)}j(Cs(S),"ph-no-capture")&&(w=!0),m.push((function($,O,J,G,M){M===void 0&&(M=!1);var K=$.tagName.toLowerCase(),ie={tag_name:K};Vl.indexOf(K)>-1&&!J&&(ie.$el_text=K.toLowerCase()==="a"||K.toLowerCase()==="button"?ca(1024,Iu($)):ca(1024,fr($)));var B=Cs($);B.length>0&&(ie.classes=B.filter((function(ee){return ee!==""}))),ae($.attributes,(function(ee){var Pe;if((!sh($)||["name","id","class","aria-label"].indexOf(ee.name)!==-1)&&(G==null||!G.includes(ee.name))&&!O&&ir(ee.value)&&(!Q(Pe=ee.name)||Pe.substring(0,10)!=="_ngcontent"&&Pe.substring(0,7)!=="_nghost")){var ke=ee.value;ee.name==="class"&&(ke=zl(ke).join(" ")),ie["attr__"+ee.name]=ca(1024,ee.name==="href"&&M?wn(ke):ke)}}));for(var X=1,fe=1,se=$;se=$v(se);)X++,se.tagName===$.tagName&&fe++;return ie.nth_child=X,ie.nth_of_type=fe,ie})(S,s,o,a,u));var L=(function($){if(!Ga($))return{};var O={};return ae($.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var G=J.name.replace("data-ph-capture-attribute-",""),M=J.value;G&&M&&ir(M)&&(O[G]=M)}})),O})(S);ge(v,L)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=rt(t,"a")||rt(t,"button")?Iu(t):fr(t)),b){var _,x;m[0].attr__href=b;var I=(_=Ps(b))==null?void 0:_.host,T=E==null||(x=E.location)==null?void 0:x.host;I&&T&&I!==T&&(h=b)}return{props:ge({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((P=>{var R,L,$="";if(P.tag_name&&($+=P.tag_name),P.attr_class)for(var O of(P.attr_class.sort(),P.attr_class))$+="."+O.replace(/"/g,"");var J=k({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(L=P.nth_of_type)!==null&&L!==void 0?L:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),G={};return ns(J).sort(((M,K)=>M[0].localeCompare(K[0]))).forEach((M=>{var K=M[1];return G[ku(M[0].toString())]=ku(K.toString())})),($+=":")+ns(G).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(S){return S.map((P=>{var R,L,$={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(L=P.attr__href)==null?void 0:L.slice(0,2048),attr_class:Ym(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return ns(P).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>$.attributes[O[0]]=O[1])),$}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var ji=ve("[ExceptionAutocapture]"),zu=()=>{},Nv=ve("[TracingHeaders]"),Rn=ve("[Web Vitals]"),Vu=9e5,Gu="disabled",Ku="lazy_loading",Ui="awaiting_config",Vr="missing_config";ve("[SessionRecording]"),ve("[SessionRecording]");var tl="[SessionRecording]",zt=ve(tl),Ov=ve("[Heatmaps]");function ua(t){return me(t)&&"clientX"in t&&"clientY"in t&&Ae(t.clientX)&&Ae(t.clientY)}var Gr=ve("[Product Tours]"),da=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Ul))},Bv=["$set_once","$set"],It=ve("[SiteApps]"),Yu="Error while initializing PostHog app with config id ";function ii(t,e,n){if(q(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 Dv{constructor(e){this.ns=new Jl,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"||!ii(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=>ii(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&ii((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=>ii(u.text,n.text,n.text_matching||"exact")||ii(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;!q(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=>ii(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||Mh(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 jv{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&&Mh(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===Li.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 Dv(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,Li.Activation),this.ks=this.Ps(e,Li.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,Li.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,Li.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&&(rn(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Ae(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=>Ae(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 Uv extends jv{constructor(e){super(e)}Js(){return Da}Ys(){return Qr}Ms(){return es}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[es]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(es)}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 Ae(r)&&r>0}ra(){return en.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 te}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({[Qr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Qr)}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 $h(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===en.SHOWN?"consume":"ignore":e===en.SHOWN?"persist":e===en.DISMISSED||e===en.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Kr="SDK is not enabled or survey functionality is not yet loaded",Ju="Disabled. Not loading surveys.",Hv=E!=null&&E.location?As(E.location.hash,"__posthog")||As(location.hash,"state"):null,Zu="_postHogToolbarParams",Xu=ve("[Toolbar]"),Qu=ve("[FeatureFlags]");class Wv{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||(Qu.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)||Qu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var ed=ve("[FeatureFlags]"),Tn=ve("[FeatureFlags]",{debugEnabled:!0}),fa=`" failed. Feature flags didn't load in time.`,td="connection_error",nd=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},id=t=>{var e={};for(var n of ns(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},kt=ve("[Error tracking]"),rd="Refusing to render web experiment since the viewer is a likely bot",qv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Ts(e,t),not_regex:(t,e)=>!Ts(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Oe{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Oe.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Oe.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);Q(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];Oe.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())Oe.aa(rd);else if(!this.Ne.disable_web_experiments){if(q(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Oe.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=Oe.getWindowLocation();if(e!=null&&e.search){var n=_i(e?.search,"__experiment_id"),i=_i(e?.search,"__experiment_variant");n&&i&&(Oe.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&&(Oe.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!q(e.conditions)&&Oe.da(e,n)&&Oe.va(e)}static da(e,n){var i;if(q(e.conditions)||q((i=e.conditions)==null?void 0:i.url))return!0;var r=Oe.getWindowLocation();if(r){var s,o,a,l=Jf(n,r.href);return(s=e.conditions)==null||!s.url||qv[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return E?.location}static va(e){var n;if(q(e.conditions)||q((n=e.conditions)==null?void 0:n.utm))return!0;var i=dh();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,h=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&h&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Oe.aa(rd):n!=="control"?i.forEach((r=>{if(r.selector){var s;Oe.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)}))}})):Oe.aa("Control variants leave the page unmodified.")}_is_bot(){return qe&&this._instance?Fh(qe,this.Ne.custom_blocked_useragents):void 0}}var dt=ve("[Conversations]"),Mn="Conversations not available yet.",sd="console",Dh="__posthogHandledLogsRequestError",ha=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Dh]=!0,n},od=t=>!!t&&typeof t=="object"&&t[Dh]===!0,eo={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=ed,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 Wv(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 E&&we(E,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){E?.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=[],E?.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[Gi,Ki,Xr,Pt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa($n);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(nr);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($n))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Ki))!==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:Xc(f),variant:Qc(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(Oa),e=this.Oa(Pt),n=this.Oa(Ln);if(!n&&!e)return t||{};var i=ge({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],p=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Xc(i),variant:Qc(i),payload:Zc(e[n])}}))}getFlagVariants(){var t=this.Oa($n),e=this.Oa(Pt);if(!e)return t||{};for(var n=ge({},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(Ki),e=this.Oa(Ln);if(!e)return t||{};for(var n=ge({},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(Bn)}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(Gt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Nn),timezone:vh()};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({[ts]:[td]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?He.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?td:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[ts]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(p,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return ch(this.Sa,3)}Ua(t){this.Sa=uh(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+fa)}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(Xr)||void 0,u=this.Oa(nr)||void 0,c=this.Oa(Bn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Ji);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Bn]:c,[Ji]:n});else{var h,g,m,v,b,w,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Bn]:c},n?{[Ji]:n}:{}));var S=this.getFeatureFlagDetails(t),P=[...(h=this.Oa(ts))!==null&&h!==void 0?h:[]];C(s)&&P.push("flag_missing");var R={$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(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),C(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var L,$=(w=S==null||(_=S.reason)==null?void 0:_.description)!==null&&w!==void 0?w:S==null||(x=S.reason)==null?void 0:x.code;$&&(R.$feature_flag_reason=$),S!=null&&(I=S.metadata)!=null&&I.id&&(R.$feature_flag_id=S.metadata.id),C(S?.original_variant)&&C(S?.original_enabled)||(R.$feature_flag_original_response=C(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(T=S.metadata)!=null&&T.original_payload&&(R.$feature_flag_original_payload=S==null||(L=S.metadata)==null?void 0:L.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[Bn]:c,[Ji]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Zc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+fa)}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 ce((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"?He.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+fa),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=ed);var c=((I,T)=>{var S=I.flags;return S?k({},I,{featureFlags:Object.fromEntries(Object.keys(S).map((P=>{var R;return[P,(R=S[P].variant)!==null&&R!==void 0?R:S[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((P=>S[P].enabled)).filter((P=>{var R;return(R=S[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=S[P].metadata)==null?void 0:R.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,p=c.featureFlagPayloads;if(f){var h=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Gi]:f,[$n]:m,[ws]:!1}}var b=f,w=p,_=d;if(l!=null&&l.partialResponse)b=k({},s,b),w=k({},o,w),_=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)})));b=k({},s,Object.fromEntries(Object.entries(b).filter((I=>x.has(I[0]))))),w=k({},o,Object.fromEntries(Object.entries(w||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else b=k({},s,b),w=k({},o,w),_=k({},a,_);return k({[Gi]:Object.keys(id(b)),[$n]:b||{},[Ki]:w||{},[Oa]:_||{},[ws]:r.minimalFlagCalledEvents===!0},h?{[Xr]:h}:{},g?{[nr]: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([Pt,Ln]),this.Va(),void Tn.info("All overrides cleared");if(U(t))return this.F({[Pt]:nd(t)}),this.Va(),void Tn.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[Pt]=U(r)?nd(r):r),s&&(i[Ln]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([Pt,Ln]):r===!1?this.q(Pt):s===!1&&this.q(Ln),this.Va(),r===!1?Tn.info("Flag overrides cleared"):r&&Tn.info("Flag overrides set",{flags:r}),void(s===!1?Tn.info("Payload overrides cleared"):s&&Tn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[Pt]:t}),this.Va(),void Tn.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(Zr)||[]).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({[Gi]:Object.keys(id(o)),[$n]:o,[Gt]:k({},this.Oa(Gt)||{},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(Zr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return ce((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({[Zr]: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(Gt)||{},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({[Gt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Gt)||{});t.forEach((i=>{delete n[i]})),this.F({[Gt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Gt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(Nn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[Nn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Nn)||{};this.F({[Nn]:k({},e,{[t]:{}})})}else this.q(Nn)}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}}},zv={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===Ui||this.Ya===Vr?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=Gu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=E==null||(e=E.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 zt.error("started without valid sessionManager"),new Error(tl+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Xt)throw new Error(tl+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&we(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(jn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return E&&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),zt.info("starting")):(this.Ya=Gu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Ui&&this.Ya!==Vr&&(this.Ya=Ku),N!=null&&(e=N.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=N.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return zt.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(Hl),(e=this.Mr)==null||e.unregister(Df)}uo(t,e){if(q(t))return null;var n,i=Ae(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(zt.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;q(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[jn]: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===Ui&&(this.Ya=Vr,zt.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):zt.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(jn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(jn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return zt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!q(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=N.__PosthogExtensions__)==null||!e.initSessionRecording)return zt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Gf]:!0});var r;if(this.Ja||(this.Ja=(r=N.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Vr||this.Ya===Ui?void 0:(this.Ya=Ui,zt.info("persisted remote config is stale, requesting fresh config before starting"),void new yh(this._instance).load());this.Ya=Ku,(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({[Uf]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[jf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Hf:Wf]:!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))}}},Vv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new qu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=me(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(E&&F){var t=n=>{n=n||E?.event;try{this.bo(n)}catch(i){la.error("Failed to capture event",i)}};if(we(F,"submit",t,{capture:!0}),we(F,"change",t,{capture:!0}),we(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||E?.event;try{this.bo(n,aa)}catch(i){la.error("Failed to capture copy/cut event",i)}};we(F,"copy",e,{capture:!0}),we(F,"cut",e,{capture:!0})}}}else la.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;wt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Fa]: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[Fa],i=this.co,r=this.instance.Qi()&&!this.fo;if(et(i)&&!wt(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=Yo(t);Xf(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())&&wu(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===aa;if(i&&(function(d,f,p,h,g,m){var v;if(!E||Gl(d)||p!=null&&p.url_allowlist&&!vu(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&vu(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>f.type===S)))return!1}var w=rh(d,h),_=w.parentIsUsefulElement,x=w.targetElementList;if(!(function(S,P){var R=P?.element_allowlist;if(C(R))return!0;var L,$=function(J){if(R.some((G=>J.tagName.toLowerCase()===G)))return{v:!0}};for(var O of S)if(L=$(O))return L.v;return!1})(x,p)||!Va(x,p?.css_selector_allowlist)||Va(x,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Wm))return!1;try{var I=E.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&&(Vl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Lv(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===aa){var l,u=th(E==null||(l=E.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 Ue(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(E==null||(e=E.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(){E&&E.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(E&&((e=E.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return zu;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 Ue(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];Ue(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 zu}})(E.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=E==null||(e=E.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(si,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};we(E,"popstate",t),this.wo=()=>{E&&E.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[Ra]),this.rageclicks=new qu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return me(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return q(this.Ne.capture_heatmaps)?q(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Ov.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({[Ra]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ua(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(){E&&F&&(this.Po=this.cr.bind(this),we(E,Is,this.Po),this.Ro=t=>this.ke(t||E?.event),we(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||E?.event),we(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Cu(this.instance,Jm,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),we(F,xs,this.Oo),this.vo=!0)}Eo(){var t;E&&F&&(this.Po&&E.removeEventListener(Is,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(xs,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&&bn(u)&&!rt(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:E)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=nh(u)}return!1})(Yo(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"),!mu(t.target)&&ua(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&wu(Yo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!mu(t.target)&&ua(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(E){var e=this.Ne.disable_capture_url_hashes?wn(E.location.href):E.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...wi,...n||[]]:[],r=hr(e,i,pr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!rn(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Cu,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},q(n?.name)||q(n?.value))Rn.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=Ae(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 Rn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=N.__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 Rn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[La]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=me(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return q(n)?((e=this._instance.persistence)==null?void 0:e.props[Na])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(me(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=me(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=me(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=me(this.Wo)&&Ae(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Vu;return t>0&&6e4>=t?Vu:t}get isEnabled(){var t=_e?.protocol;if(t!=="http:"&&t!=="https:")return Rn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=me(this.Wo)?this.Wo.web_vitals:wt(this.Wo)?this.Wo:void 0;return wt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Rn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=me(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=me(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[La]:n}),this._instance.persistence.register({[Na]: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=N.__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?Rn.error("failed to load script",r):t()}))}Bo(t){var e=t||E?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?wn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...wi,...i||[]]:[];return hr(n,r,pr)}Rn.error("Could not determine current URL")}}},Gv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(E&&this.isEnabled&&(n=N.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=N.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=N.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=N.__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){ji.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Ta]),this.Jo=new zg(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:ji})),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 me(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?(ji.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ji.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({[Ta]: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)?ji.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 lm([new mm,new Im,new ym,new vm,new Sm,new Em,new wm,new xm],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var p=fu.test(f)?f.replace(fu,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((b=>{return k({},b,{filename:b.filename||(w=v,w[w.length-1]||{}).filename,function:b.function||yi});var w}))})(u)}})("web:javascript",fm,gm)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(Ma))!==null&&e!==void 0?e:[],this.el=_s(this.il()),this.rl=new Cm(this.el)}onConfigChange(){this.el=_s(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({[Ma]:this.Xo,[$a]:o})}}}get nl(){var t,e=!!this._instance.get_property($a),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(!Q(t)||t.trim().length===0)return void kt.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)=>km.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&&kt.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[vs]:t,[ys]:new Date().toISOString()},i))}catch(s){kt.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 kt.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 kt.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 kt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&q(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 kt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void kt.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 kt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[vs]:t,[ys]:new Date().toISOString()})}sl(t){return me(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 Q(r)&&r.length>0&&n.$exception_types.push(r),Q(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=Th[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 kt.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!q(t)&&U(t)}}},Kv=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({[Ul]:!!e.productTours}),!da(this._instance))return!this.vl&&q((n=this.Mr)==null?void 0:n.props[Yi])||Gr.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&&da(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Gr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=N.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=N.__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[Yi];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(da(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||Gr.warn(o):Gr.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({[Yi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){q(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(Yi)}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)}}},eo),Yv={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=N._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var p=t.$set_once,h=t.$set;return{event:k({},nf(t,Bv),{properties:k({},t.properties,h?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(It.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)||(It.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,p=(m,v,b)=>{if(m!=null&&m[v]){var w=m[v];m[v]=b(w),c.push((()=>{m[v]=w}))}},h=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:h(v))).filter((v=>!et(v)));return p(u,"appendChild",(m=>function(v){var b=h(v);return b?m.call(this,b):v})),p(u,"insertBefore",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):v})),p(u,"replaceChild",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):b})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];var x=g(w);return w.length&&!x.length?void 0:v.apply(this,x)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,b){var w=h(b);return w?m.call(this,v,w):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&&(It.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,It.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){It.error(Yu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){It.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){It.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 It.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;N["__$$ph_site_app_"+u]=r._instance,(l=N.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return It.error(Yu+u,d)}))};for(var a of s.siteApps)o()}else It.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Jv={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=N.__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=N.__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=N.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Nv.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()}}},Zv=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 te.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(q(e))return te.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,te.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)te.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)te.info(Ju);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())te.info("Not loading surveys in cookieless mode without consent.");else{var t=N?.__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(Wl);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 te.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Uv(this._instance),te.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){te.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 te.info(Ju),t([]);var n,i=this._instance.get_property(Ba);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?te.error(a):r.error||te.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&($h(p)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[Ba]:c,[bs]: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(bs);return Ae(t)&&Date.now()-t>3e5}Bl(){return Ae(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};Nh(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){te.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!q(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);te.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(q(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(q(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(q(this._surveyManager))return te.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 q(this._surveyManager)?(te.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(q(this._surveyManager))te.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Sv.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(te.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;te.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),te.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);te.warn("Survey element not found")}else te.warn("Surveys of type "+r.type+" cannot be rendered in the app");else te.warn("Survey not found")}}displaySurvey(t,e){var n;if(q(this._surveyManager))te.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!==Ka.Popover&&e.initialResponses&&te.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 te.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==Ka.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else te.warn("Survey not found")}}cancelPendingSurvey(t){q(this._surveyManager)?te.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},eo),Xv={toolbar:class{constructor(t){this.instance=t}Wl(t){N.ph_toolbar_state=t}Vl(){var t;return(t=N.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),za(this.instance.config)||!E||!F)return!1;t=t??E.location,n=n??E.history;try{if(!e){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}e=E?.localStorage}var i,r=Hv||As(t.hash,"__posthog")||As(t.hash,"state"),s=r?pu((()=>JSON.parse(atob(decodeURIComponent(r)))))||pu((()=>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(Zu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=N.ph_load_toolbar||N.ph_load_editor;!q(e)&&Ue(e)?e(t,this.instance):Xu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(Zf));if(!E||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(E.localStorage.setItem(Zu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=N.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Xu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),we(E,"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)}}},Qv=k({experiments:Oe},eo),ey={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;q(e)||(wt(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||za(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=N?.__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(Wl);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 dt.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,dt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else dt.error("Cannot complete initialization: remote config is null")}eu(t,e){dt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():dt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!et(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":za(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?q(this.Jl)||!this.Jl.token?"missing_token":N!=null&&N.__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 ce((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(dt.warn(Mn),null)}))()}getMessages(t,e){var n=this;return ce((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(dt.warn(Mn),null)}))()}markAsRead(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(dt.warn(Mn),null)}))()}getTickets(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(dt.warn(Mn),null)}))()}requestRestoreLink(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(dt.warn(Mn),null)}))()}restoreFromToken(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(dt.warn(Mn),null)}))()}restoreFromUrlToken(){var t=this;return ce((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(dt.warn(Mn),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()}}},ty={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ve("[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(od)||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),E&&we(E,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=C(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(f=w?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=w?.["deployment.environment"])!==null&&h!==void 0?h:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,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 sm(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},sd);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;!q(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){od(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=N?.__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(Wl)}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===Kt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Kt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.LIB_VERSION}}Ot(t){return new Promise((e=>{if(ch(this.Sa,3))e({kind:"fatal",error:ha(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:ha(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:ha(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=uh(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,oe.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,sd,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=$f(s,Mf(n,oe.LIB_NAME,oe.LIB_VERSION),i,oe.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,q(r)||(e.sessionStartTimestamp=r),q(s)||(e.lastActivityTimestamp=s)}if(N!=null&&(t=N.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?wn(N.location.href):N.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},ny={metrics:class{constructor(t){this.rt=ve("[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 om(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:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.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)}}},iy=k({},eo,zv,Vv,Gv,Kv,Yv,Zv,Jv,Xv,Qv,ey,ty,ny);nt.__defaultExtensionClasses=k({},iy);var jh=(function(){oe.SDK_DIST_CHANNEL="npm";var t=sr[oi]=new nt;return(function(){function e(){e.done||(e.done=!0,Bh=!1,ae(sr,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():we(F,"DOMContentLoaded",e,{capture:!1}):E&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ry=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Ze=null,$s=null,Uh="";const nl=new Map;function Hh(t){return[...t.querySelectorAll(ry)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function sy(t){for(const n of document.body.children)n===t||n.tagName==="SCRIPT"||(nl.set(n,{inert:n.inert,ariaHidden:n.getAttribute("aria-hidden")}),n.inert=!0,n.setAttribute("aria-hidden","true"));const e=document.activeElement;e&&e!==document.body&&!t.contains(e)&&e.blur()}function oy(){for(const[t,e]of nl)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);nl.clear()}function Wh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=Ze&&Ze!==n?Ze:null,r=$s;if(i&&Ge(i,{restoreFocus:!1,force:!0}),Ze!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),$s=a,Uh=document.body.style.overflow,sy(n),document.body.style.overflow="hidden"}Ze=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(Ze!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Hh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function Ge(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Wh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==Ze)return!0;oy(),document.body.style.overflow=Uh,Ze=null;const i=$s;return $s=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function ay(){return!!Ze}function ad(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 ly(t){if(!Wh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ge(t)}document.addEventListener("keydown",t=>{if(!Ze)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),ly(Ze);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Hh(Ze);if(!e.length){t.preventDefault(),(Ze.querySelector(".modal-content")||Ze).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 cy(){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 Zl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),uy=Object.freeze({free:2,professional:50,power:2e3}),dy="(contact us)",fy=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 ${dy}`])}),qh="CodeFile",zh="GeneratedCode",hy={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function vn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function il(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function py(t={},e=0){const n=il(t.artifactType||t.type||qh),i=il(t.artifactName||t.name||t.fileName||`${zh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Vh(t={},e=0){const n=vn(t),i=n.artifactType||n.type||qh,r=n.artifactName||n.name||zh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:il(n.id)||py({...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:Gh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:Kh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:vn(n.metadata),codeType:n.codeType||hy[i]||"O"}}function Gh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=vn(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(vn(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function Kh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=vn(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 rl(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 gr(t,e={}){const n=[],i=typeof t=="string"?rl(t):t,s=vn(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)=>Vh(d,f)),l=new Map(o.map((d,f)=>[vn(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=Kh(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:Gh(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:vn(s.metadata)}}function Ei(t){return gr(t).artifacts[0]||Vh()}function an(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Si(t){return JSON.stringify(t,null,2)}function gy(t){return Si({task:"architect",userRequest:String(t??"")})}function my(t){const e=an(t);return e&&typeof e=="object"&&typeof e.task=="string"?Si(e):Si({task:"generate_bundle",bundleSpec:e})}function vy(t){return Si({task:"review_bundle",generatedBundle:an(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 Xl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=an(e)),n}function yy({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return Si({task:"regenerate_artifact",artifactId:i,bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(r)})}function Yh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Si({task:"regenerate_bundle",bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(i??"")})}const ld={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"},_y=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function st(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function wy(t){return st(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||st(t.filterSummary)||st(t.filterResults):!1}function Jh(t,e=0){if(!st(t)||e>3)return null;if(wy(t))return t;for(const n of _y){const i=t[n];if(st(i)){const r=Jh(i,e+1);if(r)return r}}return null}function Ls(t){return Array.isArray(t)?t.some(Ls):st(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(Ls):!1}function sl(t){return Array.isArray(t)?t.some(sl):st(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(sl):!1}function Zh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function by(t,e){if(st(t))for(const[n,i]of Object.entries(t)){if(!st(i))continue;const r=st(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>st(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Zh(n))}}function Ey(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>st(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!Ls(r))continue;const s=Zh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=st(o)?Object.entries(o).filter(([,l])=>Ls(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function Sy(t){return ld[t]?ld[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function cd(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 xy(t){const e=Jh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);by(e.filterSummary,n),Ey(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=sl(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Iy(t,e){const n=xy(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(Sy))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${cd(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 ${cd(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 ky(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ud(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of ky(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 Ql(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 dd(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 Cy(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=Ql(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await dd(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await dd(c)),n[o]=u,a.type==="F"){const d=ud(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const r=new Set(ud(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 Py=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),fd={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Ay=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Fy=["Struct","Record"],Ry=[{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=>pa(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=>pa(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 { + const _P({required this.t}); + final double t; +} +class W extends StatefulWidget { + const W({this.value = 1.0}); + final double value; +}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } +var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>pa(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { + const W({this.textStyle}); + final TextStyle? textStyle; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { + const W({this.width}); + final double? width; + @override _S createState() => _S(); +} +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Ct(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function mr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function My(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$y(t).usable);function Ny(t=""){const e=mr(t);return Ly.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Oy(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=Ty(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rhd(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function to(t=""){return Array.from(mr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function By(t="",e=""){return ec(t,e)?.returnType||null}function pd(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 Dy(t,e){const n=to(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>pd(l)===r)||n.length>1)return null;const[o]=n,a=`${pd(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 tc(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function jy(t,e,n=""){const i=ec(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Ql(r,"A");if(s===i)return null;const o=`${tc(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 Uy(t="",e=""){return ec(t,e)!==null}function Hy(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Ay.has(i)?!1:!Fy.some(s=>i.endsWith(s))||e.has(i))}function Wy(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=By(t,e),r=Hy(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 qy(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(Py.has(t.artifactType)||n.push(Ct(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(Ct(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(Ct(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(Ct(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ny(r))n.push(Ct(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Uy(r,t.artifactName)&&n.push(Ct(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(to(r)),o=Wy(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(Ct(t,"error",o));const a=jy(i,r,t.artifactName);a&&n.push(Ct(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(Ct(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Dy(i,r);s&&n.push(Ct(t,"info",s))}return n}function zy(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>to(s.code||""))),i=e.flatMap(s=>qy(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:fd[s.artifactType]||fd.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const gd="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function md(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Vy(t=""){const e=t.indexOf(gd);return e===-1?t:t.slice(e+gd.length).replace(/^\s*\n/,"")}const Gy=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Ky(t="",e=""){const n=Vy(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(md).filter(Boolean)),r=n.split(` +`).filter(s=>{const o=md(s);return o===null||!i.has(o)?!0:!Gy.test(s)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Yy=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","flutter_web_plugins","integration_test","sky_engine"]);function Jy(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 i_(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 r_(t,e={}){const n=Array.isArray(t?.artifacts)?t.artifacts:[],r=(e.selectedArtifactIds||t?.deployOrder||n.map(p=>p.id)).map(p=>n.find(h=>h.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(p=>{const h=n_(p),g=p.fixedCode||p.code||"",m=p.codeType||e_[p.artifactType]||it.OTHER;g.trim()||s.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:h,content:g,type:m,path:p.deployPath||t_(h,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,h)=>({entry:p,index:h})).filter(({entry:p})=>p.type===it.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],h={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} +${m.content}`).join(` + +`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=h}const u={...vd(t?.dependencies),...r.reduce((p,h)=>({...p,...vd(h.dependencies)}),{})},c={};r.forEach(p=>{nc(p.fixedCode||p.code||"").forEach(h=>{h in u||(c[h]="")})});const d={...c,...u},f=i_(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 s_(t){return String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/)?.[1]}function o_(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 a_(t,e){const i=[o_(t),s_(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 l_(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:a_(i,r),content:r.content,fileName:i,path:r.path});return n}function c_(t,e=new Map){const n=[],i=[];for(const r of t)(e.has(r.path)?n:i).push(r);return{landed:n,notLanded:i}}function ol(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}function u_(t){return t?t.notLanded.length===0&&t.landed.length>0:!1}function d_(t,e,n){const i=ol(t,e),r=new Map(i);return r.set("pubspec.yaml",{content:n,type:"D",path:"pubspec.yaml"}),r}const yd={pass:0,warning:1,fail:2},f_=["manualActions"];function ct(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tn(...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 At(t){return t==null?[]:Array.isArray(t)?t:[t]}function h_(t){const e=ct(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return _d(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?_d(Number(i[1])):null}function _d(t){return t>=0&&t<=100?t:null}function ht(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ic(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 al(...t){return t.filter(Boolean).reduce((e,n)=>yd[n]>yd[e]?n:e,"pass")}function tp(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ct(t),r=tn(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:ic(i.severity||i.status||i.level)||e,message:r,suggestion:tn(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function ll(t,e="review"){const n=ct(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>At(n[r]).map(o=>tp(o,s,e)).filter(Boolean))}function p_(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=ct(t),r=tn(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:tn(i.detail,i.instructions,i.description),location:tn(i.location,i.flutterFlowPath,i.path),timing:tn(i.timing,i.phase)||"unspecified",artifactId:n,source:tn(i.source)||"Code Review"}:null}function cl(t,e=null){const n=ct(t);return f_.flatMap(i=>At(n[i])).map((i,r)=>p_(i,r,e)).filter(Boolean)}function g_(t){let e=typeof t=="string"?rl(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ct(e);typeof n.content=="string"&&(e=rl(n.content)||e);const i=ct(e),r=ct(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function m_(t,e){const n=[e.id,e.fileName,e.artifactName].map(ht);return t.find(i=>{const r=ct(i);return[r.id,r.fileName,r.artifactName,r.name].map(ht).some(s=>s&&n.includes(s))})||null}function v_(t,e){return At(t?.metadata?.compatibility?.deployHints).find(r=>ht(r?.artifactId)===ht(e.id)||ht(r?.fileName)===ht(e.fileName))?.pathHint||""}function y_(t,e){return At(t?.relationships).filter(n=>ht(n?.from)===ht(e.id)||ht(n?.to)===ht(e.id))}function __(t,e){return At(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ht(n.artifactId)===ht(e.id)).map(n=>tp(n,"warning","Compatibility check")).filter(Boolean)}function w_(t,e,n,i){const r=m_(e,n),s=ct(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...ll(s),...__(t,n)],l=cl(s,n.id),u=ic(s.status||s.verdict||s.outcome||s.result),c=a.length?al(...a.map(f=>f.severity)):null,d=al(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?tn(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:v_(t,n),relationships:y_(t,n)}}function b_({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 E_({bundle:t,reviewResult:e}){const n=ct(t),i=At(n.artifacts),{root:r,rawText:s}=g_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ct).find(w=>Object.keys(w).length)||{},a=At(r.artifacts||r.files||r.reviews),l=i.map((w,_)=>w_(n,a,w,_)),u=ll(r),d=[...ll(o),...u],f=[...cl(o),...cl(r),...l.flatMap(w=>w.manualSteps)].filter((w,_,x)=>x.findIndex(I=>I.title===w.title&&I.artifactId===w.artifactId)===_),p=ic(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=al(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??r.score??r.overallScore??s,m=h_(g),v=tn(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)||b_({status:h,score:m,artifactPresentations:l,manualSteps:f}),b=l.reduce((w,_)=>(w[_.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:At(n.deployOrder),relationships:At(n.relationships),warnings:At(n.warnings),compatibility:ct(n.metadata?.compatibility)}}const S_="x-ff-api-key",wd="dr_",x_=/^[A-Za-z0-9_-]{1,120}$/;function I_(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`${wd}${t.randomUUID()}`;if(t&&typeof t.getRandomValues=="function"){const e=t.getRandomValues(new Uint8Array(16));return`${wd}${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}return null}function k_(t){return typeof t=="string"&&x_.test(t)}function C_(t,e){return`${String(t).replace(/\/deployCustomClasses$/,"")}/runStatus/${encodeURIComponent(e)}`}function P_(t){if(!t||typeof t!="object")return null;const{status:e}=t;return e!=="running"&&e!=="done"&&e!=="failed"?null:{status:e,phase:typeof t.phase=="string"?t.phase:"",message:typeof t.message=="string"?t.message:"",error:typeof t.error=="string"?t.error:null,deployed:Array.isArray(t.deployed)?t.deployed:[],dryRun:t.dryRun===!0}}const A_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function F_(t){return!t||!t.status?{definitive:null}:t.status==="done"?{definitive:"success",deployed:Array.isArray(t.deployed)?t.deployed:[]}:t.status==="failed"&&A_.has(t.phase)?{definitive:"failed",error:t.error||"The deploy failed before writing anything to FlutterFlow."}:{definitive:null}}async function R_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,timeoutMs:r=8e3}){if(!k_(e))return null;const s=i||globalThis.fetch;if(!s)return null;const o=new AbortController,a=setTimeout(()=>o.abort(),r);try{const l=await s(C_(t,e),{method:"GET",headers:{[S_]:String(n||"")},signal:o.signal});if(!l.ok)return null;const u=await l.json();return P_(u)}catch{return null}finally{clearTimeout(a)}}async function T_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,budgetMs:r=12e3,intervalMs:s=2e3}){const o=Date.now()+r;let a=0;for(;Date.now()=2)return{definitive:null};const u=o-Date.now();if(u<=0)break;await new Promise(c=>setTimeout(c,Math.min(s,u)))}return{definitive:null}}const M_=/^\uFEFF/;function Hi(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(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+f)),c+=n[d].length+1}}if(r===0)return Hi(n);{const c=ul(e);if(!c.error&&o.every(f=>Ed(f,c.commentAndStringRanges)))return Hi(n)}if(r===1){const c=Hi(n.slice(0,s)),d=Hi(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 L_(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 np(t){const e=L_(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 ip(t){return`${tc(t)}.dart`}function N_(t){return Ql(t,"W")}const bd={"(":")","[":"]","{":"}"},O_={")":"(","]":"[","}":"{"},B_=/[A-Za-z0-9_]/;function ul(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]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!B_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(bd[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(O_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&bd[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function D_(t){return ul(String(t??"")).error}function Ed(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 j_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],U_="MAGIC_LINK_SENT",H_="PLUS_ALIAS_REJECTED",W_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",no={allowlistedDomains:j_,successCode:U_,validationCode:H_,messageTemplate:W_},q_=new Set(no.allowlistedDomains),z_=no.successCode,V_=no.validationCode;function io(t){return typeof t=="string"?t.trim():""}function G_(t){const e=io(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 q_.has(r)?i.includes("+"):!1}function K_(t,e){return no.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function rp(t){if(!G_(t))return null;const e=io(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return K_(e,i)}function sc(t){return!t||typeof t!="object"||Array.isArray(t)||t.success===!1||t.error?!1:t.code?t.code===z_:t.success===!0||typeof t.message=="string"}function sp(t,e){return t?.code===V_?t.message||rp(e)||"Please enter your primary email address.":sc(t)?`Check your email — we sent a link to ${io(e)}`:t?.message||"Something went wrong. Please try again."}const Y_="ccc_auth_session",J_="ccc_subscription",Z_=Object.freeze(["hasSeenWalkthrough"]);function X_(t){const e=[];for(const n of Z_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function Q_(){return[Y_,J_]}function e0({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of Q_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function t0(t){const e=t?.message||t?.error;return typeof e=="string"&&e.trim()?e.trim():"The server could not send the link."}function n0({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());if(!sc(o))throw new Error(t0(o));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 i0=/^dependencies\s*:\s*(?:#.*)?$/,r0=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Ir(t){const e=t.match(r0);return e?e[1]??e[2]??e[3]:null}function kr(t){const e=t.trim();return e===""||e.startsWith("#")}function En(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function oc(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;sc&&/\s/.test(s[d-1]);)d-=1}return t[r]=s.slice(0,c)+lc(n)+s.slice(d),!0}return!1}function Sd(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?lc(i):">=0.0.0"}`]}function l0(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(dp(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=ac(r);if(l){const u=o.flatMap(([c,d])=>Sd(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(...Sd(" ",u,c))});return{yaml:r.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function c0(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=ro(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l),d=c&&!c.isScalar&&c.sourceKey===null&&c.version!==null;if(!c||!c.isScalar&&!d||!String(u||"").trim()){a.push(l);continue}if(d){a0(r,c,String(u).trim())?o.push({name:l,from:c.version,to:u}):a.push(l);continue}const f=" ".repeat(En(r[c.lineIndex]));r[c.lineIndex]=`${f}${l}: ${lc(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` +`),overridden:o,skipped:a}}function hp(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),ac(e.split(` +`))||n.push("pubspec.yaml missing dependencies section"),dp(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 u0=">=3.0.0 <4.0.0";function dl(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 d0(t=""){const e=ep(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function xd(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=dl(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=dl(s.version);continue}i.push(r)}return i}function f0(t){const e=new Set,n=new Set,i={},r={},s=xd(ro(t),i,e),o=xd(s0(t,"dependency_overrides"),r,n),a=[...s,...o],l=new Set([...Object.keys(i),...e]),{sdk:u}=fp(t);return{sdkConstraint:dl(u)||u0,dependencies:i,dependencyOverrides:r,sdkPackages:[...e].sort(),sdkOverrides:[...n].sort(),availablePackages:l,unrepresentable:a,unrepresentableOverrides:o}}function h0(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 p0(t,e){const{sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o,availablePackages:a,unrepresentable:l,unrepresentableOverrides:u}=f0(e),c={sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o},d=[],f=[],p=[];for(const h of t){const{className:g,content:m}=h,v=nc(m),b=ep(m).some(x=>x.startsWith("package:"));if(l.length>0&&b){const x=v.filter(T=>l.includes(T));let I;if(x.length>0)I=`${g} was not compiled before deploying: it imports or exports ${x.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`;else{const T=l.filter(P=>!u.includes(P)),S=[T.length>0?`your project's pubspec.yaml declares ${T.join(", ")} from a source that cannot be reproduced outside it`:null,u.length>0?`your project's dependency_overrides redirects ${u.join(", ")} to a source that cannot be reproduced outside it`:null].filter(Boolean).join(", and ");I=`${g} was not compiled before deploying: ${S}, and an entry like that can change what every package depending on it resolves to - including packages this class reaches transitively - so package resolution could not be matched exactly.`}f.push({className:g,reason:I});continue}const{unresolvableImports:w}=d0(m),_=v.filter(x=>!a.has(x));if(w.length>0||_.length>0){f.push({className:g,reason:h0(g,w,_)});continue}d.push({fileName:`${tc(g)}.dart`,content:m})}return{manifest:c,sources:d,skipped:f,approximate:p}}function Id(t,e){const n=`${t}${e}`.split(` +`),i=n.pop()??"",r=[];for(const s of n){const o=pp(s);o&&r.push(o)}return{events:r,buffer:i}}function g0(t){const e=pp(t);return e?[e]:[]}function pp(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 Ne=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),gp=84e4,mp=1e4;function vp(t){return t?.unconfirmed===!0||t?.outcome===Ne.UNCONFIRMED?Ne.UNCONFIRMED:t?.partial===!0||t?.outcome===Ne.PARTIAL?Ne.PARTIAL:t?.success===!0?Ne.COMMITTED:Ne.FAILED}class We extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Ne.UNCONFIRMED}}function kd({httpStatus:t}={}){return new We(`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 m0(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}if(u.event==="result"){r=u;return}u.event===void 0&&typeof u.success=="boolean"&&(r=u)};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const p=Id(o,c.decode(f,{stream:!0}));o=p.buffer,p.events.forEach(a)}}else{const u=Id("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return g0(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 v0=new Set(["connected","workspace_init","workspace_ready","verifying"]);function yp(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?v0.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Cd(t){if(t?.finalResultReceived){const e=vp(t);return e===Ne.FAILED&&!yp(t)?Ne.UNCONFIRMED:e}return t?.httpRejected&&typeof t.httpStatus=="number"&&t.httpStatus>=400&&t.httpStatus<500?Ne.FAILED:Ne.UNCONFIRMED}function y0(){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,p,h,g,m,v;function b(V,z){if(!i)return null;const D=i.createShader(V);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const V=b(i.VERTEX_SHADER,o),z=b(i.FRAGMENT_SHADER,a());if(V&&z&&(l=i.createProgram(),i.attachShader(l,V),i.attachShader(l,z),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),p=i.getUniformLocation(l,"parallax"),h=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function w(V){if(!V)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(V);if(z){let D=z[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const he=D.getContext("2d");he.fillStyle="rgb(9, 8, 7)";const Ce=String(he.fillStyle);he.fillStyle=V;const Te=String(he.fillStyle);if(Te===Ce)return null;const mt=/^#([0-9a-f]{6})$/i.exec(Te);if(mt){const vt=mt[1];return[parseInt(vt.slice(0,2),16)/255,parseInt(vt.slice(2,4),16)/255,parseInt(vt.slice(4,6),16)/255]}const Wt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Te);if(Wt)return[Number(Wt[1])/255,Number(Wt[2])/255,Number(Wt[3])/255]}catch{}return null}function _(){let V="";try{const z=getComputedStyle(document.documentElement);V=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return w(V)||[.56,.68,.88]}const x=_();let I=1920,T=1080,S=960,P=540,R=960,L=540,$=.66,O=0,J=-1e9,G=!1,M=0,K=0,ie=null,B=!1,X=!1,fe=!1;const se=64,ee=15.2;let Pe=0,ke=0;const je=.0032,St=0,ye=.56,tt=.26,xt=.32,Cn=.16,Le=.349;let Re=St;function Dt(){const V=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!V.width||!z||!D)return;const he=Math.min(window.devicePixelRatio||1,2),Ce=Math.max(.2,Math.min(2,V.width/z*he)),Te=Math.max(2,Math.round(z*Ce)),mt=Math.max(2,Math.round(D*Ce));(Te!==t.width||mt!==t.height)&&(t.width=Te,t.height=mt,i&&i.viewport(0,0,Te,mt)),I=z,T=D,G||(S=R=I/2,P=L=T/2,G=!0)}function Zn(V){!l||!B||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,S,P),i.uniform1f(f,$),i.uniform1f(p,O),i.uniform2f(v,Math.cos(Re),Math.sin(Re)),i.uniform1f(h,V),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Ke(V,z,D){const he=Math.max(0,Math.min(1,(D-V)/(z-V)));return he*he*(3-2*he)}function Xn(V){if(!ie||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/I;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const he=Math.min(I,T),Ce=Math.max(64,Math.min(118,he/10)),Te=Ce*2.9,mt=2*Te*Te,Wt=Math.sin(V*.11)*7,vt=Math.cos(V*.09)*7-O,$r=S+Wt,Lr=P+vt,Ro=Te*Math.sqrt(2*Math.log(1/.06)),Ri=Ro+je*Ro*Ro+Ce,Ag=Math.floor(($r-Ri)/Ce)-1,Fg=Math.ceil(($r+Ri)/Ce)+1,Rg=Math.floor((Lr-Ri)/Ce)-1,Tg=Math.ceil((Lr+Ri)/Ce)+1;for(let To=Rg;To<=Tg;To++){const Mg=(To+.5)*Ce;for(let Mo=Ag;Mo<=Fg;Mo++){const $o=(Mo+.5)*Ce-$r,Lo=Mg-Lr,No=Math.sqrt($o*$o+Lo*Lo)+1e-5;if(No>Ri)continue;const Nr=(-1+Math.sqrt(1+4*je*No))/(2*je),Vc=Math.exp(-(Nr*Nr)/mt),Gc=Ke(.06,.8,Vc)*$*.26;if(Gc<.004)continue;const gn=Ce/(1+2*je*Nr)*.26*(.32+1.1*Vc),Kc=Nr/No,Oo=$r+$o*Kc,Bo=Lr+Lo*Kc;Oo<-gn*1.6||Oo>I+gn*1.6||Bo<-gn*1.6||Bo>T+gn*1.6||(z.globalAlpha=Gc,z.save(),z.translate(Oo,Bo),z.rotate(Re),z.drawImage(ie,-gn,-gn,gn*2,gn*2),z.restore())}}z.globalAlpha=1}function jt(V){if(!X)return;const z=K?Math.min(.05,(V-K)/1e3):.016;K=V;const he=V-J>2400?.6:1;$+=(he-$)*Math.min(1,z*3.2);const Ce=Math.min(.05,z);Pe+=((R-S)*se-Pe*ee)*Ce,ke+=((L-P)*se-ke*ee)*Ce,S+=Pe*Ce,P+=ke*Ce,O=(window.scrollY||window.pageYOffset||0)*.55;const Te=V/1e3,mt=S/(I||1)-.5,Wt=P/(T||1)-.5;let vt=mt*(mt>=0?ye:tt)+Wt*(Wt>=0?xt:Cn);vt>Le?vt=Le:vt<-Le&&(vt=-Le),Re=St+vt-O*6e-4,Dt(),i?Zn(Te):Xn(Te),M=requestAnimationFrame(jt)}function Ut(V){if(!X)return;const z=t.getBoundingClientRect();!z.width||!I||!T||(R=(V.clientX-z.left)/z.width*I,L=(V.clientY-z.top)/z.height*T,J=performance.now())}function ut(){X||Fo||e.matches||n.matches||!fe||document.hidden||(X=!0,K=0,M=requestAnimationFrame(jt))}function Ht(){X=!1,M&&(cancelAnimationFrame(M),M=0),K=0}function Fi(){e.matches?(Ht(),t.classList.remove("is-ready")):fe&&ut()}function Qn(){n.matches?Ht():fe&&ut()}function Wc(){document.hidden?Ht():fe&&ut()}const qc=new IntersectionObserver(V=>{fe=V[0]?.isIntersecting||!1,fe?ut():Ht()},{threshold:0});qc.observe(t),window.addEventListener("pointermove",Ut,{passive:!0,capture:!0}),window.addEventListener("resize",Dt),e.addEventListener("change",Fi),n.addEventListener("change",Qn),document.addEventListener("visibilitychange",Wc);function Pg(){const V=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(V&&window.Path2D){const he=Math.min(8.533333333333333,8.421052631578947);D.setTransform(he,0,0,he,he+(256-30*he)/2,-6.4*he),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(V),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const he=D.getImageData(0,0,256,256),Ce=he.data;for(let Te=3;Te{V.persisted?Ht():zc()}),window.addEventListener("pageshow",V=>{V.persisted&&ut()}),{dispose:zc,isRunning:()=>X}}const _0=120;function w0(t,e,n){return tn?n:t}function pe(t,e,n){return w0((t-e)/(n-e),0,1)}function b0(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function ga(t){return 1-Math.pow(1-t,3)}function Ye(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 Pd(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function re(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(pe(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=re(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),h=re(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ye}]),d=re(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ye},{t:10.6,v:0}]),p=re(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ye}]),o=re(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=re(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=pe(_,.45,2.2);a=x>0?-2.6*(1-Pd(x)):0,g=re(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=pe(_,.67,2.42);f=I>0?-2.6*(1-Pd(I)):0,s=1-.05*(Math.sin(pe(_,1.9,2.5)*Math.PI)+Math.sin(pe(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[re(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}]),re(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 w=x;const _=t-60,I=1-pe(_,12,14),T=x(pe(_,0,12)),S=x(pe(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(S[0]-T[0])*.6*I,a=(S[1]-T[1])*.6*I,p=(S[0]-T[0])*30*I,b=pe(_,0,.4)*I}else if(t<85.4){const _=t-74,x=re(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ye},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=re(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ye},{t:11.4,v:0}]),p=-l*.7,a=re(_,[{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=pe(_,0,5.6),I=pe(_,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,p=x*360*(1-I);const S=re(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:ga},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*S,d+=.16*S,l=-6*S,p+=6*S,s=1+.05*S,m=1+.9*S}else if(t<108.6){const _=t-96.4,x=pe(_,9.6,12.2);n=re(_,[{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(pe(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,h=1-.12*I,l=I*8,p=-I*8,o=.06*I,d=-.06*I,b=pe(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(pe(_,0,8)*Math.PI),I=1-pe(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(pe(_,0,6)*Math.PI),v=1+.1*Math.sin(pe(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=b,e}function E0(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=_0;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function p(M){const K=Math.min(1,Math.max(0,M.x))*c,ie=M.y*d;n.style.transform="translate3d("+K.toFixed(2)+"px,"+ie.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("+K.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,b=!1,w=!1,_=0;function x(){return w||a.matches||document.hidden||!e.offsetParent?!1:b}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){S();return}const K=g?(M-g)/1e3:0;g=M,h=(h+Math.min(K,.1))%l,_+=1,p(Wi(h))}function T(){v||w||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function S(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():S()}function R(){a.matches?(S(),p(Wi(0))):P()}function L(){f(),v&&p(Wi(h))}function $(){g=0,P()}const O=new IntersectionObserver(M=>{b=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});O.observe(e),window.addEventListener("resize",L),a.addEventListener("change",R),document.addEventListener("visibilitychange",$);function J(){w||(w=!0,S(),O.disconnect(),window.removeEventListener("resize",L),a.removeEventListener("change",R),document.removeEventListener("visibilitychange",$))}window.addEventListener("pagehide",M=>{M.persisted?S():J()}),window.addEventListener("pageshow",M=>{M.persisted&&P()});function G(M){h=(M%l+l)%l,p(Wi(h))}return f(),p(Wi(0)),P(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:G,dispose:J}}const S0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ln(t){const e=String(t||"").trim().match(S0);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function x0(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 k0(t){const e=ln(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function cc(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 ln(o)?{min:o,minInclusive:!0,max:k0(o),maxInclusive:!1}:null}if(ln(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(!ln(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Ad(t,e){const n=cc(t);if(!n||!ln(e))return!1;if(n.min!==null){const i=Ns(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=Ns(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function C0(t,e){const n=cc(t);if(!n||!ln(e))return!1;if(n.max===null)return!0;const i=Ns(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ri(t){const e=cc(t);return e?e.min:null}const P0="https://pub.dev/api/packages/",A0=8e3;function F0(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||I0(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Ad(l.sdk,n)||i&&l.flutter&&!Ad(l.flutter,i)||(!s||Ns(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function R0(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${P0}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(A0)});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=F0(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 T0(t,e={}){const n=await Promise.all(t.map(i=>R0(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function M0(t,e={},n={}){const{resolveVersions:i=T0}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=fp(t),o={dartSdkFloor:ri(s.sdk),flutterSdkFloor:ri(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=ro(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(Yy.has(d)?c:u).push(d);continue}const h=ri(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:d,constraint:p.constraint});continue}if(C0(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(ri(h)){a.additions[f]=`^${ri(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${ri(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const $0={"&":"&","<":"<",">":">",'"':""","'":"'"};function cn(t){return String(t??"").replace(/[&<>"']/g,e=>$0[e])}function W(t){return t?cn(t).replace(/\n/g,"
    "):""}function on(t){return cn(t).replace(/\r?\n/g," ")}function so(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 wp(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 L0(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 N0(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 O0(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 xi(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 Fd(t){return t=cn(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 bp(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=xi(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 cn(i)}}}function oo(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=O0(o),u=bp(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+=`
    +

    + ${L0(l)} + ${cn(l)} +

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

    + ${N0(l)} + ${cn(l)} +

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

    ${Fd(a)}

    `)}return i+="
    ",` +
    +
    +
    + Live Audit Report +
    + ${i} +
    + `}const ai=5200,ma=73,B0=1600,Rd=35,Td=22,va=new WeakMap;function Md(t,e){return!!(t&&t.trim())&&!e}function D0(t,e){const n=ai+(e-1)*ma,i=n+B0;if(t{X.disabled=B}),o&&(o.disabled=B),a&&(a.disabled=B),b()}async function x(){if(Md(n.value,v())){_(!0);try{await t()}finally{_(!1)}}}function I(){f&&(f=!1,g&&(clearTimeout(g),g=null),e.classList.remove("is-demo-typing","is-demo-keying"),n.placeholder="Describe the widget or action you need",b())}function T(){if(l.matches||!m.trim())return;const B=window.location.hash.replace(/^#/,"");if(B&&B!=="home")return;f=!0,n.placeholder="",n.value="",w(),b(),e.classList.add("is-demo-typing");const X=performance.now(),fe=()=>{if(!f)return;const se=D0(performance.now()-X,m.length);n.value=m.slice(0,se.chars),w(),e.classList.toggle("is-demo-keying",se.keying),se.done?I():g=setTimeout(fe,se.next)};g=setTimeout(fe,ai)}function S(){f&&(n.value="",w(),I())}function P(){l.matches&&(S(),L())}function R(){d=!1,h&&(clearInterval(h),h=null),e.classList.remove("is-demo-typing","is-demo-keying"),b()}function L(){d&&(n.value=s.find(B=>B.classList.contains("is-active"))?.dataset.prompt||n.value,w(),R())}function $(){s.forEach(B=>{B.classList.remove("is-active"),B.setAttribute("aria-pressed","false")})}function O(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function J(B){const X=B.dataset.prompt||"";if(I(),R(),s.forEach(se=>{const ee=se===B;se.classList.toggle("is-active",ee),se.setAttribute("aria-pressed",String(ee))}),l.matches||!X){n.value=X,w(),b(),O();return}n.value="",w(),d=!0,b(),e.classList.add("is-demo-typing","is-demo-keying");const fe=performance.now();h=setInterval(()=>{const se=Math.min(X.length,Math.floor((performance.now()-fe)/Td));n.value=X.slice(0,se),w(),se>=X.length?(R(),O()):b()},Td)}s.forEach(B=>{B.setAttribute("aria-pressed","false"),B.addEventListener("click",()=>J(B))}),n.addEventListener("keydown",B=>{if((f||d)&&B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u){B.preventDefault();return}S(),L(),B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u&&(B.preventDefault(),x())}),n.addEventListener("beforeinput",()=>S()),n.addEventListener("input",()=>{I(),R(),$(),w(),b()}),n.addEventListener("compositionstart",()=>{u=!0}),n.addEventListener("compositionend",()=>{u=!1,b()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),i.addEventListener("click",x),n.addEventListener("pointerdown",()=>{S(),L(),$()}),n.addEventListener("focus",()=>S());const G=va.get(e);G&&G.mql.removeEventListener("change",G.handler),l.addEventListener("change",P),va.set(e,{mql:l,handler:P});function M(){K(),l.removeEventListener("change",P),va.delete(e),document.removeEventListener("visibilitychange",ie)}function K(){S(),L()}function ie(){document.hidden&&K()}return document.addEventListener("visibilitychange",ie),w(),b(),T(),{setAttachmentsPending(B){p=!!B,b()},dispose:M,cancelTyping:K}}const vr=window.matchMedia("(prefers-reduced-motion: reduce)");let hi=null,Jt=null;const Os=new Map;function Ep(){for(const[t,e]of Os)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Os.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Gn(){if(Ep(),hi){const t=hi;hi=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Jt&&(Jt.animation.cancel(),Jt.hero.classList.remove("is-exiting"),Jt.hero.style.cssText=Jt.style,Jt=null)}function U0(t){return(hi?.ghost||t)?.getBoundingClientRect()}function H0(t){Ep(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",vr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Os.delete(e))}Os.set(e,i),e.addEventListener("animationend",i)})}function W0(t,e){if(!t||!e||vr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Jt={hero:t,animation:i,style:n},i.onfinish=()=>{Jt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Jt=null)}}function Sp(t,e,n,{results:i=!1}={}){if(Gn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,H0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(vr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};hi=h,p.onfinish=()=>{hi===h&&(Gn(),s())}}window.addEventListener("resize",Gn);window.addEventListener("pagehide",Gn);document.addEventListener("visibilitychange",()=>{document.hidden&&Gn()});vr.addEventListener("change",()=>{vr.matches&&Gn()});const $d="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",q0="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",z0="https://us.i.posthog.com";jh.init(q0,{api_host:z0,person_profiles:"identified_only"});function Dn(t,e={}){try{jh.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const Et="https://4tgke4.buildship.run",xp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Bs="ccc_auth_session",fl="ccc_signin_return",V0=1800*1e3,Ld=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let de=Kn({isResolved:!0}),hl=Promise.resolve();const G0=`${Et}/service/runpipeline`,K0="bs_user_id",Y0="bs_identity_token",J0=`${Et}/authUserCheck`;let yt={userId:null,token:null,status:null,resolved:!1};const Ds=uy,js="ccc_subscription",Nd=3,Z0=new Set(["active","trialing","paid"]),Us="google/gemini-3.7-flash",ss=["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"],X0={"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 nn(t){return X0[t]||t}const Q0=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 Ip(t){return Q0.has(t)}const pl=4,ya=8*1024*1024,ew="https://4tgke4.buildship.run/service/runpipeline-image";let De=[];const Sn=[],tw=3e4;let uc=null;function nw(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function iw(t,e){const n=new FormData;return n.append("file",t),(await fetch(ew,{method:"POST",body:n,signal:e})).json()}function rw(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 sw(t,e,n){const i=await nw(t,n);i&&De.includes(e)&&(e.dataUrl=i,yn());let r="";if(i)try{r=rw(await iw(t,n))}catch{r=""}return De.includes(e)?!i||!r?(De.splice(De.indexOf(e),1),yn(),"failed"):(e.url=r,yn(),"added"):"dropped"}function kp(t){const e=Sn.indexOf(t);e>=0&&Sn.splice(e,1),Pp()}function Cp(t){t.controller.abort(),kp(t);const e=De.indexOf(t.slot);e>=0&&(De.splice(e,1),yn())}function Pp(){uc?.setAttachmentsPending(Sn.length>0)}async function ow(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>ya);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(ya/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ya);if(!i.length)return;const r=pl-De.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${pl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};De.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),tw);return d.job=sw(u,c,d.controller.signal),Sn.push(d),d.job.finally(()=>{clearTimeout(f),kp(d)}),d.job});yn(),Pp();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 aw(t){if(y.isRunning){Ee("Wait for the current generation to finish before removing images.","info");return}const e=De[t],n=Sn.find(i=>i.slot===e);if(n){Cp(n);return}De.splice(t,1),yn()}function yn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",De.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=De.length>=pl?"Image limit reached":"Add images"))}function dc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ip(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(Cp),De=[],yn())}const Wn="ccc_usage",Ap="google/gemini-3.7-flash",Fp="google/gemini-3.7-flash",Yr="google/gemini-3.7-flash",Zi={professional:11,power:49},gl={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"},os={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 as={...os};async function lw(){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(os),...Object.values(ml),...Object.values(gl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:os[a]&&(s[a]=os[a]));as=s}catch{}finally{clearTimeout(e)}}const ml={"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 fc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ml[s])return ml[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=gl[e];if(n)return n;const i=e.split("_")[0],r=gl[i];return r||"USD"}function Xi(t,e){const n=as[e]??as.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*as.USD)}}const _t="ccc_api_key_",Tt="ccc_session_api_key_",Nt="ccc_encryption_key",yr="ccc_encryption_key_scope",cw="ccc_keystore",Hs="keys",_r="ccc_encryption_key_version";let vl=null,Ws=null,wr=!1,qs=!1,Od=!1;class zs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Bd(){if(Od)return;Od=!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 Rp(){return localStorage.getItem(_r)||""}function yl(){return crypto.randomUUID?.()||Mp(crypto.getRandomValues(new Uint8Array(16)))}function uw(){const t=Rp();if(t)return t;const e=yl();return localStorage.setItem(_r,e),e}function Ii(){vl=null,Ws=null,wr=!1,qs=!1}window.addEventListener("storage",t=>{t.key===_r&&Ii()});function dw(){return new Promise((t,e)=>{const n=indexedDB.open(cw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Hs)||i.createObjectStore(Hs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function hc(t,e){const n=await dw();return new Promise((i,r)=>{const s=n.transaction(Hs,t);let o;try{o=e(s.objectStore(Hs))}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 fw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function hw(){const t=await hc("readonly",e=>e.get(Nt));return fw(t)?t:null}async function Tp(t){await hc("readwrite",e=>e.put(t,Nt))}async function pw(){Ii();try{await hc("readwrite",t=>t.delete(Nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function gw(){const t=sessionStorage.getItem(Nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Tp(e),sessionStorage.removeItem(Nt),sessionStorage.removeItem(yr),localStorage.removeItem(_t+"salt"),e}async function Dd(t){const e=sessionStorage.getItem(Nt);if(e)return qs=sessionStorage.getItem(yr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new zs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Nt,JSON.stringify(i)),sessionStorage.setItem(yr,"session"),qs=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function mw(t){if(sessionStorage.getItem(yr)==="session"&&sessionStorage.getItem(Nt))return Bd(),wr=!0,Dd(t);try{const e=await hw();if(e)return e;const n=await gw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Tp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Bd(),wr=!0,Dd(t)}}async function pc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=uw();Ws!==n&&Ii();const i=vl||mw(e);vl=i,Ws=n;try{return await i}catch(r){throw Ii(),r}}async function vw(t){const e=await pc(),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:Mp(o),keyVersion:n,sessionFallback:wr}}async function yw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await pc({allowSessionFallbackCreation:!1});if(wr&&!n&&!qs)throw new zs;const r=_w(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 zs)throw i;return console.error("Decryption failed:",i),null}}function Mp(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ie="",Mt="",or=null,Ud=0,ot="not-configured",gt=0,_l=0,wl=0,ao=0,Zt=0,un=0,Xe=null,$t=null,br=null;function bw(){return _l+=1,_l}function Ew(){return wl+=1,wl}function Er(t,e,n){Xe=t?{projectId:t,key:e,generation:n}:null}function bl(t,e=Ie){if(!t)return!1;const n=Xe;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function gc(t,e,n){if(!Mt||Xe&&Xe.projectId!==Mt)return;(t||[]).some(r=>(r.id||r.projectId)===Mt)?Er(Mt,e,n):Xe&&Er("",null,null)}function $p({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===Ie||r===Ie}async function mc(){sessionStorage.getItem(Nt)&&await pc(),Ie=await Me("flutterflow"),Mt=await Me("flutterflow_project_id"),Pw(),pn(),Ie?wc():(ot="not-configured",bt())}let Sr=!1;function Lp(){const t=document.getElementById("api-keys-modal");Ve(t),_c(),Ie&&uo(Ie)}function vc(){Sr=!1,Lp()}function Sw(){Sr=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Lp()}let Hd=!1;function Wd(){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 qd(){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=nn(t.value),r=Ip(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.`),dc()}function Np(){if(Sr=!1,Wd(),qd(),!Hd){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")),Wd(),qd()}),Hd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function xw(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Op(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=Sr;if(Sr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&yc(),Ve(i))}}let dn=1;function Bp(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function lo(){const t=Bp();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,lo())}function Iw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,lo(),Ve(t))}function kw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Dp(){if(H.isVerified&&Ot()&&de.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,lo(),Ve(e))}}async function _c(){const t=document.getElementById("flutterflow-api-key-input");Ie?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Cw()}function Cw(){zd("flutterflow","flutterflow-key-status"),zd("flutterflow_project_id","flutterflow-project-status")}function zd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ft(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function Pw(){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"?Ft("flutterflow")&&Ft("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ft("flutterflow")||Ft("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)"):Ft(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)")}),pn()}async function Aw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==Ie,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await jd("flutterflow",n),n!==l&&!r&&ls()}const s=n||Ie;if(r){if(!co(r)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}bl(r,s)?await jd("flutterflow_project_id",r):(i?ls():Xe=null,e.value="",s&&!($t&&$t.key===s&&$t.generation===gt)&&uo(s))}else i&&ls();await mc(),n&&await wc(),_c();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Op()},1e3)}async function Fw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(_r,yl()),Ii(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),sessionStorage.removeItem(Nt),sessionStorage.removeItem(yr),localStorage.removeItem(_t+"salt"),await pw(),localStorage.setItem(_r,yl()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),Xe=null,$t=null,br=null,await mc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),_c()}function co(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Mt||"—"),!e)return;let r,s;if(!Ft("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 wc(){const t=Ew(),e=++ao,n=gt,i=Ie,r=await Me("flutterflow"),s=()=>$p({seq:t,currentSeq:wl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Ft("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&gc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function ls(){Mt="",Xe=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow_project_id")}function Rw(){gt+=1,$t=null,br=null,ls();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ft("flutterflow")?(ot="validating",uo(Ie)):ot="not-configured",bt()}function Tw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Mw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Tw("flutterflow-api-key-input",i)}),t.addEventListener("blur",$w(async n=>{const i=n.target.value.trim();i&&await uo(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&$t?Er(n,$t.key,$t.generation):Er("",null,null)})}function $w(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function uo(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=bw(),r=++ao,s=gt,o=Ie,a=()=>$p({seq:i,currentSeq:_l,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};$t=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===Ie&&(Ft("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;$t={key:t,generation:s};const f=t===Ie,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,gc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Mt&&(e.value=Mt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===Ie&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Lw(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 Nw(){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 Ow(){y.bundleSpec=gr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function fo(){const t=Ei(y.bundleSpec);y.artifactBundle=gr(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=zy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Ei(y.artifactBundle).id}function ho(){const t=gr(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=gr({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 jp(){const t=bc();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function bc(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Ei(t)}function Ec(){return bc().code||y.step2Result||""}async function Bw(){try{await mc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const cs={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Dw(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 In{constructor(e,n,i="main",r=cs.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=[cs.production,cs.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(El(f?d.clone():d,mp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 kd({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(Dw(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 El(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 Sc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function jw(t,e=mp){const n=t.clone();let i;try{i=JSON.parse(await El(t,e))}catch{let o="";try{o=await El(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 po(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 Z={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Up=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Hp=/extends\s+State<\w+>/;function Uw(t,e=""){if(t==="pubspec.yaml")return Z.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return Z.OTHER;if(t==="custom_functions.dart")return Z.FUNCTION;if(e){const n=Up.test(e),i=Hp.test(e);if(n||i)return Z.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return Z.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return Z.FUNCTION}return Z.CODE_FILE}function Wp(t,e){switch(e){case Z.ACTION:return`lib/custom_code/actions/${t}`;case Z.WIDGET:return`lib/custom_code/widgets/${t}`;case Z.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case Z.CODE_FILE:return`lib/custom_code/${t}`;case Z.DEPENDENCIES:return"pubspec.yaml";case Z.OTHER:return`lib/custom_code/${t}`;default:return t}}async function go(t,e=new Map){return Cy(t,e)}const Sl=new Map,pi=new Map,gi=new Map;function Pr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){Sl.delete(Pr(t))}function Qi(t,e,n){const i=Pr(t),r=pi.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?pi.delete(i):pi.set(i,r)}function Hw(t,e){Qi(t,e,{uncertain:1})}function Ww(t){const e=Pr(t);gi.set(e,(gi.get(e)??0)+1)}function Vd(t){const e=Pr(t),n=(gi.get(e)??0)-1;n<=0?gi.delete(e):gi.set(e,n)}function Sc(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 mo(t,e,n=gp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return jw(s)})();return Sc(r,n,(s,o)=>{i.stop=!0,Yn(t),Ww(t),r.then(()=>Vd(t),()=>Vd(t)),o(new We("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 qw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=c_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function xc(t,e,n,i,r="",s=gp){const o=l_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=I_();let l=!1;const u=p0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch($d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 m0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await Sc(g,s,(m,v)=>{p=!1,v(new We("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(Cd(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Cd(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Yn(t),Hw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Qi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&yp(w)&&Qi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await T_({provisionEndpoint:$d,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Qi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:ol(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await qw(t,o,m);throw u_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Yn(t),Qi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:ol(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Ic(t,e={}){const n=Pr(t);let i=Sl.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=hp(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=pi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&pi.delete(n)}!pi.has(n)&&!gi.has(n)&&Sl.set(n,i)}const r=await M0(i.pubspecYaml,e),s=c0(i.pubspecYaml,r.overrides),o=l0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function zw(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===Z.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=D_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===Z.WIDGET){const o=np(t.content),a=N_(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=`${ip(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 qp(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=np(s)[0],c=u?ip(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=Z.CODE_FILE;switch(n){case"CustomAction":a=Z.ACTION;break;case"CustomWidget":a=Z.WIDGET;break;case"CustomFunction":a=Z.FUNCTION;break;case"CustomClass":case"CodeFile":a=Z.CODE_FILE;break}let l="";return a===Z.WIDGET?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom widget code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===Z.ACTION?l=`// Automatic FlutterFlow imports +import '/flutter_flow/flutter_flow_theme.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/material.dart'; +// Begin custom action code +// DO NOT REMOVE OR MODIFY THE CODE ABOVE! + +`:a===Z.FUNCTION&&(l=`// Automatic FlutterFlow imports +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:intl/intl.dart'; +import 'package:timeago/timeago.dart' as timeago; +import '/flutter_flow/lat_lng.dart'; +import '/flutter_flow/place.dart'; +import '/flutter_flow/uploaded_file.dart'; + +`),{content:Ky(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function Vw(t){const e={};for(const n of nc(t))e[n]="";return e}function Gw(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 Kw(t,e,n,i=new Set,r=""){const s=[],o=Up.test(e),a=Hp.test(e);return n===Z.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function vo(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=>to(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=Kw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=hp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function kc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(bl(n,e))return n;const i=++ao,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==Ie||i<=un||(un=i,!s)?"":Xe&&Xe.projectId!==n&&bl(Xe.projectId,e)?Xe.projectId:((!Xe||Xe.projectId===n)&&Er(n,e,r),n)}async function Yw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=Z.WIDGET),i==="CustomAction"&&(i=Z.ACTION),i==="CustomFunction"&&(i=Z.FUNCTION),i==="CustomClass"&&(i=Z.CODE_FILE),i==="CodeFile"&&(i=Z.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await kc(o);if((o!==Ie||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!co(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||Uw(e,t),f=Wp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=vo(c);if(!p.valid)throw new Error(`Validation failed: +${p.errors.join(` +`)}`);const h=await Ic(u,r),g=h.yaml,m=await xc(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await go(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await yo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Yn(u),$e.set("push");const x=await mo(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||po(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function yo(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 Jw(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=qp(t,{artifactType:n,artifactName:i,fileName:r}),u=Vw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=or||await kc(c);if((c!==Ie||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!co(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Wp(l.fileName,l.codeType),functionName:l.codeType===Z.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=vo(h);if(!g.valid)throw new Error(`File validation failed: +${g.errors.join(` +`)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),Y.setState(ne.PUSHING);const m=new In(c,p,"main",d),v=await Ic(m,u),b=v.yaml,w=await xc(m,h,v.remoteFiles,`Provision ${i} custom class`,b);o=w.provisionSucceeded===!0;const _=await go(w.syncFileMap,w.remoteFiles),x=new Map(w.syncFileMap);x.set("pubspec.yaml",{content:b,type:Z.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const I=await yo(x),T={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:b,file_map:_.fileMapContents,functions_map:_.functionsMapContents};Y.setProgress(1,h.size),Yn(m),$e.set("push");const S=await mo(m,T);if(S.success){const P={...Gw(l,s),projectId:p};return Y.setSuccess({...P,fileCount:h.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:w.unverified,approximate:w.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=S.errorMessage||po(S.responseCode),R=new Error(P);throw R.errorMap=S.errorMap,R.remoteRefusal=!0,R}}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 We?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...l.finishDeploy?{finishDeploy:hg(l.finishDeploy,a,Y)}:{}}: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,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function Zw(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:ze(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ne.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===Z.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=vo(s);if(!o.valid)throw new Error(`File validation failed: +${o.errors.join(` +`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=or||await kc(a);if((a!==Ie||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!co(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Ic(d,t.dependencies),p=f.yaml,h=await xc(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await go(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:Z.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await yo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Yn(d),$e.set("push");const w=await mo(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||po(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:hg(s.finishDeploy,r,Y)}:{}}: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 Xw(t,e=[]){const n=Xl("architect");try{return await Ks("architect",Ap,gy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function _o(t,e,n=[],i){const r=my(t),s=Xl("generator",y.bundleSpec);try{return await Ks("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Yr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),iE(e,Yr,i);try{return await Ks("generator",Yr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Yr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function wo(t,e=null){const n={...Xl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ks("review",Fp,vy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Vs(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=` + + `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` + + `):i.innerHTML=` + + `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Vs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Vs(t,"completed"))}function Qw(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 eb(t){at(parseInt(t.replace("step","")))}function at(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"),Jn();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 tb(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 xl(t){const e=Il(t);console.log(`Step 1 (Prompt Architect): ${nn(Ap)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(Fp)}`)}function zp(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function nb(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=Ei(y.artifactBundle)?.id||null)}const Vp="results-replacement-error";function ib(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Vp);if(!r)return;const s=wp(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=`${xo[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=()=>ki(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Cc(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Cc(){const t=document.getElementById(Vp);t&&(t.hidden=!0)}function Gp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),nb(e),Ai(),Bt(!0),Mr(),y.resultsViewMode=e.resultsViewMode||"summary",Tr(),kn(),ib(t,{stage:n,runId:i,retry:r}),pn())}async function Kp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Io();Pc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=zp();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + + + Refining...`});try{Cc();const r=bc(),s=r.id,o=yy({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."});Po({runId:e}),Lt(2,e),at(2),Fe(2,!0);const a=await _o(o,t,[],e);if(!le(e))return;y.step2Result=a,fo(),fn(2,e);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,e),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,ho(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=Ei(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ai();const f=oo(y.step3Result);Mr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=so(r,{architect:2,generator:2,review:3});Gp(r,{previous:i,stage:s,runId:e,retry:Kp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function Pc(t,e,n){const i=`${Et}/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 rb(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Yp(){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=Io();Pc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + + Fixing…`);const s=zp();try{Cc();const o=Yh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Ig(),Po({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await _o(o,n,[],i);if(!le(i))return;y.step2Result=a,fo(),fn(2,i);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,ho(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ai();const f=oo(y.step3Result);Mr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=so(o,{architect:2,generator:2,review:3});Gp(o,{previous:s,stage:a,runId:i,retry:Yp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function xr(){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=De.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Io();try{if(await hl,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await Pb()||!le(i)||(await Eb(),!le(i)))return;const r=Il(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),Nw(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Js(!0),xl(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Po({prompt:t,runId:i}),aE(a,l),at(1),Lt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await Xw(t,u);if(!le(i))return;y.step1Result=c,Ow(),fn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=xi(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Lt(2,i),Fe(2,!0);const p=await _o(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,fo(),fn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=xi(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const m=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,ho(),fn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Ai();const b=oo(y.step3Result);Mr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=so(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():Dn("Pipeline Failed",{error:r.message,effectiveModel:Il(document.getElementById("code-generator-model").value)}),at(s),Fe(s,!1),bg(r,{stage:s,runId:i}),Vs(s,"error")}finally{le(i)&&(y.isRunning=!1,Js(!1),pn())}}function sb(){const t=document.getElementById("code-generator-model").value,e=[Us,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + +Current: ${t} + +Options: +1. ${e[0]} +2. ${e[1]} + +Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],xr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],xr())}async function ob(){const t=Ec();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),vc();return}if(y.artifactBundle?.artifacts?.length>1){await ab();return}const{artifactType:i,artifactName:r,fileName:s}=jp(),o=qp(t,{artifactType:i,artifactName:r,fileName:s}),a=zw(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Rc(o,a,null,null)}async function ab(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),vc();return}const n=r_(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=vo(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};Rc(o,s,n.dependencies,n)}function lb(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    +

    FlutterFlow Commit Failed

    +

    ${W(t.error)}

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

    Errors:

    +
      `;for(const[r,s]of e.entries()){const o=rc(s);n+=`
    • + ${W(r)}: ${W(o)} +
    • `}n+="
    "}n+="
    ",n+=`
    + +
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Jp(t.error,e)}))}async function Jp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=Io(),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[p,h]of e.entries()){const g=rc(h);s+=`File: ${p} +Error: ${g} + +`}else s+=`${t} +`;const o=Yh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Po({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await _o(o,n,[],i);if(!le(i))return;y.step2Result=a,fo(),fn(2,i);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,ho(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ai();const f=oo(y.step3Result);Mr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=so(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),bg(s,{stage:o,runId:i,retry:()=>Jp(t,e)}),Vs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function cb(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 Zp(t){try{const e=await fetch(`${Et}/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 ub(t){try{const n=await(await fetch(`${Et}/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 db(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Gd(t,e){const n=Qp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,de=Kn({isLoading:!0}),localStorage.setItem(Bs,JSON.stringify({email:t,sessionToken:e})),i&&sg()}function Xp(){H.email=null,H.sessionToken=null,H.isVerified=!1,de=Kn({isResolved:!0}),localStorage.removeItem(Bs),localStorage.removeItem(js)}function Qp(){try{const t=localStorage.getItem(Bs);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Bs),{email:null,sessionToken:null}}}async function fb(){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 ub(e);Gd(n,i),eg();const r=Kd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){Kd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),bo(),ui(i,"error")}}else{const{email:n,sessionToken:i}=Qp();if(n&&i){const r=await db(i);r?Gd(r.email,r.sessionToken):Xp()}}Ac()}function hb(){try{localStorage.setItem(fl,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function Kd(){try{const t=localStorage.getItem(fl);if(localStorage.removeItem(fl),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>V0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function bo(){const t=document.getElementById("signin-modal");if(!t)return;hb(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ui(""),Ve(t)}function eg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function ui(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 pb(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=io(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"),ui("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=rp(n);r&&ui(r,"error");try{const s=await Zp(n),o=sc(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ui(sp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ui("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function gb(){H.email=null,H.sessionToken=null,H.isVerified=!1,de=Kn({isResolved:!0}),e0({storage:window.localStorage,onIdentityChanged:Ac,onPlanChanged:So})}const mb=n0({sendLink:Zp,getEmail:()=>H.email||"",onState:vb});function vb(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=sp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function yb(){await mb()}function _b(){const t=X_(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 wb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function bb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Ac(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Rb(),So()}async function tg(){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(J0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(K0,r.user_id),yt.token&&sessionStorage.setItem(Y0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),_n()}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 _a=null;function Eb(t=5e3){return yt.resolved?Promise.resolve():(_a||(_a=tg().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([_a,new Promise(e=>setTimeout(e,t))]))}function ng(){const t=xn();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Ar(){const t=ng();return t.month!==xn()?{count:0,month:xn()}:t}function Sb(){const e={count:Ar().count+1,month:xn()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Pi(){return!!de.isLoading}function Ot(){return!!de.isResolved}function xb(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(Ds,e)?e:null}function Ib(t){return t&&Object.entries(xp).find(([,e])=>e===t)?.[0]||null}function Jr(...t){return t.find(e=>e!=null&&e!=="")}function kb(...t){return t.find(e=>e&&typeof e=="object")||{}}function Cb(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=kb(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=Jr(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=Jr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=xb(Jr(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=Z0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Ib(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Jr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Eo(){return Ds[de.tier]??Ds.free}async function Pb(){if(H.isVerified&&(!Ot()||Pi())&&(await rg({force:!0}),So()),H.isVerified&&!Ot())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Ar(),e=Eo();if(t>=e)return ig(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 Yd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function ig(t,e,n={}){Bt(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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"),ki();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=de.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",H.isVerified),u.classList.remove("hidden"),n.openModal&&ki()}function Il(t){return de.tier==="free"&&ss.includes(t)?Us:t}function Ab(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=de.tier,r=!(H.isVerified&&!Ot())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=ss.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&ss.includes(e.value)&&(e.value=Us),e.disabled=!1,Ld.has(e)||(e.addEventListener("change",()=>{Ot()&&de.tier==="free"&&ss.includes(e.value)&&(e.value=Us,ki()),xl(e.value),dc()}),Ld.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(),xl(e.value)}function Fc(){const t=H.isVerified&&!!H.email,e=t&&Pi(),n=!t||Ot(),i=Ar(),r=n?i.count:0,s=n?Eo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Zl,u=n?de.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ng(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Ds.free} generations used`}}Fb()}function Fb(){if(!(H.isVerified&&!!H.email))return;const e=Pi(),n=Ot(),i=Ar(),r=n?i.count:0,s=n?Eo():0,o=Math.max(0,s-r),a=n?de.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Xi(Zi[a]??0,fc());h.textContent=`${S} / 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 S=Date.parse(de.periodEnd||""),P=n&&a!=="free"&&!!de.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Fc(),H.isVerified&&(Pi()||!Ot())){Yd();return}const{count:t}=Ar(),e=Eo();t>=e&&!y.isRunning&&!ay()?ig(t,e):Yd()}function Rb(){Fc()}async function rg(t={}){const e=t.force===!0;if(!H.isVerified||!H.sessionToken){de=Kn({isResolved:!0});return}de={...de,isLoading:!0,error:null};const n=H.sessionToken,i=localStorage.getItem(js);if(!e&&i)try{const{data:r,email:s,ts:o,version:a}=JSON.parse(i);if(a===Nd&&s===H.email&&Date.now()-o<300*1e3){de={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",i)}try{const s=await(await fetch(`${Et}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken,user_id:yt.userId})})).json();if(!H.isVerified||H.sessionToken!==n)return;if(s.error){if(["unauthorized","invalid session","expired session"].some(a=>String(s.error).toLowerCase().includes(a))){Xp(),Ac();return}de=Kn({isResolved:!1,error:s.error});return}de=Cb(s),localStorage.setItem(js,JSON.stringify({version:Nd,data:de,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),de={...de,isLoading:!1,isResolved:!1,error:r.message}}}function sg(){localStorage.removeItem(js)}async function Tb(t){if(!H.isVerified||!H.sessionToken){ag(),bo();return}if(!xp[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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:fc()})})).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 Mb(t){if(!H.isVerified||!H.sessionToken){bo();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Gs=new Set;function og(){Gs.forEach(t=>t.abort()),Gs.clear()}async function Ks(t,e,n,i={},r=[]){const o=new AbortController;Gs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(G0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Wn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=Iy(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),_n())}else Sb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Gs.delete(o)}}let kl=!1;function $b(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),sg(),kl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function Lb(){if(!kl)return;kl=!1;const t=de.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 So(){const t=H.isVerified&&!!H.email,e=de.tier,n=t&&Pi(),i=!t||Ot(),r=document.getElementById("subscription-tier-badge");if(r){const a=Zl,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"),Nb(i?e:null),Ab(),dc(),_n(),kg()}function Nb(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 Ob(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=fy[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 Cl(){const t=fc(),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=Xi(Zi.professional,t)),n&&(n.textContent=Xi(Zi.power,t)),i&&(i.textContent=Xi(Zi.professional,t)),r&&(r.textContent=Xi(Zi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function ki(){Cl();const t=document.getElementById("pricing-modal");t&&Ve(t),lw().then(()=>Cl())}function ag(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(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()=>{cy(),Xb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Bb(),window.__heroField=y0(),window.__pipelineLogo=E0(),_E(),uc=j0({onSubmit:xr}),hl=(async()=>{try{await fb(),$b(),await rg()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await hl,Lb(),So(),Cl(),Ob(),await Bw(),Mw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Dp(),tg();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(yc(),lo())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(gg(),$e.phaseId||Mc(),Zd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(Zd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,$c()},1e3))}),Hc()});function Bb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Db(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Dp()}let ar=null;async function Pl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ud,n=++ao,i=()=>e===Ud,r=gt;br=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==Ie)return Pl();if(n>un&&(un=n,gc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),br={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==Ie)return Pl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function jb(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=br;return!n||n.key!==Ie||n.generation!==gt?null:e}function Rc(t,e,n,i=null){ar={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,Pl();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function lg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),ar=null}function Ub(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 cg(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function ug(t){$c(),lb(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,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(rc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function dg(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 fg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Al=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Tc(t,{heading:e,title:n,guidance:i})}let Al=null;function hg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function Hb(){const t=Al;if(!t||Lc)return;Al=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);pg(),Nc(!0),Mc();try{$e.set("package");const n=d_(t.fileMap,t.landed,t.serializedYaml),i=await go(n,new Map),r=await yo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),$e.set("push");const o=await mo(e,s);if(o.success){Ys({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||po(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ys({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function pg(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function Wb(){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 Jd={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}},qb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function gg(){Un&&clearTimeout(Un),Un=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){gg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(ad(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Jd[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=Jd[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=qb.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(zb(e)),mg(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&&(ad(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function zb(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 Mc(t){$e.start(t)}function $c(){$e.stop()}function mg(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 Zd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,mg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function Vb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===Z.CODE_FILE):t.codeInfo?.codeType===Z.CODE_FILE}let Lc=!1;function Nc(t){Lc=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 Ys(t){$c(),Nc(!1);const e=vp(t);e===Ne.COMMITTED?cg(t):e===Ne.PARTIAL?dg(t):e===Ne.UNCONFIRMED?fg(t):ug(t)}async function Gb(){if(!ar){console.error("No pending commit data");return}if(Lc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=ar;if(ar=null,or=jb(),lg(),Nc(!0),Mc({withProvisioning:Vb(t)}),t.bundlePlan){const o=await Zw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});or=null,Ys(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=jp(),s=await Jw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});or=null,Ys(s)}window.runThinkingPipeline=xr;window.toggleStep=eb;window.toggleSection=Qw;window.selectWorkflowStep=at;window.copyCode=tb;window.retryWithDifferentModel=sb;window.openApiKeysModal=vc;window.closeApiKeysModal=Op;window.openComposerSettings=Np;window.closeComposerSettings=xw;window.walkthroughConnectAccount=Sw;window.closeWalkthroughModal=kw;window.openWalkthroughModal=Iw;window.advanceWalkthrough=yc;window.commitToFlutterFlow=Yw;function Kb(){y.isRunning||Bt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Yb(){Np();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Kb;window.openModelSelector=Yb;window.handlePromptImageSelect=ow;window.removePromptImage=aw;window.saveApiKeys=Aw;window.validateFlutterFlowConnection=wc;window.clearAllApiKeys=Fw;window.toggleKeyVisibility=Lw;window.handleWelcomeVideoEnd=Db;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=ob;window.updateFlutterFlowCredentialStatus=cb;window.openCommitConfirmModal=Rc;window.closeCommitConfirmModal=lg;window.closeCommitSuccessModal=Ub;window.closeCommitTerminalModal=pg;window.finishProvisionedDeploy=Hb;window.showCommitPartialModal=dg;window.showCommitUnconfirmedModal=fg;window.showCommitSuccessModal=cg;window.showCommitFailureModal=ug;window.toggleCodePreview=Wb;window.confirmCommitToFlutterFlow=Gb;window.runRefinement=Kp;window.regenerateFromPastedErrors=Yp;window.clearErrorInput=rb;window.setFlutterFlowEndpoint=ww;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=bo;window.closeSignInModal=eg;window.handleMagicLinkRequest=pb;window.handleSignOut=gb;window.handleSendNewLink=yb;window.handleClearCache=_b;window.handleDeleteAccount=wb;window.closeDeleteUnavailableModal=bb;window.startCheckout=Tb;window.openCustomerPortal=Mb;window.openPricingModal=ki;window.closePricingModal=ag;let us=null,vg=null,hn={1:"pending",2:"pending",3:"pending"},qn=1,Fl=null,Oc=null;const xo={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Jb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Zb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Io(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function yg(){y.runId+=1}function Bc(t){return document.getElementById(`pdot-${t}`)}const _g=window.matchMedia("(max-width: 920px)");function Xd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=_g.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Xb(){Xd(),_g.addEventListener("change",Xd)}function Qb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Js(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 ko(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){hn[t]=e;const n=Bc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=xo[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 eE(){return[1,2,3].filter(t=>hn[t]==="done").length}function Fr(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${tE()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function tE(){const t=33.333333333333336,e=hn[qn];if(e==="active"&&Fl!==null){const n=(Date.now()-Fl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:eE()/3*100}function Co(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?Zb[t]:Jb[t]),i&&(i.textContent=Qb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${xo[t]}${a}`}}function nE(t){hn[t]==="pending"||hn[t]==="skipped"||(Oc=t,[1,2,3].forEach(e=>{const n=Bc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Co(t))}function Dc(){Oc=null,[1,2,3].forEach(t=>{const e=Bc(t);e&&e.removeAttribute("aria-pressed")})}function wg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function iE(t,e,n){le(n)&&wg(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function jc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function rE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Gn()}function sE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function oE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=oE;function aE(t,e){Sp(t,document.getElementById("main-stage-container"),sE()),W0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function Po(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Rr(),kn(),Bt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),ko("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}vg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Dc(),jc(),wg(""),[1,2,3].forEach(a=>zn(a,"pending")),Lt(1,n),lE()}function Lt(t,e){le(e)&&(qn=t,Fl=Date.now(),Dc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),Co(t),Fr())}function fn(t,e){le(e)&&(zn(t,"done"),Oc===null&&Co(t,{done:!0}),Fr())}function bg(t,{stage:e=1,runId:n,retry:i=Eg}={}){if(!le(n))return;Ao(),Rr(),kn(),ko("failed"),Bt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Dc(),Co(e),Fr();const o=wp(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=`${xo[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>ki()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Rl}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Rl}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Rl(){yg(),og(),y.isRunning=!1,Js(!1),pn(),ko("settled"),kn(),Ao(),Rr(),jc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Bt(!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 Eg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),jc(),xr()}function lE(){Ao(),us=setInterval(()=>{const t=(Date.now()-vg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Fr()},250)}function Ao(){us&&(clearInterval(us),us=null)}let lr=null;function Rr(){lr&&(clearTimeout(lr),lr=null)}function Ai(){Ao(),Rr(),ko("settled"),Fr();const t=document.getElementById("pipeline-progress-fill");lr=setTimeout(()=>{lr=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ci(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Sg(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function cE(){return E_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function uE(t){return` +
    + ${Ci(t.severity)} +
    +
    ${W(t.message)}
    + ${t.suggestion?`
    ${W(t.suggestion)}
    `:""} + ${W(t.source)} +
    +
    + `}function dE(t){return` +
  • +
    + ${W(t.title)} + ${t.detail&&t.detail!==t.title?`

    ${W(t.detail)}

    `:""} +
    +
  • + `}function fE(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=>` +
    • + ${Ci(u.severity)} + + ${W(u.message)} + ${u.suggestion?`${W(u.suggestion)}`:""} + +
    • + `).join("")} +
    + `:"",a=t.warnings.length?` +
    +

    ${Ci("warning")} Bundle

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

    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=>` +
    1. + ${W(u.title)} + ${u.detail&&u.detail!==u.title?`${W(u.detail)}`:""} +
    2. + `).join("")} +
    +
    + `:"";e.innerHTML=` +
    +
    +

    ${W(t.title)}

    +

    ${W(t.summary)}

    +
    +
    Artifact${t.artifacts.length===1?"":"s"}
    ${t.artifacts.map(u=>W(u.artifactType||u.type||u.name)).join(" · ")}
    +
    Public API
    ${t.artifacts.flatMap(u=>u.publicApi||[]).map(W).join(" · ")||"No parameters returned"}
    +
    Manual Steps Required
    ${l||"None reported"}
    +
    Review
    ${W(t.status||"Not reported")}
    +
    + ${o} + ${a} +
    +
    + +
    + Is the generated code correct? +
    + + +
    + +
    +
    +
    + `}function hE(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(uE).join(""):`
    ${Ci(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` +
  • ${W(l.name)}${l.version?` ${W(l.version)}`:""}${l.reason?`

    ${W(l.reason)}

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

    ${W(l.description)}

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

    ${W(e.artifactName)}

    + ${e.description?`

    ${W(e.description)}

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

    Code Review findings

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

    Manual FlutterFlow steps for this file

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

    Dependencies

    +
      ${r}
    +
    +
    +

    Deployment

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

    Public API

    +
    ${o}
    +
    +
    +

    Imports

    +
    ${s}
    +
    +
    +

    Relationships

    +
      ${a}
    +
    +
    + `}function pE(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=""),Qd();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&&Uc(o.dataset.artifactId)},Qd()),e&&e.classList.add("visible")}function Qd(){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")xg();else{const a=s.dataset.artifactId;a&&Uc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function Tr(){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=cE(),o=Ec();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")}fE(s),pE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` +`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=bp(a),!rE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=hE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Mr(t,e){const n=document.getElementById("main-stage-container"),i=U0(n),r=document.body.classList.contains("results-fullscreen");Rr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),Bt(!0),y.selectedArtifactId||(y.selectedArtifactId=Ei(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Tr(),pn(),gE(),r||Sp(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function gE(){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 Uc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Tr()}function xg(){y.resultsViewMode="summary",Tr()}function mE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ec(),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 vE(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 Pc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function yE(){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 Ig(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function _E(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function Bt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function kg(){const t=H.isVerified&&!!H.email,e=de.tier||"free",n=t&&Pi(),i=!t||Ot(),s=n?"Checking…":i?Zl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Fc();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 wE(){kg();const t=document.getElementById("credits-modal");t&&Ve(t)}function bE(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function Cg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),uc?.cancelTyping?.(),y.isRunning&&(yg(),og(),y.isRunning=!1,Js(!1),Ai(),y.artifactBundle?Tr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")Bt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&Bt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ef=!1;function Hc(){const t=window.location.hash.replace(/^#/,"");Cg(t||"home",!1,ef),ef=!0}window.addEventListener("popstate",t=>{Hc()});window.addEventListener("hashchange",()=>{Hc()});window.copyResultsCode=mE;window.selectArtifact=Uc;window.selectResultsSummary=xg;window.submitResultsFeedback=vE;window.showErrorInputPanel=yE;window.hideErrorInputPanel=Ig;window.setGenerationStageVisible=Bt;window.switchView=Cg;window.selectPipelineStage=nE;window.editPipelinePrompt=Rl;window.retryPipelineRun=Eg;window.openCreditsModal=wE;window.closeCreditsModal=bE; diff --git a/dist/assets/index-DYbo9B-C.js b/dist/assets/index-DYbo9B-C.js deleted file mode 100644 index 12178ef..0000000 --- a/dist/assets/index-DYbo9B-C.js +++ /dev/null @@ -1,328 +0,0 @@ -(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 E=typeof window<"u"?window:void 0,Be=typeof globalThis<"u"?globalThis:E,qe=Be?.navigator,F=Be?.document,we=Be?.location,Rl=Be?.fetch,ya=Be!=null&&Be.XMLHttpRequest&&"withCredentials"in new Be.XMLHttpRequest?Be.XMLHttpRequest:void 0,Gc=Be?.AbortController,Fg=Be?.CompressionStream,Je=qe?.userAgent;function Zd(){return!(!E||E.navigator.onLine===!1)}var Ri=typeof globalThis<"u"?globalThis:E;Ri&&typeof self>"u"&&(Ri.self=Ri),Ri&&typeof File>"u"&&(Ri.File=function(){});var N=E??{},oe={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Kc(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 ce(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){Kc(s,i,r,o,a,"next",l)}function a(l){Kc(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 Xd(t,e){if(t==null)return{};var n={};for(var i in t)if({}.hasOwnProperty.call(t,i)){if(e.indexOf(i)!==-1)continue;n[i]=t[i]}return n}var Yc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Jc(t){return typeof t=="string"||t}function Zc(t){return typeof t=="string"?t:void 0}var Ti,Rg=["$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"],Kt=(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})({}),Xc=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Tg=["$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"],Mg=["token"],Qd="NativeGzipValidationError",_a=t=>t.length>=2&&t[0]===31&&t[1]===139,Qc=(t,e)=>t===Xc.GZipJS||e===Xc.GZipJS||e==="gzip",eu=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Nr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=Qd,e},$g=(function(){var t=ce((function*(e,n){18>e.size&&Nr("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());_a(i)&&i[2]===8||Nr("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Ti)return Ti;Ti=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;Ti[c]=d>>>0}return Ti})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Nr("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Nr("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function wa(){return wa=ce((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=ce((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 $g(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),wa.apply(this,arguments)}var Lg=["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"],tu=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Lg.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Js=function(t){return t.trim()},ba=function(t){return t.replace(/^\$/,"")};function ef(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 tf=Object.prototype,nf=tf.hasOwnProperty,Zs=tf.toString,U=Array.isArray||function(t){return Zs.call(t)==="[object Array]"},Ue=t=>typeof t=="function",me=t=>t===Object(t)&&!U(t),rn=t=>{if(me(t)){for(var e in t)if(nf.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,ee=t=>Zs.call(t)=="[object String]",Ea=t=>ee(t)&&t.trim().length===0,et=t=>t===null,q=t=>C(t)||et(t),Ae=t=>Zs.call(t)=="[object Number]"&&t==t,Vt=t=>Ae(t)&&t>0,wt=t=>Zs.call(t)==="[object Boolean]",Ng=t=>t instanceof FormData,Og=t=>j(Tg,t),Bg=t=>j(Mg,t);function rf(t){return t===null||typeof t!="object"}function us(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Tl(t){return typeof Event<"u"&&sf(t,Event)}function sf(t,e){try{return t instanceof e}catch{return!1}}var Dg=[!0,"true",1,"1","yes"],Bo=t=>j(Dg,t),jg=[!1,"false",0,"0","no"];function Rt(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Ae(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),Rt(r||n,e,n,i))}class Ug{constructor(e){this.tt={},this.et=e.et,this.it=Rt(e.bucketSize,0,100,e.rt),this.nt=Rt(e.refillRate,0,this.it,e.rt),this.st=Rt(e.refillInterval,0,864e5,e.rt)}ot(e,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 lt="Mobile",ds="iOS",sn="Android",gi="Tablet",of=sn+" "+gi,af="iPad",lf="Apple",cf=lf+" Watch",Qi="Safari",mi="BlackBerry",uf="Samsung",df=uf+"Browser",ff=uf+" Internet",Hn="Chrome",Hg=Hn+" OS",hf=Hn+" "+ds,Ml="Internet Explorer",pf=Ml+" "+lt,$l="Opera",Wg=$l+" Mini",Ll="Edge",gf="Microsoft "+Ll,ui="Firefox",mf=ui+" "+ds,lr="Nintendo",cr="PlayStation",di="Xbox",vf=sn+" "+lt,yf=lt+" "+Qi,Wi="Windows",Sa=Wi+" Phone",nu="Nokia",xa="Ouya",_f="Generic",qg=_f+" "+lt.toLowerCase(),wf=_f+" "+gi.toLowerCase(),Ia="Konqueror",bf="Oculus Browser",fs="Vivaldi",Ef="Yandex",hs="Whale",ka="DuckDuckGo",Sf="Pale Moon",ps="Waterfox",er="Brave",xf="Google Search App",xe="(\\d+(\\.\\d+)?)",Do=new RegExp("Version/"+xe),zg=new RegExp(di,"i"),Vg=new RegExp(cr+" \\w+","i"),Gg=new RegExp(lr+" \\w+","i"),Nl=new RegExp(mi+"|PlayBook|BB10","i"),Kg={"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"},If=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?er:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?xf:j(t," OPR/")&&j(t,"Mini")?Wg:j(t," OPR/")?$l:Nl.test(t)?mi:j(t,"IE"+lt)||j(t,"WPDesktop")?pf:j(t,"OculusBrowser")?bf:j(t,df)?ff:j(t,Ll)||j(t,"Edg/")?gf:j(t,fs+"/")?fs:j(t,"YaBrowser/")?Ef:j(t,hs+"/")?hs:j(t,ka+"/")||j(t,"Ddg/")?ka:j(t,"FBIOS")?"Facebook "+lt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?hf:j(t,"CrMo")||j(t,Hn)?Hn:j(t,sn)&&j(t,Qi)?vf:j(t,"FxiOS")?mf:j(t.toLowerCase(),Ia.toLowerCase())?Ia:j(t,er+"/")?er:((s,o)=>o&&j(o,lf)||(function(a){return j(a,Qi)&&!j(a,Hn)&&!j(a,sn)})(s))(t,e)?j(t,lt)?yf:Qi:j(t,"PaleMoon/")?Sf:j(t,ps+"/")?ps:j(t,ui)?ui:j(t,"MSIE")||j(t,"Trident/")?Ml:j(t,"Gecko")?ui:"")},Yg={[pf]:[new RegExp("rv:"+xe)],[gf]:[new RegExp(Ll+"?\\/"+xe)],[Hn]:[new RegExp("("+Hn+"|CrMo)\\/"+xe)],[hf]:[new RegExp("CriOS\\/"+xe)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+xe)],[Qi]:[Do],[yf]:[Do],[$l]:[new RegExp("(Opera|OPR)\\/"+xe)],[ui]:[new RegExp(ui+"\\/"+xe)],[mf]:[new RegExp("FxiOS\\/"+xe)],[Ia]:[new RegExp("Konqueror[:/]?"+xe,"i")],[mi]:[new RegExp(mi+" "+xe),Do],[vf]:[new RegExp("android\\s"+xe,"i")],[ff]:[new RegExp(df+"\\/"+xe)],[bf]:[new RegExp("OculusBrowser\\/"+xe)],[fs]:[new RegExp(fs+"\\/"+xe)],[Ef]:[new RegExp("YaBrowser\\/"+xe)],[hs]:[new RegExp(hs+"\\/"+xe)],[er]:[new RegExp(er+"\\/"+xe)],[ka]:[new RegExp("(DuckDuckGo|Ddg)\\/"+xe)],[Sf]:[new RegExp("PaleMoon\\/"+xe)],[ps]:[new RegExp(ps+"\\/"+xe)],[xf]:[new RegExp("GSA\\/"+xe)],[Ml]:[new RegExp("(rv:|MSIE )"+xe)],Mozilla:[new RegExp("rv:"+xe)]},Jg=function(t,e,n,i){var r=If(t,e,n,i),s=Yg[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},iu=[[new RegExp(di+"; "+di+" (.*?)[);]","i"),t=>[di,t&&t[1]||""]],[new RegExp(lr,"i"),[lr,""]],[new RegExp(cr,"i"),[cr,""]],[Nl,[mi,""]],[new RegExp(Wi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Sa,""];if(new RegExp(lt).test(e)&&!/IEMobile\b/.test(e))return[Wi+" "+lt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Kg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Wi,i]}return[Wi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[ds,[t[3],t[4],t[5]||"0"].join(".")]:[ds,""]],[/(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("("+sn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+sn+")","i"),t=>t&&t[2]?[sn,[t[2],t[3],t[4]||"0"].join(".")]:[sn,""]],[/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/,[Hg,""]],[/Linux|debian/i,["Linux",""]]],ru=function(t){return Gg.test(t)?lr:Vg.test(t)?cr:zg.test(t)?di:new RegExp(xa,"i").test(t)?xa:new RegExp("("+Sa+"|WPDesktop)","i").test(t)?Sa:/iPad/.test(t)?af:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?cf:Nl.test(t)?mi:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(nu,"i").test(t)?nu:/(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(lt).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)?sn:of:new RegExp("(pda|"+lt+")","i").test(t)?qg:new RegExp(gi,"i").test(t)&&!new RegExp(gi+" pc","i").test(t)?wf:""},Zg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function su(t,e){return typeof(n=t)=="string"&&Zg.test(n)?t:e();var n}function wn(t){return t&&t.split("#")[0]}function Ol(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function ou(t,e,n){return kf.apply(this,arguments)}function kf(){return(kf=ce((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 Xg=t=>t instanceof Error,Cf={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}},Qg=Cf.info;function Pf(t){if(wt(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=>Pf(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function gs(t){var e=[];for(var n in t){var i=t[n];et(i)||C(i)||e.push({key:n,value:Pf(i)})}return e}function em(t,e){var n=Cf[t.level||"info"]||Qg,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),q(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),q(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:gs(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 Af(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 Ff(t,e,n,i){return{resourceLogs:[{resource:{attributes:gs(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let tm=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:em(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 ce((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return ce((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Kt.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=Ff(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(Kt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return ce((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Kt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Kt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Af(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Kt.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(Kt.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(Kt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return ce((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield ou(n,t):yield n}))()}flushWithTimeout(t){var e=this;return ce((function*(){var n=e.flush();yield ou(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 jo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function au(t){return String(t)+"000000"}function lu(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 nm=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=ce((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=lu(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(jo.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,jo)]+=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 ce((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:gs(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=au(Date.now()),n=new Map;for(var i of t.values()){var r,s=lu(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=gs((r=i.attributes)!==null&&r!==void 0?r:{}),l=au(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:jo})}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 Or,cu,Uo;function im(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Uo&&n.length===cu||(cu=n.length,Uo=n.reduce(((i,r)=>{Or||(Or={});var s=Or[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,Or[r]=[u,c];break}}return i}),{})),Uo}}class rm{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 ce((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 ce((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:im(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 vi="?";function Ca(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?vi:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Rf=(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]:vi,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},sm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,om=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,am=/\((\S*)(?::(\d+))(?::(\d+))\)/,lm=(t,e)=>{var n=sm.exec(t);if(n)return Ca(e,n[1],vi,+n[2],+n[3]);var i=om.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=am.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Rf(i[1]||vi,i[2]);return Ca(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},cm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,um=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dm=(t,e)=>{var n=cm.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=um.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]||vi,o=Rf(s,r);return Ca(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},uu=/\(error: (.*)\)/;class fm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=ee(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 us(e,"DOMException")}isDOMError(e){return us(e,"DOMError")}}class hm{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 sf(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 pm{constructor(){}match(e){return!!us(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 ee(e.message)&&e.message.length>0}pe(e){var n=e;if(ee(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 gm=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class mm{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(gm);return r&&(n=r[1],i=r[2]),[n,i]}}var vm=["fatal","error","warning","log","info","debug"];function Tf(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 ym{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: "+Tf(e)}isSeverityLevel(e){return ee(e)&&!Ea(e)&&vm.indexOf(e)>=0}getStack(e){try{return ee(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ee(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(Xg(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class _m{match(e){return Tl(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Tf(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class wm{match(e){return rf(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 bm{match(e){return us(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 rf(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 ms="$message",vs="$timestamp",Em=new Set([ms,vs]),Ho={enabled:!0,max_bytes:32768};function ys(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Ho.enabled,max_bytes:xm(t.max_bytes,Ho.max_bytes)}:k({},Ho)}class Sm{constructor(e){this.Ke=[],this.Je=0,this.Ne=ys(e)}setConfig(e){this.Ne=ys(e),this.Xe()}add(e){var n=(function(r){var s;try{s=ef(r)}catch{return}try{var o=JSON.parse(s);if(!me(o))return;var a=o,l=a[ms],u=a[vs];return!ee(l)||l.trim().length===0||!ee(u)&&!Ae(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 xm(t,e){if(!Ae(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Mf=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(E&&(oe.DEBUG||E.POSTHOG_DEBUG||n)&&!C(E.console)&&E.console){for(var s=("__rrweb_original__"in E.console[r])?E.console[r].__rrweb_original__:E.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)=>Mf(t+" "+r,s)};return i},A=Mf("[PostHog.js]"),ve=A.createLogger,Im=ve("[ExternalScriptsLoader]"),Wo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Im.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)};N.__PosthogExtensions__=N.__PosthogExtensions__||{},N.__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)}},N.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);Wo(t,i,n)};oe.DEBUG=!1,oe.LIB_VERSION="1.415.7",oe.LIB_NAME="web";var $f="$people_distinct_id",ur="$device_id",qo="$device_model",qi="__alias",zi="__timers",Pa="$autocapture_disabled_server_side",Aa="$heatmaps_enabled_server_side",Fa="$exception_capture_enabled_server_side",Ra="$error_tracking_suppression_rules",Ta="$error_tracking_capture_extension_exceptions",Ma="$web_vitals_enabled_server_side",Bl="$dead_clicks_enabled_server_side",Dl="$product_tours_enabled_server_side",$a="$web_vitals_allowed_metrics",jn="$session_recording_remote_config",Lf="$replay_sample_rate",Nf="$replay_override_sampling",Of="$replay_override_linked_flag",Bf="$replay_override_url_trigger",Df="$replay_override_event_trigger",ai="$sesid",jl="$session_is_sampled",$n="$enabled_feature_flags",Vi="$active_feature_flags",Jr="$early_access_features",La="$feature_flag_details",Gi="$feature_flag_payloads",Zr="$feature_flag_request_id",_s="$minimal_flag_called_events",Pt="$override_feature_flags",Ln="$override_feature_flag_payloads",Gt="$stored_person_properties",Nn="$stored_group_properties",Na="$surveys",ws="$surveys_loaded_at",Oa="$surveys_activated",Xr="$surveys_activated_session",Qr="$surveys_activated_timestamps",Ki="ph_product_tours",Bn="$flag_call_reported",Yi="$flag_call_reported_session_id",es="$feature_flag_errors",tr="$feature_flag_evaluated_at",ft="$user_state",Ba="$client_session_props",Da="$capture_rate_limit",ja="$initial_campaign_params",Ua="$initial_referrer_info",bs="$initial_person_info",Es="$epp",Br="$posthog_cookieless",jf="$cookieless_mode",Uf="$sdk_debug_extensions_init_method",Hf="$sdk_debug_extensions_init_time_ms",Wf="$sdk_debug_recording_script_not_loaded",Ul="PostHog loadExternalDependency extension not found.",On="on_reject",Xt="always",ei="anonymous",Pn="identified",Ha="identified_only",Ss="visibilitychange",xs="beforeunload",si="$pageview",zo="$pageleave",Vo="$identify",du="$groupidentify";function Dr(t,e){U(t)&&t.forEach(e)}function ae(t,e){if(!q(t))if(U(t))t.forEach(e);else if(Ng(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)nf.call(t,n)&&e(t[n],n)}var ge=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 ts(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 fu=function(t){try{return t()}catch{return}},km=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 ae(t,(function(n,i){(ee(n)&&n.length>0||Ae(n))&&(e[i]=n)})),e},Cm=["herokuapp.com","vercel.app","netlify.app"];function Pm(t){var e=t?.hostname;if(!ee(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Cm)if(n===i)return!1;return!0}function be(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 Wa(t){return t.name==="ph_toolbar_internal"}var qf=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 Ae(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 Am{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 Fm}}var hu,zf=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};E&&!C(E.crypto)&&crypto.getRandomValues&&(zf=t=>crypto.getRandomValues(t));class Fm{nextUint32(){return this.R.length>this.O||(zf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Yt=()=>Rm().toString(),Rm=()=>(hu||(hu=new Am)).generate(),Mi="",Tm=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:qf,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(h,g){if(g===void 0&&(g=F),Mi)return Mi;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),b="dmn_chk_"+Yt();!Mi&&v--;){var w=m.slice(v).join("."),_=b+"=1;domain=."+w+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(b)&&(g.cookie=_+";max-age=0",Mi=w)}return Mi})(c);if(!f){var p=(h=>{var g=h.match(Tm);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}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}}},Go=null,de={N(){if(!et(Go))return Go;var t=!0;if(C(E))t=!1;else try{var e="__mplssupport__";de.F(e,"xyz"),de.P(e)!=='"xyz"'&&(t=!1),de.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Go=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return E?.localStorage.getItem(t)}catch(e){de.j(e)}return null},H(t){try{return JSON.parse(de.P(t))||{}}catch{}return null},F(t,e){try{return E?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){de.j(n)}return!1},q(t){try{E?.localStorage.removeItem(t)}catch(e){de.j(e)}}},Mm=[ur,"distinct_id",ai,jl,Es,bs,ft],jr={},$m={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>jr[t]||null,H:t=>jr[t]||null,F:(t,e)=>(jr[t]=e,!0),q(t){delete jr[t]}},An=null,Ie={N(){if(!et(An))return An;if(An=!0,C(E))An=!1;else try{var t="__support__";Ie.F(t,"xyz"),Ie.P(t)!=='"xyz"'&&(An=!1),Ie.q(t)}catch{An=!1}return An},j(t){A.error("sessionStorage error: ",t)},P(t){try{return E?.sessionStorage.getItem(t)}catch(e){Ie.j(e)}return null},H(t){try{return JSON.parse(Ie.P(t))||null}catch{}return null},F(t,e){try{return E?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){Ie.j(n)}return!1},q(t){try{E?.sessionStorage.removeItem(t)}catch(e){Ie.j(e)}}};class Lm{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===Xt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===On}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 Bo(e)?1:j(jg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?de:Qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Qt:de;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Bo(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[qe?.doNotTrack,qe?.msDoNotTrack,N.doNotTrack].some((e=>Bo(e)))}}function Vf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Ue(i))return e;try{var r=i(e);return ee(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var Gf="__POSTHOG_TOOLBAR__",Nm=1,Om=3,Bm=11;function pu(t){return t instanceof Element&&(t.id===Gf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function bn(t){return!!t&&t.nodeType===Nm}function rt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Kf(t){return!!t&&t.nodeType===Om}function Yf(t){return!!t&&t.nodeType===Bm&&bn(t.host)}var Jf=1e3;function Wl(t){return t?Js(t).split(/\s+/):[]}function gu(t,e){var n=(function(i){var r,s=E==null||(r=E.location)==null?void 0:r.href;return C(s)?void 0:Vf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function ks(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 Wl(e)}function Zf(t){return q(t)?null:Js(t).split(/(\s+)/).filter((e=>nr(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function dr(t){var e="";return za(t)&&!th(t)&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;Kf(n)&&n.textContent&&(e+=(i=Zf(n.textContent))!==null&&i!==void 0?i:"")})),Js(e)}function Ko(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var ql=["a","button","form","input","select","textarea","label"];function qa(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 Xf(t){var e=t.parentNode;return!(!e||!bn(e))&&e}var Dm=[".ph-no-autocapture","[data-ph-no-autocapture]"],Qf=["next","previous","prev",">","<"],jm=[...Qf,"+","-","−","–"],mu=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,vu=[".ph-no-rageclick",".ph-no-capture"],Um=["","text","search","email","password","url","tel","number"];function yu(t,e){if(!E||zl(t))return!1;var n,i,r,s,o;if(wt(e)?(n=!!e&&vu,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:vu,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!bn(l))&&(!!rt(l,"textarea")||(rt(l,"input")?j(Um,(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=eh(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=Qf;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,p=d.ariaLabel;return c.some((h=>mu(f,h)||mu(p,h)))}))})(i,a.map((l=>{var u;return{safeText:dr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!qa(a,n)}var zl=t=>!t||rt(t,"html")||!bn(t),eh=(t,e)=>{if(!E||zl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!rt(r,"body");)if(Yf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=Xf(r);if(!s)break;if(e||ql.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=E.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function za(t){for(var e=new Set,n=0,i=t;i.parentNode&&!rt(i,"body");i=i.parentNode){if(n++>=Jf||e.has(i))return!1;e.add(i);var r=ks(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(ks(t),"ph-include"))return!0;var s=t.type||"";if(ee(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!ee(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 th(t){return!!(rt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||rt(t,"select")||rt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var _u=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}))$"),wu=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Hm=[16,15,14,13],Wm=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),bu=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Eu=/[0-9A-Za-z_]/;function qm(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 nr(t,e){if(e===void 0&&(e=!0),q(t))return!1;if(ee(t)){t=Js(t);var n=e?_u.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(wu.lastIndex=0;s=wu.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of Hm){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(_u.test(d)&&qm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Wm.test(t):(function(r){var s;for(bu.lastIndex=0;s=bu.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&Eu.test(o)&&Eu.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Su(t){var e=dr(t);return nr(e=(e+" "+nh(t)).trim())?e:""}function nh(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=dr(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+nh(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function xu(t){return t.replace(/"|\\"/g,'\\"')}function zm(t){var e=t.attr__class;if(e)return U(e)?e:Wl(e)}var Ur=ve("[Dead Clicks]"),Vm=()=>!0,Gm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(Bl)),i=t.instance.config.capture_dead_clicks;return wt(i)?i:!!me(i)||n};class Iu{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({[Bl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=N.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Ur.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=N.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=me(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=N.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),Ur.info("starting...")}}else Ur.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Ur.info("stopping..."))}}var Yo=ve("[SegmentIntegration]"),ih="posthog-js";function rh(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,p,h,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,b=((d=c.exception)==null?void 0:d.values)||[],w=b.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=b[0])==null?void 0:f.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=b[0])==null?void 0:h.value)||c.message,$sentry_exception_type:(g=b[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 Km{constructor(e,n,i,r,s,o){this.name=ih,this.setupOnce=function(a){a(rh(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class ku{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=E?.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?Rt(a/o,0,1,A):1,p=o>1?Rt(l/o,0,1,A):1,h=u>1?Rt(c/u,0,1,A):1,g=u>1?Rt(d/u,0,1,A):1;r=ge(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Jo=["flags","surveys"],Ym={[$f]:{exposure:"hidden"},[qi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[zi]:{exposure:"hidden"},[Pa]:{exposure:"event"},[Aa]:{exposure:"hidden"},[Fa]:{exposure:"event"},[Ra]:{exposure:"hidden"},[Ta]:{exposure:"event"},[Ma]:{exposure:"event"},[Bl]:{exposure:"event"},[Dl]:{exposure:"hidden"},[$a]:{exposure:"event"},[jn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[ai]:{exposure:"hidden"},[jl]:{exposure:"event"},[Lf]:{exposure:"event",shouldSkipFromEventProperties:t=>et(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"},[$n]:{exposure:"hidden",storageGroup:"flags"},[Vi]:{exposure:"hidden",storageGroup:"flags"},[Jr]:{exposure:"hidden"},[La]:{exposure:"hidden",storageGroup:"flags"},[Gi]:{exposure:"hidden",storageGroup:"flags"},[Zr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[_s]:{exposure:"hidden",storageGroup:"flags"},[Pt]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Gt]:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[Na]:{exposure:"hidden",storageGroup:"surveys"},[ws]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Oa]:{exposure:"event"},[Xr]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[Ki]:{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"},[Bn]:{exposure:"hidden"},[Yi]:{exposure:"hidden"},[es]:{exposure:"hidden"},[tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[Ba]:{exposure:"hidden"},[Da]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[Ua]:{exposure:"hidden"},[bs]:{exposure:"hidden"},[Es]:{exposure:"hidden"},[Nf]:{exposure:"event"},[Of]:{exposure:"event"},[Bf]:{exposure:"event"},[Df]:{exposure:"event"},[Uf]:{exposure:"event"},[Hf]:{exposure:"event"},[Wf]:{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"}},Jm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Fn=t=>{var e=Ym[t];if(e)return e;for(var n of Jm){var i=n[1];if(t.indexOf(n[0])===0)return i}},li=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return ef(t)}},Cs=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},yi=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," ")},fr=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},Ps=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},sh=(t,e)=>t>=e&&Zd(),oh=(t,e,n,i)=>{if(t===0){if(Zd()){var r=e+1;return r===n&&i(),r}return e}return 0},Hr="https?://(.*)",_i=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Zm=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",..._i],hr="",Xm=["li_fat_id"];function ah(t,e,n){if(!F)return{};var i,r=e?[..._i,...n||[]]:[],s=lh(fr(F.URL,r,hr),t),o=(i={},ae(Xm,(function(a){var l=qf(a);i[a]=l||null})),i);return ge(o,s)}function lh(t,e){var n=Zm.concat(e||[]),i={};return ae(n,(function(r){var s=yi(t,r);i[r]=s||null})),i}function ch(t){var e=(function(s){return s?s.search(Hr+"google.([^/?]*)")===0?"google":s.search(Hr+"bing.com")===0?"bing":s.search(Hr+"yahoo.com")===0?"yahoo":s.search(Hr+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",i={};if(!et(e)){i.$search_engine=e;var r=F?yi(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Cu(){return navigator.language||navigator.userLanguage}var As="$direct";function uh(){return F?.referrer||As}function dh(t,e,n){n===void 0&&(n=!1);var i=t?[..._i,...e||[]]:[],r=n?wn(we?.href):we?.href,s=r?.substring(0,1e3);return{r:uh().substring(0,1e3),u:s?fr(s,i,hr):void 0}}function fh(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?wn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==As?As:(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=lh(s);ge(o,l)}if(i){var u=ch(i);ge(o,u)}return o}function hh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Qm(){try{return new Date().getTimezoneOffset()}catch{return}}var ev={flags:tr,surveys:ws},tv=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ti="main";class Zo{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(),E){var r=()=>this.flush();be(E,"beforeunload",r,{capture:!1}),be(E,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Ae(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){tv.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=[...Mm,...o];return k({},de,{H(u){try{var c={};try{c=Qt.H(u)||{}}catch{}var d,f=JSON.parse(de.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];et(g)||g===""||(p[h]=g)}d=ge(f,p)}else d=ge(c,f);return de.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=de.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Qt.F(u,m,d,f,p,h)}catch(v){de.j(v)}return g},q(u,c){try{E?.localStorage.removeItem(u),Qt.q(u,c)}catch(d){de.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&de.N()?(n=de,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&Ie.N()?n=Ie:s==="memory"?n=$m: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 ae(this.props,((n,i)=>{var r=Fn(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=ge({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Jo){var n=de.H(this.Si(e));if(n&&!rn(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ge(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Fn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=ev[e];if(!i)return!1;var r=n[i],s=this.props[i];return Ae(r)&&Ae(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Fn(e))==null?void 0:n.storageGroup:void 0,r=i?de.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,ti))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,ti),Jo)){var s,o=i[r];(!rn(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(de,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ae(this.props,((i,r)=>{var s,o=(s=Fn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===ti)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ae(e,((r,s)=>{var o;i[s]=(o=Fn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===ti||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!==ti&&(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 Jo)de.q(this.Si(r));i?delete this.ci[ti]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(me(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ae(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(me(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ae(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||me(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=ah(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);rn(Hl(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?ch(e):{})}update_referrer_info(){var e;this.register_once({$referrer:uh(),$referring_domain:F!=null&&F.referrer&&((e=Cs(F.referrer))==null?void 0:e.host)||As},void 0)}set_initial_person_info(){this.props[ja]||this.props[Ua]||this.register_once({[bs]:dh(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={};ae([Ua,ja],(r=>{var s=this.props[r];s&&ae(s,(function(o,a){e["$initial_"+ba(a)]=o}))}));var n=this.props[bs];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=fh(r,s),a={};return ae(o,(function(l,u){a["$initial_"+ba(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ge(e,i)}return e}safe_merge(e){return ae(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,p)=>f===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[zi]||{};i[e]=n,this.Pi(zi,i),this.save()}remove_event_timer(e){var n=this.props[zi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(zi,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=Fn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Fn(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&&Ue(n.then)&&n.then(void 0,(()=>{}))}}}}var He={GZipJS:"gzip-js",Base64:"base64"},$i={Activation:"events",Cancellation:"cancelEvents"},Xo={Popover:"popover",API:"api",Widget:"widget"},en={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Qo={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},Va={Popover:"popover",Inline:"inline"},nv={SHOWN:"product tour shown"},Pu={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Au=ve("[RateLimiter]");class iv{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=>{Au.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Au.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=(Ae(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")&&we!=null&&we.pathname)return""+((e=we.origin)!==null&&e!==void 0?e:"")+we.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 mn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void mn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return mn.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){mn.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||mn.warn("Failed to fetch remote config from PostHog."):mn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){mn.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){mn.error("Error loading feature flags",r)}}}var pt=Uint8Array,Qe=Uint16Array,wi=Uint32Array,Vl=new pt([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]),Gl=new pt([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]),Fu=new pt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),gh=function(t,e){for(var n=new Qe(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]},mh=gh(Vl,2),Ga=mh[1];mh[0][28]=258,Ga[258]=28;for(var Ru=gh(Gl,0)[1],vh=new Qe(32768),Ee=0;32768>Ee;++Ee){var ni=(43690&Ee)>>>1|(21845&Ee)<<1;vh[Ee]=((65280&(ni=(61680&(ni=(52428&ni)>>>2|(13107&ni)<<2))>>>4|(3855&ni)<<4))>>>8|(255&ni)<<8)>>>1}var ir=function(t,e,n){for(var i=t.length,r=0,s=new Qe(e);i>r;++r)++s[t[r]-1];var o,a=new Qe(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Qe(i),r=0;i>r;++r)o[r]=vh[a[t[r]-1]++]>>>15-t[r];return o},Vn=new pt(288);for(Ee=0;144>Ee;++Ee)Vn[Ee]=8;for(Ee=144;256>Ee;++Ee)Vn[Ee]=9;for(Ee=256;280>Ee;++Ee)Vn[Ee]=7;for(Ee=280;288>Ee;++Ee)Vn[Ee]=8;var Fs=new pt(32);for(Ee=0;32>Ee;++Ee)Fs[Ee]=5;var rv=ir(Vn,9),sv=ir(Fs,5),yh=function(t){return(t/8>>0)+(7&t&&1)},_h=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Qe?Qe:t instanceof wi?wi:pt)(n-e);return i.set(t.subarray(e,n)),i},qt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Li=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},ea=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 pt(0),0];if(r==1){var o=new pt(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 p=new Qe(f+1),h=Ka(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var b=s[i].s;if(e>=p[b])break;g+=v-(1<>>=m;g>0;){var w=s[i].s;e>p[w]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new pt(p),h]},Ka=function(t,e,n){return t.s==-1?Math.max(Ka(t.l,e,n+1),Ka(t.r,e,n+1)):e[t.s]=n},Tu=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Qe(++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]},Ni=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Ya=function(t,e,n){var i=n.length,r=yh(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)},Mu=function(t,e,n,i,r,s,o,a,l,u,c){qt(e,c++,n),++r[256];for(var d=ea(r,15),f=d[0],p=d[1],h=ea(s,15),g=h[0],m=h[1],v=Tu(f),b=v[0],w=v[1],_=Tu(g),x=_[0],I=_[1],T=new Qe(19),S=0;b.length>S;++S)T[31&b[S]]++;for(S=0;x.length>S;++S)T[31&x[S]]++;for(var P=ea(T,7),R=P[0],L=P[1],$=19;$>4&&!R[Fu[$-1]];--$);var O,J,G,M,K=u+5<<3,ie=Ni(r,Vn)+Ni(s,Fs)+o,B=Ni(r,f)+Ni(s,g)+o+14+3*$+Ni(T,R)+(2*T[16]+3*T[17]+7*T[18]);if(ie>=K&&B>=K)return Ya(e,c,t.subarray(l,l+u));if(qt(e,c,1+(ie>B)),c+=2,ie>B){O=ir(f,p),J=f,G=ir(g,m),M=g;var Z=ir(R,L);for(qt(e,c,w-257),qt(e,c+5,I-1),qt(e,c+10,$-4),c+=14,S=0;$>S;++S)qt(e,c+3*S,R[Fu[S]]);c+=3*$;for(var se=[b,x],Ce=0;2>Ce;++Ce){var Q=se[Ce];for(S=0;Q.length>S;++S)qt(e,c,Z[ue=31&Q[S]]),c+=R[ue],ue>15&&(qt(e,c,Q[S]>>>5&127),c+=Q[S]>>>12)}}else O=rv,J=Vn,G=sv,M=Fs;for(S=0;a>S;++S)if(i[S]>255){var ue;Li(e,c,O[257+(ue=i[S]>>>18&31)]),c+=J[ue+257],ue>7&&(qt(e,c,i[S]>>>23&31),c+=Vl[ue]);var ye=31&i[S];Li(e,c,G[ye]),c+=M[ye],ye>3&&(Li(e,c,i[S]>>>5&8191),c+=Gl[ye])}else Li(e,c,O[i[S]]),c+=J[i[S]];return Li(e,c,O[256]),c+J[256]},ov=new wi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),av=(function(){for(var t=new wi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),ta=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function lv(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=av[255&p^f[h]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,p,h,g,m){var v=d.length,b=new pt(h+v+5*(1+Math.floor(v/7e3))+g),w=b.subarray(h,b.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=Ya(w,_,d.subarray(x,I)):(w[x]=!0,_=Ya(w,_,d.subarray(x,v)))}else{for(var T=ov[f-1],S=T>>>13,P=8191&T,R=(1<x;++x){var ue=G(x),ye=32767&x,je=$[ue];if(L[ye]=je,$[ue]=ye,x>=Ce){var St=v-x;if((B>7e3||se>24576)&&St>423){_=Mu(d,w,0,M,K,ie,Z,se,Q,x-Q,_),se=B=Z=0,Q=x;for(var _e=0;286>_e;++_e)K[_e]=0;for(_e=0;30>_e;++_e)ie[_e]=0}var tt=2,xt=0,Cn=P,Le=ye-je&32767;if(St>2&&ue==G(x-Le))for(var Re=Math.min(S,St)-1,Dt=Math.min(32767,x),Zn=Math.min(258,St);Dt>=Le&&--Cn&&ye!=je;){if(d[x+tt]==d[x+tt-Le]){for(var Ke=0;Zn>Ke&&d[x+Ke]==d[x+Ke-Le];++Ke);if(Ke>tt){if(tt=Ke,xt=Le,Ke>Re)break;var Xn=Math.min(Le,Ke-2),jt=0;for(_e=0;Xn>_e;++_e){var Ut=x-Le+_e+32768&32767,ut=Ut-L[Ut]+32768&32767;ut>jt&&(jt=ut,je=Ut)}}}Le+=(ye=je)-(je=L[ye])+32768&32767}if(xt){M[se++]=268435456|Ga[tt]<<18|Ru[xt];var Ht=31&Ga[tt],Ai=31&Ru[xt];Z+=Vl[Ht]+Gl[Ai],++K[257+Ht],++ie[Ai],Ce=x+tt,++B}else M[se++]=d[x],++K[d[x]]}}_=Mu(d,w,!0,M,K,ie,Z,se,Q,x-Q,_)}return _h(b,0,h+yh(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var p=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&ta(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),ta(u,c-8,n.d()),ta(u,c-4,i),u}var cv=!!ya||!!Rl,wh="text/plain",ns=!1,bh=(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:"")},Xs=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("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return ae(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},na=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===He.GZipJS){var i=lv((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new pt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new pt(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return _h(c,0,d)})(li(e)),{mtime:0});return{contentType:wh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===He.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(li(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:li(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=li(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Eh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Xs(t.url,{compression:He.Base64}),encodedBody:na(k({},t,{compression:He.Base64,Ji:void 0}))}:{url:bh(t.url,"compression"),encodedBody:na(k({},t,{compression:void 0,Ji:void 0}))};try{e=na(t)}catch(r){if(Qc(t.compression,yi(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&Qc(t.compression,yi(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?_a(new Uint8Array(n)):ArrayBuffer.isView(n)&&_a(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(ns=!0,i()):{url:t.url,encodedBody:e}},Sh=t=>{try{return Eh(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},uv=(function(){var t=ce((function*(e){var n=li(e.data),i=yield(function(s,o,a){return wa.apply(this,arguments)})(n,oe.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:wh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),dv=/Failed to fetch|NetworkError|Load failed/i,xh=t=>t?.name==="TypeError"&&dv.test(t?.message||""),Ih=t=>{var e=Sh(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ae(t.headers,(function(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Gc){var d=new Gc;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||xh(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;Rl(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(h){u&&clearTimeout(u.timeout),f(h)}}},Ja=t=>{try{var e,n=Eh(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(qe.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 Ja(k({},t,{data:d(u.slice(0,c))})),void Ja(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Ih(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},$u=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Xs(n===He.GZipJS?bh(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===He.GZipJS?{}:{compression:n}))},is=[];Rl&&is.push({transport:"fetch",method:Ih}),ya&&is.push({transport:"XHR",method(t){var e=Sh(t);if(e){var n=new ya,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ae(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)}}}),qe!=null&&qe.sendBeacon&&is.push({transport:"sendBeacon",method:Ja});var Za=3e3;class fv{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Rt(n?.flush_interval_ms||Za,250,5e3,A.createLogger("flush interval"),Za),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)&&ae(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 ae(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 hv=["retriesPerformedSoFar"];class pv{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(E)&&"onLine"in E.navigator&&(this.dr=E.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},be(E,"online",this.vr),be(E,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=Xd(e,hv);Vt(n)&&(i.url=Xs(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(E)||(this.vr&&(E.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(E.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 gv{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(){be(E,"scroll",this.yr,{capture:!0}),be(E,"scrollend",this.yr,{capture:!0}),be(E,"resize",this.yr)}scrollElement(){if(!this._r)return E?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=E?.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 E?e==="y"?E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop||0:E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var mv=t=>dh(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Lu{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({[Ba]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||mv,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Ba]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?fh(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 ae(Hl(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+ba(i)]=n})),e}}class Kl{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 Oi=ve("[SessionId]");class Nu{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 Kl,this.Lr=(u,c)=>!(!Vt(u)||!Vt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Xt)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||Yt,this.Nr=i||Yt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Oi.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=Ie.H(this.jr),a=Ie.H(this.Br);o&&!a?this.Or=o:Ie.q(this.jr),Ie.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){Oi.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&&Ie.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&Ie.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?Ie.H(this.jr):null}Zr(e){var n=this.Pr;return!et(n)&&!et(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({[ai]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Vt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(ai):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!et(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({[ai]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Vt(e)?e:0,i=Vt(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[ai];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&&E&&(E.removeEventListener(xs,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&Ie.q(this.Br)},be(E,xs,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Xt)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=Vt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||Oi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),Oi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Oi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Vt(a)&&e&&!u?a:i,v=Vt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var b={noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(s,l,b))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var kh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&tu(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>tu(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Ch(){return(Ch=ce((function*(){var t=qe?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return ee(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 Rs=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 ia(t,e,n){return li({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Ph={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=>Rs(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Rs(n,i))))),icontains:(t,e)=>e.map(qr).some((n=>t.map(qr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(qr).every((n=>t.map(qr).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 Ah(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||et(r))return!1;var s=[String(r)],o=Ph[i.operator];return!!o&&o(i.values,s)}))}var Xa="custom",Ou="i.posthog.com",vv=/^\/static\//;class yv{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":Xa),this.en[this.apiHost]}rn(e){if(vv.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=Ou+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function Fh(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var te=ve("[Surveys]"),Rh="seenSurvey_",Th=t=>{try{var e=(n=>((i,r)=>""+Rh+(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){te.error("Failed to persist survey seen state",n)}},_v=[Xo.Popover,Xo.Widget,Xo.API],wv={ignoreConditions:!1,ignoreDelay:!1,displayType:Va.Popover},bv=ve("[PostHog ExternalIntegrations]"),Ev={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Sv{constructor(e){this._instance=e}ai(e,n){var i;(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return bv.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=N.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Ev[l],(()=>{var c;(c=N.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=N.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=N.__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 xv{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return ce((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&&Ue(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 Iv{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 Bu="extensionsRemoteConfig";class kv{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Iv(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(Bu,i);return this.un&&i(this.un),Wr(r)},this.vn=new xv(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(ur))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(ur);return typeof e=="string"?e:void 0}get library(){return{name:oe.LIB_NAME,version:oe.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 ce((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(Bu,e))}sendRequest(e,n){var i=this;return ce((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?Xs(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 rr={},ra=0,Ts=()=>{},Du='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Bi="Surveys module not available",ju="sanitize_properties is deprecated. Use before_send instead",Mh="Invalid value for property_denylist config: ",Cv=["token","distinct_id",jf],oi="posthog",$h=!cv&&Je?.indexOf("MSIE")===-1&&Je?.indexOf("Mozilla")===-1,sa=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:Pm(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Ts,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:we&&ee(we?.search)&&we.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:(E==null||(e=E.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:Ha,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Za},error_tracking:{},_onCapture:Ts},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:jm,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))},Pv=[["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 Pv){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=ge({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),ee(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(Mh+t.property_denylist)),s};class Av{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 nt{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===Xt||this.config.cookieless_mode===On&&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 Av,this.mn=!1,this.version=oe.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Kl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=sa(),this.SentryIntegration=Km,this.sentryIntegration=i=>(function(r,s){var o=rh(r,s);return{name:ih,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 gv(this),this.pageViewManager=new ku(this),this.rateLimiter=new iv(this),this.requestRouter=new yv(this),this.consent=new Lm(this),this.externalIntegrations=new Sv(this);var n=(e=nt.__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=ee(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=ee(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!==oi){var r,s=(r=rr[i])!==null&&r!==void 0?r:new nt;return s._init(e,n,i),rr[i]=s,rr[oi][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=ee(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=sa(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=sa(n.defaults),u=Uu(n),c=ge({},l,u,{name:i,token:a});me(l.rageclick)&&me(u.rageclick)&&(c.rageclick=ge({},l.rageclick,u.rageclick)),me(l.session_recording)&&me(u.session_recording)&&(c.session_recording=ge({},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:He.GZipJS;var d=this.En();if(this.persistence=new Zo(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Zo(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&&Ie.N()){var f=Ie.H(this.bn);U(f)&&f.forEach((I=>{ee(I)&&this.yn.add(I)}))}else Ie.q(this.bn);var p=k({},this.persistence.props),h=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new fv((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new pv(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Nu(this),this.sessionPropsManager=new Lu(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.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)),oe.DEBUG=oe.DEBUG||this.config.debug,oe.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p,s:h}),!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(),b=this.persistence.get_property(ft);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===ei)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Pn)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 w=this.config.get_device_id(Yt()),_=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(ft,n.bootstrap.isIdentifiedID?Pn:ei),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Br,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Yt());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ft,ei)}return be(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var S=I.config.segment;if(!S)return T();(function(P,R){var L=P.config.segment;if(!L)return R();var $=J=>{var G=()=>J.anonymousId()||Yt();P.config.get_device_id=G,J.id()&&(P.register({distinct_id:J.id(),$device_id:G()}),P.persistence.set_property(ft,Pn)),R()},O=L.user();"then"in O&&Ue(O.then)?O.then($):$(O)})(I,(()=>{S.register((P=>{typeof Promise<"u"&&Promise.resolve||Yo.warn("This browser does not have Promise support, and can not use the segment integration");var R=(L,$)=>{if(!$)return L;L.event.userId||L.event.anonymousId===P.get_distinct_id()||(Yo.info("No userId set, resetting PostHog"),P.reset()),L.event.userId&&L.event.userId!==P.get_distinct_id()&&(Yo.info("UserId set, identifying with PostHog"),P.identify(L.event.userId));var O=P.calculateEventProperties($,L.event.properties);return L.event.properties=Object.assign({},O,L.event.properties),L};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:L=>R(L,L.event.event),page:L=>R(L,si),identify:L=>R(L,Vo),screen:L=>R(L,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),Ue(this.config._onCapture)&&this.config._onCapture!==Ts&&(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 Ch.apply(this,arguments)})().then((I=>{I&&this.register({[qo]:I})})).catch(Ts),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=nt.__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)),Ue(this.featureFlags.onReloading)&&Ue(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({},nt.__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,Gm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[Uf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Hf]: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,He.GZipJS)?He.GZipJS:j(r.supportedCompression,He.Base64)?He.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:Ha}),(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&&we!=null&&we.hostname){var e=we.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 ph(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()&&Dr(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(zo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(zo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?$h?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=He.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((b=>k({},b,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=$u(o.url,o.method,o.compression,o.timestampMode);var p=is.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var b=0;m.length>b;b++)if(m[b].transport===f)return m[b]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){xh(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===He.GZipJS&&Fg&&typeof Promise<"u"&&!ns?uv(o).then((m=>{g(m)})).catch((m=>{if(eu(m))return ns=!0,void g(k({},o,{compression:void 0,url:$u(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var b="name"in v?String(v.name):"";return eu(v)||b===Qd})(m)&&(ns=!0),g(o)})):h(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){ra++;try{var n,i=[],r=[],s=[];Dr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(Ue(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&&Ue(this[n])?s.push(a):r.push(a)}));var o=function(a,l){Dr(a,(function(u){try{if(U(u[0])){var c=l;ae(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{ra--}}push(e){if(ra>0&&U(e)&&ee(e[0])){var n=nt.prototype[e[0]];Ue(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)&&ee(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&&!ee(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,p=su(i?.uuid,Yt),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===si&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(_s)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,b,w,_=g?void 0:this.Vn(i?.$set_once,e!==du,e===Vo);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=$=>ee($)?$.slice(0,s):$,l=new Set,h=(function $(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var G;if(l.add(O),U(O))G=[],Dr(O,(K=>{G.push($(K))}));else{var M={};ae(O,((K,ie)=>{l.has(K)||(M[ie]=$(K))})),G=M}return G}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function($,O){O===void 0&&(O=[]);var J={},G=M=>{$[M]!==void 0&&(J[M]=$[M])};return Rg.forEach(G),O.forEach(G),J})(h.properties,Cv)),e===en.DISMISSED||e===en.SENT){var x=n?.[Qo.SURVEY_ID],I=n?.[Qo.SURVEY_ITERATION];Th({id:x,current_iteration:I}),h.$set=k({},h.$set,{[(v={id:x,current_iteration:I},b=e===en.SENT?"responded":"dismissed",w="$survey_"+b+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+b+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===en.SHOWN&&(h.$set=k({},h.$set,{[Qo.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===nv.SHOWN){var T=n?.[Pu.TOUR_TYPE];T&&(h.$set=k({},h.$set,{[Pu.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var S=k({},h.properties.$set,h.$set);if(rn(S)||this.setPersonPropertiesForFlags(S),!q(this.config.before_send)){var P=this.Pt(h);if(!P)return;(h=P).uuid=su(h.uuid,Yt)}this.dn.emit("eventCaptured",h);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),L={method:"POST",url:R,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"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(L):this.In.enqueue(L),h}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new kv(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[jf]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!ee(a.distinct_id)&&!Ae(a.distinct_id)||Ea(a.distinct_id))&&A.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=(function(x,I,T,S){var P,R,L,$;if(S===void 0&&(S=!1),!Je)return{};var O,J=x?[..._i,...I||[]]:[],G=(function(Zn){for(var Ke=0;iu.length>Ke;Ke++){var Xn=iu[Ke],jt=Xn[1],Ut=Xn[0].exec(Zn),ut=Ut&&(Ue(jt)?jt(Ut,Zn):jt);if(ut)return ut}return["",""]})(Je),M=G[0],K=G[1],ie=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},B={};C(T)||(B.detectGoogleSearchApp=T);var Z={},se=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,Ce=(R=navigator)==null?void 0:R.maxTouchPoints,Q=E==null||(L=E.screen)==null?void 0:L.width,ue=E==null||($=E.screen)==null?void 0:$.height,ye=E?.devicePixelRatio;C(se)||(Z.userAgentDataPlatform=se),C(Ce)||(Z.maxTouchPoints=Ce),C(Q)||(Z.screenWidth=Q),C(ue)||(Z.screenHeight=ue),C(ye)||(Z.devicePixelRatio=ye);var je,St,_e,tt,xt,Cn,Le,Re,Dt=ge(Hl({$os:M,$os_version:K,$browser:If(Je,navigator.vendor,ie,B),$device:ru(Je),$device_type:(St=Je,_e=Z,Re=ru(St),Re===af||Re===of||Re==="Kobo"||Re==="Kindle Fire"||Re===wf?gi:Re===lr||Re===di||Re===cr||Re===xa?"Console":Re===cf?"Wearable":Re?lt:_e?.userAgentDataPlatform==="Android"&&((tt=_e?.maxTouchPoints)!==null&&tt!==void 0?tt:0)>0?600>Math.min((xt=_e?.screenWidth)!==null&&xt!==void 0?xt:0,(Cn=_e?.screenHeight)!==null&&Cn!==void 0?Cn:0)/((Le=_e?.devicePixelRatio)!==null&&Le!==void 0?Le:1)?lt:gi:"Desktop"),$timezone:hh(),$timezone_offset:Qm()}),{$current_url:fr(S?wn(we?.href):we?.href,J,hr),$host:we?.host,$pathname:we?.pathname,$raw_user_agent:Je.length>1e3?Je.substring(0,997)+"...":Je,$browser_version:Jg(Je,navigator.vendor,ie,B),$browser_language:Cu(),$browser_language_prefix:(je=Cu(),typeof je=="string"?je.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:oe.LIB_NAME,$lib_version:oe.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return oe.SDK_DIST_CHANNEL&&(Dt.$sdk_dist_channel=oe.SDK_DIST_CHANNEL),Dt})(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&&ge(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ge(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===Xa&&(a.$lib_custom_api_host=this.config.api_host),u=e!==si||s?e!==zo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=ge(a,u),e===si&&F&&(a.title=F.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}Je&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ae(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var b of this._n.slice())try{ge(v,b())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=ge({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ae(this.config.property_denylist,(function(x){delete a[x]})):A.error(Mh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(A.error(ju),a=w(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=ge({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(ju),a=l(a,"$set_once")),n&&(this.mn=!0),rn(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||!Ie.N())Ie.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?Ie.F(this.bn,n):Ie.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:Bi}),()=>{})}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:Bi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Bi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=wv),(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:Bi}}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:Bi})}Jn(e){return!e||Ea(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Br?(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(Ae(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(ur)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(qi)&&(this.unregister(qi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ft)||ei)===ei,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ft,Pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Vo,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=ia(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ft,Pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=ia(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Bn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=ia(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=>ee(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(du,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var p,h=this.get_property(ur),g=this.get_property(qo),m=this.get_property(jn),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(p=this.persistence)==null||p.register({[jn]: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(ft,ei),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Xt)this.register_once({distinct_id:Br,$device_id:null},"");else{var b=this.config.get_device_id(Yt());this.register_once({distinct_id:b,$device_id:e?b:h},""),e||C(g)||this.register({[qo]: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 ce((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($f)?(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(qi,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(me(e)){var i,r,s,o,a,l,u,c,d,f,p,h;ge(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 Zo(k({},this.config,{persistence:"sessionStorage"}),g,!1);var m=this.Cn(this.config.debug);wt(m)&&(this.config.debug=m),wt(this.config.debug)&&(this.config.debug?(oe.DEBUG=!0,de.N()&&de.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(oe.DEBUG=!1,de.N()&&de.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){oe.LIB_NAME=e,oe.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:nt.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:oi;return n!==oi&&(n=oi+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ft))===Pn||((n=this.sessionPersistence)==null?void 0:n.get_property(ft))===Pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===Ha&&!this._isIdentified()&&rn(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[qi])&&((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!==On)}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!==Xt){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 Nu(this),this.pageViewManager=new ku(this),this.persistence&&(this.sessionPropsManager=new Lu(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=nt.__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==On&&((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(Du)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Xt?(this.config.cookieless_mode===On&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===On&&(this.register({distinct_id:Br,$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(Du)}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===Xt||(this.config.cookieless_mode===On?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return qe?kh(qe,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(si,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(Ss,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),be(F,Ss,this.kn)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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&&!q(n[i]),l=r in n&&!q(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(q(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Bg),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),q(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return Og(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!rn(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&&q(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=wt(e)&&!e,i=de.N()&&de.P("ph_debug")==="true";return!n&&(!!i||e)}}nt.__defaultExtensionClasses={},nt.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]]=km(t.prototype[e[n]])})(nt,["identify"]);class Hu{constructor(e){this.disabled=e===!1;var n=me(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 oa="$copy_autocapture",aa=ve("[AutoCapture]");function la(t,e){return e.length>t?e.slice(0,t)+"...":e}function Fv(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!bn(e));return e}function Rv(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!bn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!rt(f,"body")&&Jf>c.length;)if(Yf(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!bn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},b=!1,w=!1;if(ae(c,(S=>{var P=za(S);if(rt(S,"a")){var R=S.getAttribute("href");b=!!(P&&R&&nr(R))&&(u?wn(R):R)}j(ks(S),"ph-no-capture")&&(w=!0),m.push((function($,O,J,G,M){M===void 0&&(M=!1);var K=$.tagName.toLowerCase(),ie={tag_name:K};ql.indexOf(K)>-1&&!J&&(ie.$el_text=K.toLowerCase()==="a"||K.toLowerCase()==="button"?la(1024,Su($)):la(1024,dr($)));var B=ks($);B.length>0&&(ie.classes=B.filter((function(Q){return Q!==""}))),ae($.attributes,(function(Q){var ue;if((!th($)||["name","id","class","aria-label"].indexOf(Q.name)!==-1)&&(G==null||!G.includes(Q.name))&&!O&&nr(Q.value)&&(!ee(ue=Q.name)||ue.substring(0,10)!=="_ngcontent"&&ue.substring(0,7)!=="_nghost")){var ye=Q.value;Q.name==="class"&&(ye=Wl(ye).join(" ")),ie["attr__"+Q.name]=la(1024,Q.name==="href"&&M?wn(ye):ye)}}));for(var Z=1,se=1,Ce=$;Ce=Fv(Ce);)Z++,Ce.tagName===$.tagName&&se++;return ie.nth_child=Z,ie.nth_of_type=se,ie})(S,s,o,a,u));var L=(function($){if(!za($))return{};var O={};return ae($.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var G=J.name.replace("data-ph-capture-attribute-",""),M=J.value;G&&M&&nr(M)&&(O[G]=M)}})),O})(S);ge(v,L)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=rt(t,"a")||rt(t,"button")?Su(t):dr(t)),b){var _,x;m[0].attr__href=b;var I=(_=Cs(b))==null?void 0:_.host,T=E==null||(x=E.location)==null?void 0:x.host;I&&T&&I!==T&&(h=b)}return{props:ge({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((P=>{var R,L,$="";if(P.tag_name&&($+=P.tag_name),P.attr_class)for(var O of(P.attr_class.sort(),P.attr_class))$+="."+O.replace(/"/g,"");var J=k({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(L=P.nth_of_type)!==null&&L!==void 0?L:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),G={};return ts(J).sort(((M,K)=>M[0].localeCompare(K[0]))).forEach((M=>{var K=M[1];return G[xu(M[0].toString())]=xu(K.toString())})),($+=":")+ts(G).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(S){return S.map((P=>{var R,L,$={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(L=P.attr__href)==null?void 0:L.slice(0,2048),attr_class:zm(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return ts(P).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>$.attributes[O[0]]=O[1])),$}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var Di=ve("[ExceptionAutocapture]"),Wu=()=>{},Tv=ve("[TracingHeaders]"),Rn=ve("[Web Vitals]"),qu=9e5,zu="disabled",Vu="lazy_loading",ji="awaiting_config",zr="missing_config";ve("[SessionRecording]"),ve("[SessionRecording]");var Qa="[SessionRecording]",zt=ve(Qa),Mv=ve("[Heatmaps]");function ca(t){return me(t)&&"clientX"in t&&"clientY"in t&&Ae(t.clientX)&&Ae(t.clientY)}var Vr=ve("[Product Tours]"),ua=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Dl))},$v=["$set_once","$set"],It=ve("[SiteApps]"),Gu="Error while initializing PostHog app with config id ";function ii(t,e,n){if(q(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 Lv{constructor(e){this.ns=new Kl,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"||!ii(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=>ii(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&ii((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=>ii(u.text,n.text,n.text_matching||"exact")||ii(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;!q(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=>ii(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||Ah(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 Nv{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&&Ah(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===$i.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 Lv(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,$i.Activation),this.ks=this.Ps(e,$i.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,$i.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,$i.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&&(rn(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Ae(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=>Ae(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 Ov extends Nv{constructor(e){super(e)}Js(){return Oa}Ys(){return Xr}Ms(){return Qr}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Qr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Qr)}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 Ae(r)&&r>0}ra(){return en.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 te}Ws(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Oa]:e})}Xs(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[Xr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Xr)}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 Fh(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===en.SHOWN?"consume":"ignore":e===en.SHOWN?"persist":e===en.DISMISSED||e===en.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Gr="SDK is not enabled or survey functionality is not yet loaded",Ku="Disabled. Not loading surveys.",Bv=E!=null&&E.location?Ps(E.location.hash,"__posthog")||Ps(location.hash,"state"):null,Yu="_postHogToolbarParams",Ju=ve("[Toolbar]"),Zu=ve("[FeatureFlags]");class Dv{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||(Zu.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)||Zu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Xu=ve("[FeatureFlags]"),Tn=ve("[FeatureFlags]",{debugEnabled:!0}),da=`" failed. Feature flags didn't load in time.`,Qu="connection_error",ed=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},td=t=>{var e={};for(var n of ts(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},kt=ve("[Error tracking]"),nd="Refusing to render web experiment since the viewer is a likely bot",jv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Rs(e,t),not_regex:(t,e)=>!Rs(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Oe{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Oe.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Oe.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);ee(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];Oe.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())Oe.aa(nd);else if(!this.Ne.disable_web_experiments){if(q(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Oe.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=Oe.getWindowLocation();if(e!=null&&e.search){var n=yi(e?.search,"__experiment_id"),i=yi(e?.search,"__experiment_variant");n&&i&&(Oe.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&&(Oe.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!q(e.conditions)&&Oe.da(e,n)&&Oe.va(e)}static da(e,n){var i;if(q(e.conditions)||q((i=e.conditions)==null?void 0:i.url))return!0;var r=Oe.getWindowLocation();if(r){var s,o,a,l=Vf(n,r.href);return(s=e.conditions)==null||!s.url||jv[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return E?.location}static va(e){var n;if(q(e.conditions)||q((n=e.conditions)==null?void 0:n.utm))return!0;var i=ah();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,h=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&h&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Oe.aa(nd):n!=="control"?i.forEach((r=>{if(r.selector){var s;Oe.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)}))}})):Oe.aa("Control variants leave the page unmodified.")}_is_bot(){return qe&&this._instance?kh(qe,this.Ne.custom_blocked_useragents):void 0}}var dt=ve("[Conversations]"),Mn="Conversations not available yet.",id="console",Lh="__posthogHandledLogsRequestError",fa=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Lh]=!0,n},rd=t=>!!t&&typeof t=="object"&&t[Lh]===!0,Qs={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Xu,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 Dv(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 E&&be(E,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){E?.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=[],E?.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[Vi,Gi,Zr,Pt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa($n);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(tr);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($n))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Gi))!==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:Jc(f),variant:Zc(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(Pt),n=this.Oa(Ln);if(!n&&!e)return t||{};var i=ge({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],p=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Jc(i),variant:Zc(i),payload:Yc(e[n])}}))}getFlagVariants(){var t=this.Oa($n),e=this.Oa(Pt);if(!e)return t||{};for(var n=ge({},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(Gi),e=this.Oa(Ln);if(!e)return t||{};for(var n=ge({},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(Bn)}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(Gt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Nn),timezone:hh()};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({[es]:[Qu]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?He.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Qu:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[es]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(p,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return sh(this.Sa,3)}Ua(t){this.Sa=oh(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+da)}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(Zr)||void 0,u=this.Oa(tr)||void 0,c=this.Oa(Bn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Yi);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Bn]:c,[Yi]:n});else{var h,g,m,v,b,w,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Bn]:c},n?{[Yi]:n}:{}));var S=this.getFeatureFlagDetails(t),P=[...(h=this.Oa(es))!==null&&h!==void 0?h:[]];C(s)&&P.push("flag_missing");var R={$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(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),C(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var L,$=(w=S==null||(_=S.reason)==null?void 0:_.description)!==null&&w!==void 0?w:S==null||(x=S.reason)==null?void 0:x.code;$&&(R.$feature_flag_reason=$),S!=null&&(I=S.metadata)!=null&&I.id&&(R.$feature_flag_id=S.metadata.id),C(S?.original_variant)&&C(S?.original_enabled)||(R.$feature_flag_original_response=C(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(T=S.metadata)!=null&&T.original_payload&&(R.$feature_flag_original_payload=S==null||(L=S.metadata)==null?void 0:L.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[Bn]:c,[Yi]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Yc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+da)}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 ce((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"?He.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+da),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=Xu);var c=((I,T)=>{var S=I.flags;return S?k({},I,{featureFlags:Object.fromEntries(Object.keys(S).map((P=>{var R;return[P,(R=S[P].variant)!==null&&R!==void 0?R:S[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((P=>S[P].enabled)).filter((P=>{var R;return(R=S[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=S[P].metadata)==null?void 0:R.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,p=c.featureFlagPayloads;if(f){var h=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Vi]:f,[$n]:m,[_s]:!1}}var b=f,w=p,_=d;if(l!=null&&l.partialResponse)b=k({},s,b),w=k({},o,w),_=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)})));b=k({},s,Object.fromEntries(Object.entries(b).filter((I=>x.has(I[0]))))),w=k({},o,Object.fromEntries(Object.entries(w||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else b=k({},s,b),w=k({},o,w),_=k({},a,_);return k({[Vi]:Object.keys(td(b)),[$n]:b||{},[Gi]:w||{},[La]:_||{},[_s]:r.minimalFlagCalledEvents===!0},h?{[Zr]:h}:{},g?{[tr]: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([Pt,Ln]),this.Va(),void Tn.info("All overrides cleared");if(U(t))return this.F({[Pt]:ed(t)}),this.Va(),void Tn.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[Pt]=U(r)?ed(r):r),s&&(i[Ln]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([Pt,Ln]):r===!1?this.q(Pt):s===!1&&this.q(Ln),this.Va(),r===!1?Tn.info("Flag overrides cleared"):r&&Tn.info("Flag overrides set",{flags:r}),void(s===!1?Tn.info("Payload overrides cleared"):s&&Tn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[Pt]:t}),this.Va(),void Tn.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(Jr)||[]).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({[Vi]:Object.keys(td(o)),[$n]:o,[Gt]:k({},this.Oa(Gt)||{},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(Jr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return ce((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({[Jr]: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(Gt)||{},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({[Gt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Gt)||{});t.forEach((i=>{delete n[i]})),this.F({[Gt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Gt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(Nn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[Nn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Nn)||{};this.F({[Nn]:k({},e,{[t]:{}})})}else this.q(Nn)}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}}},Uv={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===ji||this.Ya===zr?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=zu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=E==null||(e=E.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 zt.error("started without valid sessionManager"),new Error(Qa+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Xt)throw new Error(Qa+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&be(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(jn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return E&&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),zt.info("starting")):(this.Ya=zu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ji&&this.Ya!==zr&&(this.Ya=Vu),N!=null&&(e=N.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=N.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return zt.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(jl),(e=this.Mr)==null||e.unregister(Lf)}uo(t,e){if(q(t))return null;var n,i=Ae(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(zt.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;q(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[jn]: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===ji&&(this.Ya=zr,zt.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):zt.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(jn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(jn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return zt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!q(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=N.__PosthogExtensions__)==null||!e.initSessionRecording)return zt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Wf]:!0});var r;if(this.Ja||(this.Ja=(r=N.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===zr||this.Ya===ji?void 0:(this.Ya=ji,zt.info("persisted remote config is stale, requesting fresh config before starting"),void new ph(this._instance).load());this.Ya=Vu,(n=(i=this.Ja).setDocumentWasEverVisible)==null||n.call(i,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Of]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Nf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Bf:Df]:!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))}}},Hv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new Hu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=me(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(E&&F){var t=n=>{n=n||E?.event;try{this.bo(n)}catch(i){aa.error("Failed to capture event",i)}};if(be(F,"submit",t,{capture:!0}),be(F,"change",t,{capture:!0}),be(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||E?.event;try{this.bo(n,oa)}catch(i){aa.error("Failed to capture copy/cut event",i)}};be(F,"copy",e,{capture:!0}),be(F,"cut",e,{capture:!0})}}}else aa.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;wt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Pa]: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[Pa],i=this.co,r=this.instance.Qi()&&!this.fo;if(et(i)&&!wt(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=Ko(t);Kf(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())&&yu(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===oa;if(i&&(function(d,f,p,h,g,m){var v;if(!E||zl(d)||p!=null&&p.url_allowlist&&!gu(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&gu(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>f.type===S)))return!1}var w=eh(d,h),_=w.parentIsUsefulElement,x=w.targetElementList;if(!(function(S,P){var R=P?.element_allowlist;if(C(R))return!0;var L,$=function(J){if(R.some((G=>J.tagName.toLowerCase()===G)))return{v:!0}};for(var O of S)if(L=$(O))return L.v;return!1})(x,p)||!qa(x,p?.css_selector_allowlist)||qa(x,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Dm))return!1;try{var I=E.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&&(ql.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=Rv(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===oa){var l,u=Zf(E==null||(l=E.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 Ue(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(E==null||(e=E.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(){E&&E.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(E&&((e=E.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return Wu;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 Ue(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];Ue(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 Wu}})(E.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=E==null||(e=E.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(si,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};be(E,"popstate",t),this.wo=()=>{E&&E.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Aa]),this.rageclicks=new Hu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return me(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return q(this.Ne.capture_heatmaps)?q(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Mv.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Aa]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ca(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(){E&&F&&(this.Po=this.cr.bind(this),be(E,xs,this.Po),this.Ro=t=>this.ke(t||E?.event),be(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||E?.event),be(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Iu(this.instance,Vm,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),be(F,Ss,this.Oo),this.vo=!0)}Eo(){var t;E&&F&&(this.Po&&E.removeEventListener(xs,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.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&&bn(u)&&!rt(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:E)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=Xf(u)}return!1})(Ko(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"),!pu(t.target)&&ca(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&yu(Ko(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!pu(t.target)&&ca(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(E){var e=this.Ne.disable_capture_url_hashes?wn(E.location.href):E.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[..._i,...n||[]]:[],r=fr(e,i,hr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!rn(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Iu,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},q(n?.name)||q(n?.value))Rn.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=Ae(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 Rn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=N.__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 Rn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Ma]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=me(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return q(n)?((e=this._instance.persistence)==null?void 0:e.props[$a])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(me(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=me(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=me(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=me(this.Wo)&&Ae(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:qu;return t>0&&6e4>=t?qu:t}get isEnabled(){var t=we?.protocol;if(t!=="http:"&&t!=="https:")return Rn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=me(this.Wo)?this.Wo.web_vitals:wt(this.Wo)?this.Wo:void 0;return wt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Rn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=me(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=me(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Ma]:n}),this._instance.persistence.register({[$a]: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=N.__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?Rn.error("failed to load script",r):t()}))}Bo(t){var e=t||E?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?wn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[..._i,...i||[]]:[];return fr(n,r,hr)}Rn.error("Could not determine current URL")}}},Wv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(E&&this.isEnabled&&(n=N.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=N.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=N.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=N.__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){Di.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Fa]),this.Jo=new Ug(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:Di})),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 me(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?(Di.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Di.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({[Fa]: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)?Di.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 rm([new fm,new bm,new pm,new hm,new _m,new ym,new mm,new wm],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var p=uu.test(f)?f.replace(uu,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((b=>{return k({},b,{filename:b.filename||(w=v,w[w.length-1]||{}).filename,function:b.function||vi});var w}))})(u)}})("web:javascript",lm,dm)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(Ra))!==null&&e!==void 0?e:[],this.el=ys(this.il()),this.rl=new Sm(this.el)}onConfigChange(){this.el=ys(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,[Ta]:o})}}}get nl(){var t,e=!!this._instance.get_property(Ta),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(!ee(t)||t.trim().length===0)return void kt.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)=>Em.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&&kt.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[ms]:t,[vs]:new Date().toISOString()},i))}catch(s){kt.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 kt.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 kt.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 kt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&q(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 kt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void kt.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 kt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[ms]:t,[vs]:new Date().toISOString()})}sl(t){return me(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 ee(r)&&r.length>0&&n.$exception_types.push(r),ee(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=Ph[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 kt.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!q(t)&&U(t)}}},qv=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({[Dl]:!!e.productTours}),!ua(this._instance))return!this.vl&&q((n=this.Mr)==null?void 0:n.props[Ki])||Vr.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&&ua(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Vr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=N.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=N.__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[Ki];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(ua(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||Vr.warn(o):Vr.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({[Ki]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){q(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(Ki)}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)}}},Qs),zv={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=N._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var p=t.$set_once,h=t.$set;return{event:k({},Xd(t,$v),{properties:k({},t.properties,h?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(It.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)||(It.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,p=(m,v,b)=>{if(m!=null&&m[v]){var w=m[v];m[v]=b(w),c.push((()=>{m[v]=w}))}},h=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:h(v))).filter((v=>!et(v)));return p(u,"appendChild",(m=>function(v){var b=h(v);return b?m.call(this,b):v})),p(u,"insertBefore",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):v})),p(u,"replaceChild",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):b})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];var x=g(w);return w.length&&!x.length?void 0:v.apply(this,x)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,b){var w=h(b);return w?m.call(this,v,w):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&&(It.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,It.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){It.error(Gu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){It.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){It.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 It.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;N["__$$ph_site_app_"+u]=r._instance,(l=N.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return It.error(Gu+u,d)}))};for(var a of s.siteApps)o()}else It.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Vv={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=N.__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=N.__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=N.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Tv.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()}}},Gv=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 te.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(q(e))return te.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,te.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)te.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)te.info(Ku);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())te.info("Not loading surveys in cookieless mode without consent.");else{var t=N?.__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 te.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new Ov(this._instance),te.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){te.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 te.info(Ku),t([]);var n,i=this._instance.get_property(Na);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?te.error(a):r.error||te.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&(Fh(p)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[Na]:c,[ws]: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(ws);return Ae(t)&&Date.now()-t>3e5}Bl(){return Ae(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var n,i={id:t,current_iteration:(n=e?.iteration)!==null&&n!==void 0?n:null};Th(i);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(n){te.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!q(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);te.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(q(this._surveyManager))return{eligible:!1,reason:Gr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(q(this._surveyManager))return{eligible:!1,reason:Gr};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(q(this._surveyManager))return te.warn("init was not called"),{visible:!1,disabledReason:Gr};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return q(this._surveyManager)?(te.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Gr})):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(q(this._surveyManager))te.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(_v.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(te.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;te.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),te.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);te.warn("Survey element not found")}else te.warn("Surveys of type "+r.type+" cannot be rendered in the app");else te.warn("Survey not found")}}displaySurvey(t,e){var n;if(q(this._surveyManager))te.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!==Va.Popover&&e.initialResponses&&te.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 te.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==Va.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else te.warn("Survey not found")}}cancelPendingSurvey(t){q(this._surveyManager)?te.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Qs),Kv={toolbar:class{constructor(t){this.instance=t}Wl(t){N.ph_toolbar_state=t}Vl(){var t;return(t=N.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),Wa(this.instance.config)||!E||!F)return!1;t=t??E.location,n=n??E.history;try{if(!e){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}e=E?.localStorage}var i,r=Bv||Ps(t.hash,"__posthog")||Ps(t.hash,"state"),s=r?fu((()=>JSON.parse(atob(decodeURIComponent(r)))))||fu((()=>JSON.parse(decodeURIComponent(r)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?t.hash=s.desiredHash:n?n.replaceState(n.state,"",t.pathname+t.search):t.hash="")):((i=JSON.parse(e.getItem(Yu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=N.ph_load_toolbar||N.ph_load_editor;!q(e)&&Ue(e)?e(t,this.instance):Ju.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(Gf));if(!E||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(E.localStorage.setItem(Yu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=N.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Ju.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),be(E,"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)}}},Yv=k({experiments:Oe},Qs),Jv={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;q(e)||(wt(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||Wa(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=N?.__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 dt.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,dt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else dt.error("Cannot complete initialization: remote config is null")}eu(t,e){dt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():dt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!et(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Wa(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?q(this.Jl)||!this.Jl.token?"missing_token":N!=null&&N.__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 ce((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(dt.warn(Mn),null)}))()}getMessages(t,e){var n=this;return ce((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(dt.warn(Mn),null)}))()}markAsRead(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(dt.warn(Mn),null)}))()}getTickets(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(dt.warn(Mn),null)}))()}requestRestoreLink(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(dt.warn(Mn),null)}))()}restoreFromToken(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(dt.warn(Mn),null)}))()}restoreFromUrlToken(){var t=this;return ce((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(dt.warn(Mn),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()}}},Zv={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ve("[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(rd)||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),E&&be(E,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=C(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(f=w?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=w?.["deployment.environment"])!==null&&h!==void 0?h:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,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 tm(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},id);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;!q(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){rd(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=N?.__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===Kt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Kt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.LIB_VERSION}}Ot(t){return new Promise((e=>{if(sh(this.Sa,3))e({kind:"fatal",error:fa(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:fa(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:fa(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=oh(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,oe.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,id,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=Ff(s,Af(n,oe.LIB_NAME,oe.LIB_VERSION),i,oe.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,q(r)||(e.sessionStartTimestamp=r),q(s)||(e.lastActivityTimestamp=s)}if(N!=null&&(t=N.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?wn(N.location.href):N.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Xv={metrics:class{constructor(t){this.rt=ve("[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 nm(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:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.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)}}},Qv=k({},Qs,Uv,Hv,Wv,qv,zv,Gv,Vv,Kv,Yv,Jv,Zv,Xv);nt.__defaultExtensionClasses=k({},Qv);var Nh=(function(){oe.SDK_DIST_CHANNEL="npm";var t=rr[oi]=new nt;return(function(){function e(){e.done||(e.done=!0,$h=!1,ae(rr,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():be(F,"DOMContentLoaded",e,{capture:!1}):E&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const ey=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let Ze=null,Ms=null,Oh="";const el=new Map;function Bh(t){return[...t.querySelectorAll(ey)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function ty(t){for(const n of document.body.children)n===t||n.tagName==="SCRIPT"||(el.set(n,{inert:n.inert,ariaHidden:n.getAttribute("aria-hidden")}),n.inert=!0,n.setAttribute("aria-hidden","true"));const e=document.activeElement;e&&e!==document.body&&!t.contains(e)&&e.blur()}function ny(){for(const[t,e]of el)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);el.clear()}function Dh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=Ze&&Ze!==n?Ze:null,r=Ms;if(i&&Ge(i,{restoreFocus:!1,force:!0}),Ze!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),Ms=a,Oh=document.body.style.overflow,ty(n),document.body.style.overflow="hidden"}Ze=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(Ze!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Bh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function Ge(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Dh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==Ze)return!0;ny(),document.body.style.overflow=Oh,Ze=null;const i=Ms;return Ms=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function iy(){return!!Ze}function sd(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 ry(t){if(!Dh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ge(t)}document.addEventListener("keydown",t=>{if(!Ze)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),ry(Ze);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Bh(Ze);if(!e.length){t.preventDefault(),(Ze.querySelector(".modal-content")||Ze).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 sy(){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 Yl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),oy=Object.freeze({free:2,professional:50,power:2e3}),ay="(contact us)",ly=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 ${ay}`])}),jh="CodeFile",Uh="GeneratedCode",cy={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function vn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tl(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function uy(t={},e=0){const n=tl(t.artifactType||t.type||jh),i=tl(t.artifactName||t.name||t.fileName||`${Uh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Hh(t={},e=0){const n=vn(t),i=n.artifactType||n.type||jh,r=n.artifactName||n.name||Uh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:tl(n.id)||uy({...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:Wh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:qh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:vn(n.metadata),codeType:n.codeType||cy[i]||"O"}}function Wh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=vn(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(vn(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function qh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=vn(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 nl(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 pr(t,e={}){const n=[],i=typeof t=="string"?nl(t):t,s=vn(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)=>Hh(d,f)),l=new Map(o.map((d,f)=>[vn(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=qh(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:Wh(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:vn(s.metadata)}}function bi(t){return pr(t).artifacts[0]||Hh()}function an(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Ei(t){return JSON.stringify(t,null,2)}function dy(t){return Ei({task:"architect",userRequest:String(t??"")})}function fy(t){const e=an(t);return e&&typeof e=="object"&&typeof e.task=="string"?Ei(e):Ei({task:"generate_bundle",bundleSpec:e})}function hy(t){return Ei({task:"review_bundle",generatedBundle:an(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 Jl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=an(e)),n}function py({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return Ei({task:"regenerate_artifact",artifactId:i,bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(r)})}function zh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Ei({task:"regenerate_bundle",bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(i??"")})}const od={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"},gy=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function st(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function my(t){return st(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||st(t.filterSummary)||st(t.filterResults):!1}function Vh(t,e=0){if(!st(t)||e>3)return null;if(my(t))return t;for(const n of gy){const i=t[n];if(st(i)){const r=Vh(i,e+1);if(r)return r}}return null}function $s(t){return Array.isArray(t)?t.some($s):st(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some($s):!1}function il(t){return Array.isArray(t)?t.some(il):st(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(il):!1}function Gh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function vy(t,e){if(st(t))for(const[n,i]of Object.entries(t)){if(!st(i))continue;const r=st(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>st(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Gh(n))}}function yy(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>st(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!$s(r))continue;const s=Gh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=st(o)?Object.entries(o).filter(([,l])=>$s(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function _y(t){return od[t]?od[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function ad(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 wy(t){const e=Vh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);vy(e.filterSummary,n),yy(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=il(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function by(t,e){const n=wy(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(_y))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${ad(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 ${ad(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 Ey(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ld(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of Ey(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 Zl(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 cd(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 Sy(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=Zl(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await cd(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await cd(c)),n[o]=u,a.type==="F"){const d=ld(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const r=new Set(ld(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 xy=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),ud={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Iy=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),ky=["Struct","Record"],Cy=[{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=>ha(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=>ha(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 { - const _P({required this.t}); - final double t; -} -class W extends StatefulWidget { - const W({this.value = 1.0}); - final double value; -}`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>ha(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { - const W({this.textStyle}); - final TextStyle? textStyle; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => const SizedBox(); }`,neg:`class W extends StatefulWidget { - const W({this.width}); - final double? width; - @override _S createState() => _S(); -} -class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Ct(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function gr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Ay(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;rFy(t).usable);function Ty(t=""){const e=gr(t);return Ry.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function My(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=Py(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rdd(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function eo(t=""){return Array.from(gr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function $y(t="",e=""){return Xl(t,e)?.returnType||null}function fd(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 Ly(t,e){const n=eo(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>fd(l)===r)||n.length>1)return null;const[o]=n,a=`${fd(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 Ql(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Ny(t,e,n=""){const i=Xl(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Zl(r,"A");if(s===i)return null;const o=`${Ql(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 Oy(t="",e=""){return Xl(t,e)!==null}function By(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Iy.has(i)?!1:!ky.some(s=>i.endsWith(s))||e.has(i))}function Dy(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=$y(t,e),r=By(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 jy(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(xy.has(t.artifactType)||n.push(Ct(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(Ct(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(Ct(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(Ct(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of Ty(r))n.push(Ct(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Oy(r,t.artifactName)&&n.push(Ct(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(eo(r)),o=Dy(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(Ct(t,"error",o));const a=Ny(i,r,t.artifactName);a&&n.push(Ct(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(Ct(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Ly(i,r);s&&n.push(Ct(t,"info",s))}return n}function Uy(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>eo(s.code||""))),i=e.flatMap(s=>jy(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:ud[s.artifactType]||ud.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const hd="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function pd(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function Hy(t=""){const e=t.indexOf(hd);return e===-1?t:t.slice(e+hd.length).replace(/^\s*\n/,"")}const Wy=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function qy(t="",e=""){const n=Hy(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(pd).filter(Boolean)),r=n.split(` -`).filter(s=>{const o=pd(s);return o===null||!i.has(o)?!0:!Wy.test(s)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const zy=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","flutter_web_plugins","integration_test","sky_engine"]);function Vy(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 Qy(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(p=>p.id)).map(p=>n.find(h=>h.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(p=>{const h=Xy(p),g=p.fixedCode||p.code||"",m=p.codeType||Jy[p.artifactType]||it.OTHER;g.trim()||s.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:h,content:g,type:m,path:p.deployPath||Zy(h,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,h)=>({entry:p,index:h})).filter(({entry:p})=>p.type===it.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],h={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} -${m.content}`).join(` - -`)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=h}const u={...gd(t?.dependencies),...r.reduce((p,h)=>({...p,...gd(h.dependencies)}),{})},c={};r.forEach(p=>{ec(p.fixedCode||p.code||"").forEach(h=>{h in u||(c[h]="")})});const d={...c,...u},f=Qy(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=new Map){const n=[],i=[];for(const r of t)(e.has(r.path)?n:i).push(r);return{landed:n,notLanded:i}}function rl(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}function o_(t){return t?t.notLanded.length===0&&t.landed.length>0:!1}function a_(t,e,n){const i=rl(t,e),r=new Map(i);return r.set("pubspec.yaml",{content:n,type:"D",path:"pubspec.yaml"}),r}const md={pass:0,warning:1,fail:2},l_=["manualActions"];function ct(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tn(...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 At(t){return t==null?[]:Array.isArray(t)?t:[t]}function c_(t){const e=ct(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return vd(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?vd(Number(i[1])):null}function vd(t){return t>=0&&t<=100?t:null}function ht(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function tc(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 sl(...t){return t.filter(Boolean).reduce((e,n)=>md[n]>md[e]?n:e,"pass")}function Zh(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ct(t),r=tn(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:tc(i.severity||i.status||i.level)||e,message:r,suggestion:tn(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function ol(t,e="review"){const n=ct(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>At(n[r]).map(o=>Zh(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=ct(t),r=tn(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:tn(i.detail,i.instructions,i.description),location:tn(i.location,i.flutterFlowPath,i.path),timing:tn(i.timing,i.phase)||"unspecified",artifactId:n,source:tn(i.source)||"Code Review"}:null}function al(t,e=null){const n=ct(t);return l_.flatMap(i=>At(n[i])).map((i,r)=>u_(i,r,e)).filter(Boolean)}function d_(t){let e=typeof t=="string"?nl(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ct(e);typeof n.content=="string"&&(e=nl(n.content)||e);const i=ct(e),r=ct(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(ht);return t.find(i=>{const r=ct(i);return[r.id,r.fileName,r.artifactName,r.name].map(ht).some(s=>s&&n.includes(s))})||null}function h_(t,e){return At(t?.metadata?.compatibility?.deployHints).find(r=>ht(r?.artifactId)===ht(e.id)||ht(r?.fileName)===ht(e.fileName))?.pathHint||""}function p_(t,e){return At(t?.relationships).filter(n=>ht(n?.from)===ht(e.id)||ht(n?.to)===ht(e.id))}function g_(t,e){return At(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ht(n.artifactId)===ht(e.id)).map(n=>Zh(n,"warning","Compatibility check")).filter(Boolean)}function m_(t,e,n,i){const r=f_(e,n),s=ct(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...ol(s),...g_(t,n)],l=al(s,n.id),u=tc(s.status||s.verdict||s.outcome||s.result),c=a.length?sl(...a.map(f=>f.severity)):null,d=sl(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?tn(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 y_({bundle:t,reviewResult:e}){const n=ct(t),i=At(n.artifacts),{root:r,rawText:s}=d_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ct).find(w=>Object.keys(w).length)||{},a=At(r.artifacts||r.files||r.reviews),l=i.map((w,_)=>m_(n,a,w,_)),u=ol(r),d=[...ol(o),...u],f=[...al(o),...al(r),...l.flatMap(w=>w.manualSteps)].filter((w,_,x)=>x.findIndex(I=>I.title===w.title&&I.artifactId===w.artifactId)===_),p=tc(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=sl(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??r.score??r.overallScore??s,m=c_(g),v=tn(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:h,score:m,artifactPresentations:l,manualSteps:f}),b=l.reduce((w,_)=>(w[_.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:At(n.deployOrder),relationships:At(n.relationships),warnings:At(n.warnings),compatibility:ct(n.metadata?.compatibility)}}const __="x-ff-api-key",yd="dr_",w_=/^[A-Za-z0-9_-]{1,120}$/;function b_(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`${yd}${t.randomUUID()}`;if(t&&typeof t.getRandomValues=="function"){const e=t.getRandomValues(new Uint8Array(16));return`${yd}${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}return null}function E_(t){return typeof t=="string"&&w_.test(t)}function S_(t,e){return`${String(t).replace(/\/deployCustomClasses$/,"")}/runStatus/${encodeURIComponent(e)}`}function x_(t){if(!t||typeof t!="object")return null;const{status:e}=t;return e!=="running"&&e!=="done"&&e!=="failed"?null:{status:e,phase:typeof t.phase=="string"?t.phase:"",message:typeof t.message=="string"?t.message:"",error:typeof t.error=="string"?t.error:null,deployed:Array.isArray(t.deployed)?t.deployed:[],dryRun:t.dryRun===!0}}const I_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function k_(t){return!t||!t.status?{definitive:null}:t.status==="done"?{definitive:"success",deployed:Array.isArray(t.deployed)?t.deployed:[]}:t.status==="failed"&&I_.has(t.phase)?{definitive:"failed",error:t.error||"The deploy failed before writing anything to FlutterFlow."}:{definitive:null}}async function C_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,timeoutMs:r=8e3}){if(!E_(e))return null;const s=i||globalThis.fetch;if(!s)return null;const o=new AbortController,a=setTimeout(()=>o.abort(),r);try{const l=await s(S_(t,e),{method:"GET",headers:{[__]:String(n||"")},signal:o.signal});if(!l.ok)return null;const u=await l.json();return x_(u)}catch{return null}finally{clearTimeout(a)}}async function P_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,budgetMs:r=12e3,intervalMs:s=2e3}){const o=Date.now()+r;let a=0;for(;Date.now()=2)return{definitive:null};const u=o-Date.now();if(u<=0)break;await new Promise(c=>setTimeout(c,Math.min(s,u)))}return{definitive:null}}const A_=/^\uFEFF/;function Ui(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` -`)}function F_(t){const e=String(t??"").replace(A_,"");if(!e.trim())return"";const n=e.split(` -`),i=c=>{const d=c.trim();return/^`{3,}[A-Za-z0-9+#_.-]*$/.test(d)?c.length-c.trimStart().length:-1};let r=0,s=-1;const o=[];{let c=0;for(let d=0;d=0&&(r++,s<0&&(s=d),o.push(c+f)),c+=n[d].length+1}}if(r===0)return Ui(n);{const c=ll(e);if(!c.error&&o.every(f=>wd(f,c.commentAndStringRanges)))return Ui(n)}if(r===1){const c=Ui(n.slice(0,s)),d=Ui(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 R_(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 Xh(t){const e=R_(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 Qh(t){return`${Ql(t)}.dart`}function T_(t){return Zl(t,"W")}const _d={"(":")","[":"]","{":"}"},M_={")":"(","]":"[","}":"{"},$_=/[A-Za-z0-9_]/;function ll(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]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!$_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(_d[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(M_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&_d[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function L_(t){return ll(String(t??"")).error}function wd(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 N_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],O_="MAGIC_LINK_SENT",B_="PLUS_ALIAS_REJECTED",D_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",to={allowlistedDomains:N_,successCode:O_,validationCode:B_,messageTemplate:D_},j_=new Set(to.allowlistedDomains),U_=to.successCode,H_=to.validationCode;function no(t){return typeof t=="string"?t.trim():""}function W_(t){const e=no(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 j_.has(r)?i.includes("+"):!1}function q_(t,e){return to.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function ep(t){if(!W_(t))return null;const e=no(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return q_(e,i)}function ic(t){return!t||typeof t!="object"||Array.isArray(t)||t.success===!1||t.error?!1:t.code?t.code===U_:t.success===!0||typeof t.message=="string"}function tp(t,e){return t?.code===H_?t.message||ep(e)||"Please enter your primary email address.":ic(t)?`Check your email — we sent a link to ${no(e)}`:t?.message||"Something went wrong. Please try again."}const z_="ccc_auth_session",V_="ccc_subscription",G_=Object.freeze(["hasSeenWalkthrough"]);function K_(t){const e=[];for(const n of G_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function Y_(){return[z_,V_]}function J_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of Y_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function Z_(t){const e=t?.message||t?.error;return typeof e=="string"&&e.trim()?e.trim():"The server could not send the link."}function X_({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());if(!ic(o))throw new Error(Z_(o));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 Q_=/^dependencies\s*:\s*(?:#.*)?$/,e0=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function xr(t){const e=t.match(e0);return e?e[1]??e[2]??e[3]:null}function Ir(t){const e=t.trim();return e===""||e.startsWith("#")}function En(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function rc(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;sc&&/\s/.test(s[d-1]);)d-=1}return t[r]=s.slice(0,c)+oc(n)+s.slice(d),!0}return!1}function bd(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?oc(i):">=0.0.0"}`]}function r0(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(ap(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=sc(r);if(l){const u=o.flatMap(([c,d])=>bd(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(...bd(" ",u,c))});return{yaml:r.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function s0(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=io(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l),d=c&&!c.isScalar&&c.sourceKey===null&&c.version!==null;if(!c||!c.isScalar&&!d||!String(u||"").trim()){a.push(l);continue}if(d){i0(r,c,String(u).trim())?o.push({name:l,from:c.version,to:u}):a.push(l);continue}const f=" ".repeat(En(r[c.lineIndex]));r[c.lineIndex]=`${f}${l}: ${oc(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` -`),overridden:o,skipped:a}}function cp(t){const e=String(t||""),n=[];return e.trim()?(/^name:\s*\S+/m.test(e)||n.push("pubspec.yaml missing name field"),sc(e.split(` -`))||n.push("pubspec.yaml missing dependencies section"),ap(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 o0=">=3.0.0 <4.0.0";function cl(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 a0(t=""){const e=Jh(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function Ed(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=cl(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=cl(s.version);continue}i.push(r)}return i}function l0(t){const e=new Set,n=new Set,i={},r={},s=Ed(io(t),i,e),o=Ed(t0(t,"dependency_overrides"),r,n),a=[...s,...o],l=new Set([...Object.keys(i),...e]),{sdk:u}=lp(t);return{sdkConstraint:cl(u)||o0,dependencies:i,dependencyOverrides:r,sdkPackages:[...e].sort(),sdkOverrides:[...n].sort(),availablePackages:l,unrepresentable:a,unrepresentableOverrides:o}}function c0(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 u0(t,e){const{sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o,availablePackages:a,unrepresentable:l,unrepresentableOverrides:u}=l0(e),c={sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o},d=[],f=[],p=[];for(const h of t){const{className:g,content:m}=h,v=ec(m),b=Jh(m).some(x=>x.startsWith("package:"));if(l.length>0&&b){const x=v.filter(T=>l.includes(T));let I;if(x.length>0)I=`${g} was not compiled before deploying: it imports or exports ${x.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`;else{const T=l.filter(P=>!u.includes(P)),S=[T.length>0?`your project's pubspec.yaml declares ${T.join(", ")} from a source that cannot be reproduced outside it`:null,u.length>0?`your project's dependency_overrides redirects ${u.join(", ")} to a source that cannot be reproduced outside it`:null].filter(Boolean).join(", and ");I=`${g} was not compiled before deploying: ${S}, and an entry like that can change what every package depending on it resolves to - including packages this class reaches transitively - so package resolution could not be matched exactly.`}f.push({className:g,reason:I});continue}const{unresolvableImports:w}=a0(m),_=v.filter(x=>!a.has(x));if(w.length>0||_.length>0){f.push({className:g,reason:c0(g,w,_)});continue}d.push({fileName:`${Ql(g)}.dart`,content:m})}return{manifest:c,sources:d,skipped:f,approximate:p}}function Sd(t,e){const n=`${t}${e}`.split(` -`),i=n.pop()??"",r=[];for(const s of n){const o=up(s);o&&r.push(o)}return{events:r,buffer:i}}function d0(t){const e=up(t);return e?[e]:[]}function up(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 Ne=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),dp=84e4,fp=1e4;function hp(t){return t?.unconfirmed===!0||t?.outcome===Ne.UNCONFIRMED?Ne.UNCONFIRMED:t?.partial===!0||t?.outcome===Ne.PARTIAL?Ne.PARTIAL:t?.success===!0?Ne.COMMITTED:Ne.FAILED}class We extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Ne.UNCONFIRMED}}function xd({httpStatus:t}={}){return new We(`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 f0(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}if(u.event==="result"){r=u;return}u.event===void 0&&typeof u.success=="boolean"&&(r=u)};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const p=Sd(o,c.decode(f,{stream:!0}));o=p.buffer,p.events.forEach(a)}}else{const u=Sd("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return d0(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 h0=new Set(["connected","workspace_init","workspace_ready","verifying"]);function pp(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?h0.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Id(t){if(t?.finalResultReceived){const e=hp(t);return e===Ne.FAILED&&!pp(t)?Ne.UNCONFIRMED:e}return t?.httpRejected&&typeof t.httpStatus=="number"&&t.httpStatus>=400&&t.httpStatus<500?Ne.FAILED:Ne.UNCONFIRMED}function p0(){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,p,h,g,m,v;function b(V,z){if(!i)return null;const D=i.createShader(V);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const V=b(i.VERTEX_SHADER,o),z=b(i.FRAGMENT_SHADER,a());if(V&&z&&(l=i.createProgram(),i.attachShader(l,V),i.attachShader(l,z),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),p=i.getUniformLocation(l,"parallax"),h=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function w(V){if(!V)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(V);if(z){let D=z[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const he=D.getContext("2d");he.fillStyle="rgb(9, 8, 7)";const Pe=String(he.fillStyle);he.fillStyle=V;const Te=String(he.fillStyle);if(Te===Pe)return null;const mt=/^#([0-9a-f]{6})$/i.exec(Te);if(mt){const vt=mt[1];return[parseInt(vt.slice(0,2),16)/255,parseInt(vt.slice(2,4),16)/255,parseInt(vt.slice(4,6),16)/255]}const Wt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Te);if(Wt)return[Number(Wt[1])/255,Number(Wt[2])/255,Number(Wt[3])/255]}catch{}return null}function _(){let V="";try{const z=getComputedStyle(document.documentElement);V=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return w(V)||[.56,.68,.88]}const x=_();let I=1920,T=1080,S=960,P=540,R=960,L=540,$=.66,O=0,J=-1e9,G=!1,M=0,K=0,ie=null,B=!1,Z=!1,se=!1;const Ce=64,Q=15.2;let ue=0,ye=0;const je=.0032,St=0,_e=.56,tt=.26,xt=.32,Cn=.16,Le=.349;let Re=St;function Dt(){const V=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!V.width||!z||!D)return;const he=Math.min(window.devicePixelRatio||1,2),Pe=Math.max(.2,Math.min(2,V.width/z*he)),Te=Math.max(2,Math.round(z*Pe)),mt=Math.max(2,Math.round(D*Pe));(Te!==t.width||mt!==t.height)&&(t.width=Te,t.height=mt,i&&i.viewport(0,0,Te,mt)),I=z,T=D,G||(S=R=I/2,P=L=T/2,G=!0)}function Zn(V){!l||!B||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,S,P),i.uniform1f(f,$),i.uniform1f(p,O),i.uniform2f(v,Math.cos(Re),Math.sin(Re)),i.uniform1f(h,V),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Ke(V,z,D){const he=Math.max(0,Math.min(1,(D-V)/(z-V)));return he*he*(3-2*he)}function Xn(V){if(!ie||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/I;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const he=Math.min(I,T),Pe=Math.max(64,Math.min(118,he/10)),Te=Pe*2.9,mt=2*Te*Te,Wt=Math.sin(V*.11)*7,vt=Math.cos(V*.09)*7-O,Mr=S+Wt,$r=P+vt,Fo=Te*Math.sqrt(2*Math.log(1/.06)),Fi=Fo+je*Fo*Fo+Pe,Ig=Math.floor((Mr-Fi)/Pe)-1,kg=Math.ceil((Mr+Fi)/Pe)+1,Cg=Math.floor(($r-Fi)/Pe)-1,Pg=Math.ceil(($r+Fi)/Pe)+1;for(let Ro=Cg;Ro<=Pg;Ro++){const Ag=(Ro+.5)*Pe;for(let To=Ig;To<=kg;To++){const Mo=(To+.5)*Pe-Mr,$o=Ag-$r,Lo=Math.sqrt(Mo*Mo+$o*$o)+1e-5;if(Lo>Fi)continue;const Lr=(-1+Math.sqrt(1+4*je*Lo))/(2*je),qc=Math.exp(-(Lr*Lr)/mt),zc=Ke(.06,.8,qc)*$*.26;if(zc<.004)continue;const gn=Pe/(1+2*je*Lr)*.26*(.32+1.1*qc),Vc=Lr/Lo,No=Mr+Mo*Vc,Oo=$r+$o*Vc;No<-gn*1.6||No>I+gn*1.6||Oo<-gn*1.6||Oo>T+gn*1.6||(z.globalAlpha=zc,z.save(),z.translate(No,Oo),z.rotate(Re),z.drawImage(ie,-gn,-gn,gn*2,gn*2),z.restore())}}z.globalAlpha=1}function jt(V){if(!Z)return;const z=K?Math.min(.05,(V-K)/1e3):.016;K=V;const he=V-J>2400?.6:1;$+=(he-$)*Math.min(1,z*3.2);const Pe=Math.min(.05,z);ue+=((R-S)*Ce-ue*Q)*Pe,ye+=((L-P)*Ce-ye*Q)*Pe,S+=ue*Pe,P+=ye*Pe,O=(window.scrollY||window.pageYOffset||0)*.55;const Te=V/1e3,mt=S/(I||1)-.5,Wt=P/(T||1)-.5;let vt=mt*(mt>=0?_e:tt)+Wt*(Wt>=0?xt:Cn);vt>Le?vt=Le:vt<-Le&&(vt=-Le),Re=St+vt-O*6e-4,Dt(),i?Zn(Te):Xn(Te),M=requestAnimationFrame(jt)}function Ut(V){if(!Z)return;const z=t.getBoundingClientRect();!z.width||!I||!T||(R=(V.clientX-z.left)/z.width*I,L=(V.clientY-z.top)/z.height*T,J=performance.now())}function ut(){Z||Ao||e.matches||n.matches||!se||document.hidden||(Z=!0,K=0,M=requestAnimationFrame(jt))}function Ht(){Z=!1,M&&(cancelAnimationFrame(M),M=0),K=0}function Ai(){e.matches?(Ht(),t.classList.remove("is-ready")):se&&ut()}function Qn(){n.matches?Ht():se&&ut()}function Uc(){document.hidden?Ht():se&&ut()}const Hc=new IntersectionObserver(V=>{se=V[0]?.isIntersecting||!1,se?ut():Ht()},{threshold:0});Hc.observe(t),window.addEventListener("pointermove",Ut,{passive:!0,capture:!0}),window.addEventListener("resize",Dt),e.addEventListener("change",Ai),n.addEventListener("change",Qn),document.addEventListener("visibilitychange",Uc);function xg(){const V=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(V&&window.Path2D){const he=Math.min(8.533333333333333,8.421052631578947);D.setTransform(he,0,0,he,he+(256-30*he)/2,-6.4*he),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(V),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const he=D.getImageData(0,0,256,256),Pe=he.data;for(let Te=3;Te{V.persisted?Ht():Wc()}),window.addEventListener("pageshow",V=>{V.persisted&&ut()}),{dispose:Wc,isRunning:()=>Z}}const g0=120;function m0(t,e,n){return tn?n:t}function pe(t,e,n){return m0((t-e)/(n-e),0,1)}function v0(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function pa(t){return 1-Math.pow(1-t,3)}function Ye(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 kd(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function re(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(pe(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=re(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),h=re(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ye}]),d=re(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ye},{t:10.6,v:0}]),p=re(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ye}]),o=re(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=re(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=pe(_,.45,2.2);a=x>0?-2.6*(1-kd(x)):0,g=re(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=pe(_,.67,2.42);f=I>0?-2.6*(1-kd(I)):0,s=1-.05*(Math.sin(pe(_,1.9,2.5)*Math.PI)+Math.sin(pe(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[re(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}]),re(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 w=x;const _=t-60,I=1-pe(_,12,14),T=x(pe(_,0,12)),S=x(pe(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(S[0]-T[0])*.6*I,a=(S[1]-T[1])*.6*I,p=(S[0]-T[0])*30*I,b=pe(_,0,.4)*I}else if(t<85.4){const _=t-74,x=re(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ye},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=re(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ye},{t:11.4,v:0}]),p=-l*.7,a=re(_,[{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=pe(_,0,5.6),I=pe(_,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,p=x*360*(1-I);const S=re(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:pa},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*S,d+=.16*S,l=-6*S,p+=6*S,s=1+.05*S,m=1+.9*S}else if(t<108.6){const _=t-96.4,x=pe(_,9.6,12.2);n=re(_,[{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(pe(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,h=1-.12*I,l=I*8,p=-I*8,o=.06*I,d=-.06*I,b=pe(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(pe(_,0,8)*Math.PI),I=1-pe(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(pe(_,0,6)*Math.PI),v=1+.1*Math.sin(pe(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=b,e}function y0(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=g0;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function p(M){const K=Math.min(1,Math.max(0,M.x))*c,ie=M.y*d;n.style.transform="translate3d("+K.toFixed(2)+"px,"+ie.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("+K.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,b=!1,w=!1,_=0;function x(){return w||a.matches||document.hidden||!e.offsetParent?!1:b}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){S();return}const K=g?(M-g)/1e3:0;g=M,h=(h+Math.min(K,.1))%l,_+=1,p(Hi(h))}function T(){v||w||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function S(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():S()}function R(){a.matches?(S(),p(Hi(0))):P()}function L(){f(),v&&p(Hi(h))}function $(){g=0,P()}const O=new IntersectionObserver(M=>{b=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});O.observe(e),window.addEventListener("resize",L),a.addEventListener("change",R),document.addEventListener("visibilitychange",$);function J(){w||(w=!0,S(),O.disconnect(),window.removeEventListener("resize",L),a.removeEventListener("change",R),document.removeEventListener("visibilitychange",$))}window.addEventListener("pagehide",M=>{M.persisted?S():J()}),window.addEventListener("pageshow",M=>{M.persisted&&P()});function G(M){h=(M%l+l)%l,p(Hi(h))}return f(),p(Hi(0)),P(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:G,dispose:J}}const _0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ln(t){const e=String(t||"").trim().match(_0);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function w0(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 E0(t){const e=ln(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ac(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 ln(o)?{min:o,minInclusive:!0,max:E0(o),maxInclusive:!1}:null}if(ln(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(!ln(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Cd(t,e){const n=ac(t);if(!n||!ln(e))return!1;if(n.min!==null){const i=Ls(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=Ls(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function S0(t,e){const n=ac(t);if(!n||!ln(e))return!1;if(n.max===null)return!0;const i=Ls(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ri(t){const e=ac(t);return e?e.min:null}const x0="https://pub.dev/api/packages/",I0=8e3;function k0(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||b0(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Cd(l.sdk,n)||i&&l.flutter&&!Cd(l.flutter,i)||(!s||Ls(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function C0(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${x0}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(I0)});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=k0(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 P0(t,e={}){const n=await Promise.all(t.map(i=>C0(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function A0(t,e={},n={}){const{resolveVersions:i=P0}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=lp(t),o={dartSdkFloor:ri(s.sdk),flutterSdkFloor:ri(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=io(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(zy.has(d)?c:u).push(d);continue}const h=ri(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:d,constraint:p.constraint});continue}if(S0(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(ri(h)){a.additions[f]=`^${ri(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${ri(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const F0={"&":"&","<":"<",">":">",'"':""","'":"'"};function cn(t){return String(t??"").replace(/[&<>"']/g,e=>F0[e])}function W(t){return t?cn(t).replace(/\n/g,"
    "):""}function on(t){return cn(t).replace(/\r?\n/g," ")}function ro(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 mp(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 R0(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 T0(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 M0(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 Si(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 Pd(t){return t=cn(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 vp(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=Si(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 cn(i)}}}function so(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=M0(o),u=vp(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+=`
    -

    - ${R0(l)} - ${cn(l)} -

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

    - ${T0(l)} - ${cn(l)} -

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

    ${Pd(a)}

    `)}return i+="
    ",` -
    -
    -
    - Live Audit Report -
    - ${i} -
    - `}const $0=5200,L0=73,N0=1600,O0=35,ga=new WeakMap;function Ad(t,e){return!!(t&&t.trim())&&!e}function B0({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=Array.from(document.querySelectorAll("#example-chips .chip")),o=document.getElementById("btn-add-images"),a=document.getElementById("prompt-image-input"),l=window.matchMedia("(prefers-reduced-motion: reduce)");let u=!1,c=!1,d=!1,f=!1,p=!1,h=null,g=null;const m=n.dataset.demoPrompt||"";function v(){return c||d||f||p}function b(){i.disabled=!Ad(n.value,v())}function w(){r&&(r.textContent=n.value)}function _(B){c=B,e.classList.toggle("is-busy",B),i.classList.toggle("is-busy",B),i.setAttribute("aria-label",B?"Generating":"Generate"),n.readOnly=B,s.forEach(Z=>{Z.disabled=B}),o&&(o.disabled=B),a&&(a.disabled=B),b()}async function x(){if(Ad(n.value,v())){_(!0);try{await t()}finally{_(!1)}}}function I(){f&&(f=!1,g&&(clearTimeout(g),g=null),e.classList.remove("is-demo-typing","is-demo-keying"),n.placeholder="Describe the widget or action you need",b())}function T(){if(l.matches||!m.trim())return;const B=window.location.hash.replace(/^#/,"");if(B&&B!=="home")return;f=!0,n.placeholder="",n.value="",w(),b(),e.classList.add("is-demo-typing");let Z=0;const se=(ue,ye)=>{Z+=ue,n.value=m.slice(0,Z),w(),e.classList.toggle("is-demo-keying",ye)},Ce=()=>{f&&(se(-1,!0),Z>0?g=setTimeout(Ce,O0):I())},Q=()=>{if(!f)return;const ue=Z+1B.classList.contains("is-active"))?.dataset.prompt||n.value,w(),R())}function $(){s.forEach(B=>{B.classList.remove("is-active"),B.setAttribute("aria-pressed","false")})}function O(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function J(B){const Z=B.dataset.prompt||"";if(I(),R(),s.forEach(Ce=>{const Q=Ce===B;Ce.classList.toggle("is-active",Q),Ce.setAttribute("aria-pressed",String(Q))}),l.matches||!Z){n.value=Z,w(),b(),O();return}n.value="",w(),d=!0,b(),e.classList.add("is-demo-typing","is-demo-keying");let se=0;h=setInterval(()=>{se+=1,n.value=Z.slice(0,se),w(),se>=Z.length?(R(),O()):b()},22)}s.forEach(B=>{B.setAttribute("aria-pressed","false"),B.addEventListener("click",()=>J(B))}),n.addEventListener("keydown",B=>{if((f||d)&&B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u){B.preventDefault();return}S(),L(),B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u&&(B.preventDefault(),x())}),n.addEventListener("beforeinput",()=>S()),n.addEventListener("input",()=>{I(),R(),$(),w(),b()}),n.addEventListener("compositionstart",()=>{u=!0}),n.addEventListener("compositionend",()=>{u=!1,b()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),i.addEventListener("click",x),n.addEventListener("pointerdown",()=>{S(),L(),$()}),n.addEventListener("focus",()=>S());const G=ga.get(e);G&&G.mql.removeEventListener("change",G.handler),l.addEventListener("change",P),ga.set(e,{mql:l,handler:P});function M(){K(),l.removeEventListener("change",P),ga.delete(e),document.removeEventListener("visibilitychange",ie)}function K(){S(),L()}function ie(){document.hidden&&K()}return document.addEventListener("visibilitychange",ie),w(),b(),T(),{setAttachmentsPending(B){p=!!B,b()},dispose:M,cancelTyping:K}}const mr=window.matchMedia("(prefers-reduced-motion: reduce)");let fi=null,Jt=null;const Ns=new Map;function yp(){for(const[t,e]of Ns)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Ns.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Gn(){if(yp(),fi){const t=fi;fi=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Jt&&(Jt.animation.cancel(),Jt.hero.classList.remove("is-exiting"),Jt.hero.style.cssText=Jt.style,Jt=null)}function D0(t){return(fi?.ghost||t)?.getBoundingClientRect()}function j0(t){yp(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",mr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Ns.delete(e))}Ns.set(e,i),e.addEventListener("animationend",i)})}function U0(t,e){if(!t||!e||mr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Jt={hero:t,animation:i,style:n},i.onfinish=()=>{Jt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Jt=null)}}function _p(t,e,n,{results:i=!1}={}){if(Gn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,j0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(mr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};fi=h,p.onfinish=()=>{fi===h&&(Gn(),s())}}window.addEventListener("resize",Gn);window.addEventListener("pagehide",Gn);document.addEventListener("visibilitychange",()=>{document.hidden&&Gn()});mr.addEventListener("change",()=>{mr.matches&&Gn()});const Fd="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",H0="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",W0="https://us.i.posthog.com";Nh.init(H0,{api_host:W0,person_profiles:"identified_only"});function Dn(t,e={}){try{Nh.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const Et="https://4tgke4.buildship.run",wp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Os="ccc_auth_session",ul="ccc_signin_return",q0=1800*1e3,Rd=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=Kn({isResolved:!0}),dl=Promise.resolve();const z0=`${Et}/service/runpipeline`,V0="bs_user_id",G0="bs_identity_token",K0=`${Et}/authUserCheck`;let yt={userId:null,token:null,status:null,resolved:!1};const Bs=oy,Ds="ccc_subscription",Td=3,Y0=new Set(["active","trialing","paid"]),js="google/gemini-3.7-flash",rs=["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"],J0={"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 nn(t){return J0[t]||t}const Z0=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 bp(t){return Z0.has(t)}const fl=4,ma=8*1024*1024,X0="https://4tgke4.buildship.run/service/runpipeline-image";let De=[];const Sn=[],Q0=3e4;let lc=null;function ew(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function tw(t,e){const n=new FormData;return n.append("file",t),(await fetch(X0,{method:"POST",body:n,signal:e})).json()}function nw(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 iw(t,e,n){const i=await ew(t,n);i&&De.includes(e)&&(e.dataUrl=i,yn());let r="";if(i)try{r=nw(await tw(t,n))}catch{r=""}return De.includes(e)?!i||!r?(De.splice(De.indexOf(e),1),yn(),"failed"):(e.url=r,yn(),"added"):"dropped"}function Ep(t){const e=Sn.indexOf(t);e>=0&&Sn.splice(e,1),xp()}function Sp(t){t.controller.abort(),Ep(t);const e=De.indexOf(t.slot);e>=0&&(De.splice(e,1),yn())}function xp(){lc?.setAttachmentsPending(Sn.length>0)}async function rw(t){const e=Array.from(t.target.files||[]);if(!e.length)return;if(t.target.value="",y.isRunning){Se("Wait for the current generation to finish before attaching images.","info");return}const n=e.filter(u=>u.size>ma);n.length&&Se(`Skipped ${n.length} image(s) over the ${(ma/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ma);if(!i.length)return;const r=fl-De.length,s=i.slice(0,r);if(i.length>r&&Se(`You can attach up to ${fl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};De.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Q0);return d.job=iw(u,c,d.controller.signal),Sn.push(d),d.job.finally(()=>{clearTimeout(f),Ep(d)}),d.job});yn(),xp();const l=(await Promise.all(o)).filter(u=>u==="failed").length;l&&Se(`${l} image(s) could not be uploaded and were not attached.`,"error")}function sw(t){if(y.isRunning){Se("Wait for the current generation to finish before removing images.","info");return}const e=De[t],n=Sn.find(i=>i.slot===e);if(n){Sp(n);return}De.splice(t,1),yn()}function yn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",De.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=De.length>=fl?"Image limit reached":"Add images"))}function cc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=bp(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(Sp),De=[],yn())}const Wn="ccc_usage",Ip="google/gemini-3.7-flash",kp="google/gemini-3.7-flash",Kr="google/gemini-3.7-flash",Ji={professional:11,power:49},hl={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"},ss={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 os={...ss};async function ow(){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(ss),...Object.values(pl),...Object.values(hl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:ss[a]&&(s[a]=ss[a]));os=s}catch{}finally{clearTimeout(e)}}const pl={"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 uc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&pl[s])return pl[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=hl[e];if(n)return n;const i=e.split("_")[0],r=hl[i];return r||"USD"}function Zi(t,e){const n=os[e]??os.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*os.USD)}}const _t="ccc_api_key_",Tt="ccc_session_api_key_",Nt="ccc_encryption_key",vr="ccc_encryption_key_scope",aw="ccc_keystore",Us="keys",yr="ccc_encryption_key_version";let gl=null,Hs=null,_r=!1,Ws=!1,Md=!1;class qs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function $d(){if(Md)return;Md=!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&&Se(t,"warning")}function Cp(){return localStorage.getItem(yr)||""}function ml(){return crypto.randomUUID?.()||Ap(crypto.getRandomValues(new Uint8Array(16)))}function lw(){const t=Cp();if(t)return t;const e=ml();return localStorage.setItem(yr,e),e}function xi(){gl=null,Hs=null,_r=!1,Ws=!1}window.addEventListener("storage",t=>{t.key===yr&&xi()});function cw(){return new Promise((t,e)=>{const n=indexedDB.open(aw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Us)||i.createObjectStore(Us)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function dc(t,e){const n=await cw();return new Promise((i,r)=>{const s=n.transaction(Us,t);let o;try{o=e(s.objectStore(Us))}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 uw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function dw(){const t=await dc("readonly",e=>e.get(Nt));return uw(t)?t:null}async function Pp(t){await dc("readwrite",e=>e.put(t,Nt))}async function fw(){xi();try{await dc("readwrite",t=>t.delete(Nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function hw(){const t=sessionStorage.getItem(Nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(e),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),e}async function Ld(t){const e=sessionStorage.getItem(Nt);if(e)return Ws=sessionStorage.getItem(vr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new qs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Nt,JSON.stringify(i)),sessionStorage.setItem(vr,"session"),Ws=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function pw(t){if(sessionStorage.getItem(vr)==="session"&&sessionStorage.getItem(Nt))return $d(),_r=!0,Ld(t);try{const e=await dw();if(e)return e;const n=await hw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Pp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),$d(),_r=!0,Ld(t)}}async function fc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=lw();Hs!==n&&xi();const i=gl||pw(e);gl=i,Hs=n;try{return await i}catch(r){throw xi(),r}}async function gw(t){const e=await fc(),n=Hs,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:Ap(o),keyVersion:n,sessionFallback:_r}}async function mw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await fc({allowSessionFallbackCreation:!1});if(_r&&!n&&!Ws)throw new qs;const r=vw(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 qs)throw i;return console.error("Decryption failed:",i),null}}function Ap(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let ke="",Mt="",sr=null,Od=0,ot="not-configured",gt=0,vl=0,yl=0,oo=0,Zt=0,un=0,Xe=null,$t=null,wr=null;function _w(){return vl+=1,vl}function ww(){return yl+=1,yl}function br(t,e,n){Xe=t?{projectId:t,key:e,generation:n}:null}function _l(t,e=ke){if(!t)return!1;const n=Xe;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function hc(t,e,n){if(!Mt||Xe&&Xe.projectId!==Mt)return;(t||[]).some(r=>(r.id||r.projectId)===Mt)?br(Mt,e,n):Xe&&br("",null,null)}function Fp({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===ke||r===ke}async function pc(){sessionStorage.getItem(Nt)&&await fc(),ke=await Me("flutterflow"),Mt=await Me("flutterflow_project_id"),kw(),pn(),ke?yc():(ot="not-configured",bt())}let Er=!1;function Rp(){const t=document.getElementById("api-keys-modal");Ve(t),vc(),ke&&co(ke)}function gc(){Er=!1,Rp()}function bw(){Er=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Rp()}let Bd=!1;function Dd(){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 jd(){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=nn(t.value),r=bp(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.`),cc()}function Tp(){if(Er=!1,Dd(),jd(),!Bd){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")),Dd(),jd()}),Bd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function Ew(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Mp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=Er;if(Er=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&mc(),Ve(i))}}let dn=1;function $p(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function ao(){const t=$p();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,ao())}function Sw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,ao(),Ve(t))}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Lp(){if(H.isVerified&&Ot()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,ao(),Ve(e))}}async function vc(){const t=document.getElementById("flutterflow-api-key-input");ke?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Iw()}function Iw(){Ud("flutterflow","flutterflow-key-status"),Ud("flutterflow_project_id","flutterflow-project-status")}function Ud(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ft(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function kw(){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"?Ft("flutterflow")&&Ft("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ft("flutterflow")||Ft("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)"):Ft(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)")}),pn()}async function Cw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==ke,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await Nd("flutterflow",n),n!==l&&!r&&as()}const s=n||ke;if(r){if(!lo(r)){Se("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}_l(r,s)?await Nd("flutterflow_project_id",r):(i?as():Xe=null,e.value="",s&&!($t&&$t.key===s&&$t.generation===gt)&&co(s))}else i&&as();await pc(),n&&await yc(),vc();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Mp()},1e3)}async function Pw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(yr,ml()),xi(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),await fw(),localStorage.setItem(yr,ml()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),Xe=null,$t=null,wr=null,await pc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),vc()}function lo(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Mt||"—"),!e)return;let r,s;if(!Ft("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 yc(){const t=ww(),e=++oo,n=gt,i=ke,r=await Me("flutterflow"),s=()=>Fp({seq:t,currentSeq:yl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Ft("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&hc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function as(){Mt="",Xe=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow_project_id")}function Aw(){gt+=1,$t=null,wr=null,as();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ft("flutterflow")?(ot="validating",co(ke)):ot="not-configured",bt()}function Fw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Rw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Fw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Tw(async n=>{const i=n.target.value.trim();i&&await co(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&$t?br(n,$t.key,$t.generation):br("",null,null)})}function Tw(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function co(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=_w(),r=++oo,s=gt,o=ke,a=()=>Fp({seq:i,currentSeq:vl,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};$t=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===ke&&(Ft("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;$t={key:t,generation:s};const f=t===ke,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,hc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Mt&&(e.value=Mt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===ke&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Mw(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 $w(){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 Lw(){y.bundleSpec=pr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function uo(){const t=bi(y.bundleSpec);y.artifactBundle=pr(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=Uy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=bi(y.artifactBundle).id}function fo(){const t=pr(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=pr({id:y.artifactBundle?.id,title:y.artifactBundle?.title,artifacts:y.artifactBundle?.artifacts?.map(i=>{const r=n.get(i.id)||null;return{...i,review:e.get(i.id)||i.review||y.step3Result||null,...r?{fixedCode:r}:{}}})||[],relationships:y.artifactBundle?.relationships,warnings:y.artifactBundle?.warnings})}function Np(){const t=_c();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function _c(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||bi(t)}function wc(){return _c().code||y.step2Result||""}async function Nw(){try{await pc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const ls={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Ow(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 In{constructor(e,n,i="main",r=ls.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=[ls.production,ls.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(wl(f?d.clone():d,fp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 xd({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(Ow(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 wl(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 bc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Bw(t,e=fp){const n=t.clone();let i;try{i=JSON.parse(await wl(t,e))}catch{let o="";try{o=await wl(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 ho(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 X={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Op=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Bp=/extends\s+State<\w+>/;function Dw(t,e=""){if(t==="pubspec.yaml")return X.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return X.OTHER;if(t==="custom_functions.dart")return X.FUNCTION;if(e){const n=Op.test(e),i=Bp.test(e);if(n||i)return X.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return X.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return X.FUNCTION}return X.CODE_FILE}function Dp(t,e){switch(e){case X.ACTION:return`lib/custom_code/actions/${t}`;case X.WIDGET:return`lib/custom_code/widgets/${t}`;case X.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case X.CODE_FILE:return`lib/custom_code/${t}`;case X.DEPENDENCIES:return"pubspec.yaml";case X.OTHER:return`lib/custom_code/${t}`;default:return t}}async function po(t,e=new Map){return Sy(t,e)}const bl=new Map,hi=new Map,pi=new Map;function Cr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){bl.delete(Cr(t))}function Xi(t,e,n){const i=Cr(t),r=hi.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?hi.delete(i):hi.set(i,r)}function jw(t,e){Xi(t,e,{uncertain:1})}function Uw(t){const e=Cr(t);pi.set(e,(pi.get(e)??0)+1)}function Hd(t){const e=Cr(t),n=(pi.get(e)??0)-1;n<=0?pi.delete(e):pi.set(e,n)}function bc(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 go(t,e,n=dp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Bw(s)})();return bc(r,n,(s,o)=>{i.stop=!0,Yn(t),Uw(t),r.then(()=>Hd(t),()=>Hd(t)),o(new We("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 Hw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=s_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function Ec(t,e,n,i,r="",s=dp){const o=r_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=b_();let l=!1;const u=u0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch(Fd,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 f0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await bc(g,s,(m,v)=>{p=!1,v(new We("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(Id(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Id(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Yn(t),jw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Xi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&pp(w)&&Xi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await P_({provisionEndpoint:Fd,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Xi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await Hw(t,o,m);throw o_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Yn(t),Xi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:rl(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Sc(t,e={}){const n=Cr(t);let i=bl.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=cp(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=hi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&hi.delete(n)}!hi.has(n)&&!pi.has(n)&&bl.set(n,i)}const r=await A0(i.pubspecYaml,e),s=s0(i.pubspecYaml,r.overrides),o=r0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Ww(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===X.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=L_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===X.WIDGET){const o=Xh(t.content),a=T_(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=`${Qh(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 jp(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=F_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=Xh(s)[0],c=u?Qh(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=X.CODE_FILE;switch(n){case"CustomAction":a=X.ACTION;break;case"CustomWidget":a=X.WIDGET;break;case"CustomFunction":a=X.FUNCTION;break;case"CustomClass":case"CodeFile":a=X.CODE_FILE;break}let l="";return a===X.WIDGET?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom widget code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===X.ACTION?l=`// Automatic FlutterFlow imports -import '/flutter_flow/flutter_flow_theme.dart'; -import '/flutter_flow/flutter_flow_util.dart'; -import 'package:flutter/material.dart'; -// Begin custom action code -// DO NOT REMOVE OR MODIFY THE CODE ABOVE! - -`:a===X.FUNCTION&&(l=`// Automatic FlutterFlow imports -import 'dart:convert'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:google_fonts/google_fonts.dart'; -import 'package:intl/intl.dart'; -import 'package:timeago/timeago.dart' as timeago; -import '/flutter_flow/lat_lng.dart'; -import '/flutter_flow/place.dart'; -import '/flutter_flow/uploaded_file.dart'; - -`),{content:qy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function qw(t){const e={};for(const n of ec(t))e[n]="";return e}function zw(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 Vw(t,e,n,i=new Set,r=""){const s=[],o=Op.test(e),a=Bp.test(e);return n===X.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function mo(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=>eo(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=Vw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=cp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function xc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(_l(n,e))return n;const i=++oo,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==ke||i<=un||(un=i,!s)?"":Xe&&Xe.projectId!==n&&_l(Xe.projectId,e)?Xe.projectId:((!Xe||Xe.projectId===n)&&br(n,e,r),n)}async function Gw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=X.WIDGET),i==="CustomAction"&&(i=X.ACTION),i==="CustomFunction"&&(i=X.FUNCTION),i==="CustomClass"&&(i=X.CODE_FILE),i==="CodeFile"&&(i=X.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await xc(o);if((o!==ke||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!lo(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||Dw(e,t),f=Dp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=mo(c);if(!p.valid)throw new Error(`Validation failed: -${p.errors.join(` -`)}`);const h=await Sc(u,r),g=h.yaml,m=await Ec(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await po(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await vo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Yn(u),$e.set("push");const x=await go(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||ho(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function vo(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 Kw(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=jp(t,{artifactType:n,artifactName:i,fileName:r}),u=qw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=sr||await xc(c);if((c!==ke||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Dp(l.fileName,l.codeType),functionName:l.codeType===X.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=mo(h);if(!g.valid)throw new Error(`File validation failed: -${g.errors.join(` -`)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),Y.setState(ne.PUSHING);const m=new In(c,p,"main",d),v=await Sc(m,u),b=v.yaml,w=await Ec(m,h,v.remoteFiles,`Provision ${i} custom class`,b);o=w.provisionSucceeded===!0;const _=await po(w.syncFileMap,w.remoteFiles),x=new Map(w.syncFileMap);x.set("pubspec.yaml",{content:b,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const I=await vo(x),T={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:b,file_map:_.fileMapContents,functions_map:_.functionsMapContents};Y.setProgress(1,h.size),Yn(m),$e.set("push");const S=await go(m,T);if(S.success){const P={...zw(l,s),projectId:p};return Y.setSuccess({...P,fileCount:h.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:w.unverified,approximate:w.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=S.errorMessage||ho(S.responseCode),R=new Error(P);throw R.errorMap=S.errorMap,R.remoteRefusal=!0,R}}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 We?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...l.finishDeploy?{finishDeploy:cg(l.finishDeploy,a,Y)}:{}}: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,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function Yw(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:ze(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ne.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===X.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=mo(s);if(!o.valid)throw new Error(`File validation failed: -${o.errors.join(` -`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=sr||await xc(a);if((a!==ke||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!lo(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Sc(d,t.dependencies),p=f.yaml,h=await Ec(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await po(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:X.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await vo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Yn(d),$e.set("push");const w=await go(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||ho(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:cg(s.finishDeploy,r,Y)}:{}}: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 Jw(t,e=[]){const n=Jl("architect");try{return await Gs("architect",Ip,dy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function yo(t,e,n=[],i){const r=fy(t),s=Jl("generator",y.bundleSpec);try{return await Gs("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),tE(e,Kr,i);try{return await Gs("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 _o(t,e=null){const n={...Jl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Gs("review",kp,hy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function zs(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=` - - `):e==="error"?(n.classList.add("error"),i.classList.add("error"),i.innerHTML=` - - `):i.innerHTML=` - - `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),zs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),zs(t,"completed"))}function Zw(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 Xw(t){at(parseInt(t.replace("step","")))}function at(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"),Jn();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 Qw(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 El(t){const e=Sl(t);console.log(`Step 1 (Prompt Architect): ${nn(Ip)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(kp)}`)}function Up(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function eb(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=bi(y.artifactBundle)?.id||null)}const Hp="results-replacement-error";function tb(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Hp);if(!r)return;const s=mp(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=`${So[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=()=>Ii(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Ic(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Ic(){const t=document.getElementById(Hp);t&&(t.hidden=!0)}function Wp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),eb(e),Pi(),Bt(!0),Tr(),y.resultsViewMode=e.resultsViewMode||"summary",Rr(),kn(),tb(t,{stage:n,runId:i,retry:r}),pn())}async function qp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=xo();kc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=Up();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - - - Refining...`});try{Ic();const r=_c(),s=r.id,o=py({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."});Co({runId:e}),Lt(2,e),at(2),Fe(2,!0);const a=await yo(o,t,[],e);if(!le(e))return;y.step2Result=a,uo(),fn(2,e);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,e),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,fo(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=bi(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=ro(r,{architect:2,generator:2,review:3});Wp(r,{previous:i,stage:s,runId:e,retry:qp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function kc(t,e,n){const i=`${Et}/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 nb(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function zp(){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){Se("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=xo();kc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - - Fixing…`);const s=Up();try{Ic();const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});bg(),Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=ro(o,{architect:2,generator:2,review:3});Wp(o,{previous:s,stage:a,runId:i,retry:zp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}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=De.slice();if(!t.trim()){Se("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=xo();try{if(await dl,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await kb()||!le(i)||(await wb(),!le(i)))return;const r=Sl(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),$w(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Ys(!0),El(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Co({prompt:t,runId:i}),sE(a,l),at(1),Lt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await Jw(t,u);if(!le(i))return;y.step1Result=c,Lw(),fn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=Si(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Lt(2,i),Fe(2,!0);const p=await yo(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,uo(),fn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=Si(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const m=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,fo(),fn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Pi();const b=so(y.step3Result);Tr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=ro(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():Dn("Pipeline Failed",{error:r.message,effectiveModel:Sl(document.getElementById("code-generator-model").value)}),at(s),Fe(s,!1),vg(r,{stage:s,runId:i}),zs(s,"error")}finally{le(i)&&(y.isRunning=!1,Ys(!1),pn())}}function ib(){const t=document.getElementById("code-generator-model").value,e=[js,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? - -Current: ${t} - -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 rb(){const t=wc();if(!t){Se("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}if(y.artifactBundle?.artifacts?.length>1){await sb();return}const{artifactType:i,artifactName:r,fileName:s}=Np(),o=jp(t,{artifactType:i,artifactName:r,fileName:s}),a=Ww(o);if(!a.canProceed){Se(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Ac(o,a,null,null)}async function sb(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Se("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),gc();return}const n=e_(y.artifactBundle);if(n.errors.length>0){Se(`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=mo(i),s={canProceed:r.valid&&n.errors.length===0,issues:[...n.errors,...r.errors],warnings:[...n.warnings,...r.warnings]};if(!s.canProceed){Se(`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};Ac(o,s,n.dependencies,n)}function ob(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    -

    FlutterFlow Commit Failed

    -

    ${W(t.error)}

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

    Errors:

    -
      `;for(const[r,s]of e.entries()){const o=nc(s);n+=`
    • - ${W(r)}: ${W(o)} -
    • `}n+="
    "}n+="
    ",n+=`
    - -
    `;const i=document.getElementById("step3-output");i&&(i.innerHTML=n,document.getElementById("btn-regenerate-from-error")?.addEventListener("click",()=>{Vp(t.error,e)}))}async function Vp(t,e){if(y.isRunning)return;const n=document.getElementById("code-generator-model").value;y.isRunning=!0;const i=xo(),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[p,h]of e.entries()){const g=nc(h);s+=`File: ${p} -Error: ${g} - -`}else s+=`${t} -`;const o=zh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Co({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await yo(o,n,[],i);if(!le(i))return;y.step2Result=a,uo(),fn(2,i);const l=document.getElementById("step2-output"),u=Si(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await _o(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,fo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=so(y.step3Result);Tr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=ro(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),vg(s,{stage:o,runId:i,retry:()=>Vp(t,e)}),zs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function ab(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 Gp(t){try{const e=await fetch(`${Et}/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 lb(t){try{const n=await(await fetch(`${Et}/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 cb(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Wd(t,e){const n=Yp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,fe=Kn({isLoading:!0}),localStorage.setItem(Os,JSON.stringify({email:t,sessionToken:e})),i&&tg()}function Kp(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),localStorage.removeItem(Os),localStorage.removeItem(Ds)}function Yp(){try{const t=localStorage.getItem(Os);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(Os),{email:null,sessionToken:null}}}async function ub(){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 lb(e);Wd(n,i),Jp();const r=qd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){qd();const i=n.message||"Sign-in link invalid or expired.";Se(i,"error"),wo(),ci(i,"error")}}else{const{email:n,sessionToken:i}=Yp();if(n&&i){const r=await cb(i);r?Wd(r.email,r.sessionToken):Kp()}}Cc()}function db(){try{localStorage.setItem(ul,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function qd(){try{const t=localStorage.getItem(ul);if(localStorage.removeItem(ul),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>q0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function wo(){const t=document.getElementById("signin-modal");if(!t)return;db(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ci(""),Ve(t)}function Jp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function ci(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 fb(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=no(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"),ci("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=ep(n);r&&ci(r,"error");try{const s=await Gp(n),o=ic(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ci(tp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ci("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function hb(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Kn({isResolved:!0}),J_({storage:window.localStorage,onIdentityChanged:Cc,onPlanChanged:Eo})}const pb=X_({sendLink:Gp,getEmail:()=>H.email||"",onState:gb});function gb(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=tp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function mb(){await pb()}function vb(){const t=K_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Se(`${e} Your run count, identity and stored keys are kept.`,"info")}function yb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function _b(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Cc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Ab(),Eo()}async function Zp(){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(K0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(V0,r.user_id),yt.token&&sessionStorage.setItem(G0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),_n()}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 va=null;function wb(t=5e3){return yt.resolved?Promise.resolve():(va||(va=Zp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([va,new Promise(e=>setTimeout(e,t))]))}function Xp(){const t=xn();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Pr(){const t=Xp();return t.month!==xn()?{count:0,month:xn()}:t}function bb(){const e={count:Pr().count+1,month:xn()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Ci(){return!!fe.isLoading}function Ot(){return!!fe.isResolved}function Eb(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(Bs,e)?e:null}function Sb(t){return t&&Object.entries(wp).find(([,e])=>e===t)?.[0]||null}function Yr(...t){return t.find(e=>e!=null&&e!=="")}function xb(...t){return t.find(e=>e&&typeof e=="object")||{}}function Ib(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=xb(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=Yr(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=Yr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=Eb(Yr(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=Y0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Sb(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Yr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function bo(){return Bs[fe.tier]??Bs.free}async function kb(){if(H.isVerified&&(!Ot()||Ci())&&(await eg({force:!0}),Eo()),H.isVerified&&!Ot())return Se("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Pr(),e=bo();if(t>=e)return Qp(t,e,{openModal:!0}),!1;const n=Math.floor(e*.8);if(t>=n){const i=e-t;Se(`${i} run${i===1?"":"s"} remaining this month.`,"warning")}return!0}function zd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Qp(t,e,n={}){Bt(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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){Se(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Ii();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=fe.tier;f==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${f} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",H.isVerified),u.classList.remove("hidden"),n.openModal&&Ii()}function Sl(t){return fe.tier==="free"&&rs.includes(t)?js:t}function Cb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=fe.tier,r=!(H.isVerified&&!Ot())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=rs.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&rs.includes(e.value)&&(e.value=js),e.disabled=!1,Rd.has(e)||(e.addEventListener("change",()=>{Ot()&&fe.tier==="free"&&rs.includes(e.value)&&(e.value=js,Ii()),El(e.value),cc()}),Rd.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(),El(e.value)}function Pc(){const t=H.isVerified&&!!H.email,e=t&&Ci(),n=!t||Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Yl,u=n?fe.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Xp(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Bs.free} generations used`}}Pb()}function Pb(){if(!(H.isVerified&&!!H.email))return;const e=Ci(),n=Ot(),i=Pr(),r=n?i.count:0,s=n?bo():0,o=Math.max(0,s-r),a=n?fe.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Zi(Ji[a]??0,uc());h.textContent=`${S} / 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 S=Date.parse(fe.periodEnd||""),P=n&&a!=="free"&&!!fe.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Pc(),H.isVerified&&(Ci()||!Ot())){zd();return}const{count:t}=Pr(),e=bo();t>=e&&!y.isRunning&&!iy()?Qp(t,e):zd()}function Ab(){Pc()}async function eg(t={}){const e=t.force===!0;if(!H.isVerified||!H.sessionToken){fe=Kn({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const n=H.sessionToken,i=localStorage.getItem(Ds);if(!e&&i)try{const{data:r,email:s,ts:o,version:a}=JSON.parse(i);if(a===Td&&s===H.email&&Date.now()-o<300*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",i)}try{const s=await(await fetch(`${Et}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken,user_id:yt.userId})})).json();if(!H.isVerified||H.sessionToken!==n)return;if(s.error){if(["unauthorized","invalid session","expired session"].some(a=>String(s.error).toLowerCase().includes(a))){Kp(),Cc();return}fe=Kn({isResolved:!1,error:s.error});return}fe=Ib(s),localStorage.setItem(Ds,JSON.stringify({version:Td,data:fe,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function tg(){localStorage.removeItem(Ds)}async function Fb(t){if(!H.isVerified||!H.sessionToken){ig(),wo();return}if(!wp[t]){Se("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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:uc()})})).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"),Se("Could not start checkout. Please try again.","error")}}async function Rb(t){if(!H.isVerified||!H.sessionToken){wo();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Se("Could not open billing portal. Please try again.","error")}}const Vs=new Set;function ng(){Vs.forEach(t=>t.abort()),Vs.clear()}async function Gs(t,e,n,i={},r=[]){const o=new AbortController;Vs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(z0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Wn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=by(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),_n())}else bb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Vs.delete(o)}}let xl=!1;function Tb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),tg(),xl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Se("Checkout cancelled.","info")),e}function Mb(){if(!xl)return;xl=!1;const t=fe.tier!=="free";Se(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function Eo(){const t=H.isVerified&&!!H.email,e=fe.tier,n=t&&Ci(),i=!t||Ot(),r=document.getElementById("subscription-tier-badge");if(r){const a=Yl,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"),$b(i?e:null),Cb(),cc(),_n(),Eg()}function $b(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 Lb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=ly[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 Il(){const t=uc(),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=Zi(Ji.professional,t)),n&&(n.textContent=Zi(Ji.power,t)),i&&(i.textContent=Zi(Ji.professional,t)),r&&(r.textContent=Zi(Ji.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ii(){Il();const t=document.getElementById("pricing-modal");t&&Ve(t),ow().then(()=>Il())}function ig(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Se(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()=>{sy(),Jb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Nb(),window.__heroField=p0(),window.__pipelineLogo=y0(),vE(),lc=B0({onSubmit:Sr}),dl=(async()=>{try{await ub(),Tb(),await eg()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await dl,Mb(),Eo(),Il(),Lb(),await Nw(),Rw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Lp(),Zp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(mc(),ao())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(dg(),$e.phaseId||Rc(),Gd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(Gd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,Tc()},1e3))}),jc()});function Nb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Ob(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Lp()}let or=null;async function kl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Od,n=++oo,i=()=>e===Od,r=gt;wr=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==ke)return kl();if(n>un&&(un=n,hc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),wr={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==ke)return kl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function Bb(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=wr;return!n||n.key!==ke||n.generation!==gt?null:e}function Ac(t,e,n,i=null){or={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,kl();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function rg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),or=null}function Db(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 sg(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function og(t){Tc(),ob(t);const e=t.remoteRefusal===!0;Fc(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 Fc(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(nc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function ag(t){Fc(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 lg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Cl=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Fc(t,{heading:e,title:n,guidance:i})}let Cl=null;function cg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function jb(){const t=Cl;if(!t||Mc)return;Cl=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);ug(),$c(!0),Rc();try{$e.set("package");const n=a_(t.fileMap,t.landed,t.serializedYaml),i=await po(n,new Map),r=await vo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),$e.set("push");const o=await go(e,s);if(o.success){Ks({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||ho(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ks({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function ug(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function Ub(){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 Vd={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}},Hb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function dg(){Un&&clearTimeout(Un),Un=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){dg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(sd(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Vd[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=Vd[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=Hb.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(Wb(e)),fg(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&&(sd(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function Wb(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 Rc(t){$e.start(t)}function Tc(){$e.stop()}function fg(t,e,n,i=null){const r=document.getElementById("commit-progress-bar"),s=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");r&&(r.style.width=`${Math.round(t*10)/10}%`),s&&(s.textContent=e),o&&(o.textContent=n),a&&(a.textContent=i||"",a.classList.toggle("hidden",!i))}function Gd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,fg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function qb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===X.CODE_FILE):t.codeInfo?.codeType===X.CODE_FILE}let Mc=!1;function $c(t){Mc=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 Ks(t){Tc(),$c(!1);const e=hp(t);e===Ne.COMMITTED?sg(t):e===Ne.PARTIAL?ag(t):e===Ne.UNCONFIRMED?lg(t):og(t)}async function zb(){if(!or){console.error("No pending commit data");return}if(Mc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=or;if(or=null,sr=Bb(),rg(),$c(!0),Rc({withProvisioning:qb(t)}),t.bundlePlan){const o=await Yw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Np(),s=await Kw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ks(s)}window.runThinkingPipeline=Sr;window.toggleStep=Xw;window.toggleSection=Zw;window.selectWorkflowStep=at;window.copyCode=Qw;window.retryWithDifferentModel=ib;window.openApiKeysModal=gc;window.closeApiKeysModal=Mp;window.openComposerSettings=Tp;window.closeComposerSettings=Ew;window.walkthroughConnectAccount=bw;window.closeWalkthroughModal=xw;window.openWalkthroughModal=Sw;window.advanceWalkthrough=mc;window.commitToFlutterFlow=Gw;function Vb(){y.isRunning||Bt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Gb(){Tp();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Vb;window.openModelSelector=Gb;window.handlePromptImageSelect=rw;window.removePromptImage=sw;window.saveApiKeys=Cw;window.validateFlutterFlowConnection=yc;window.clearAllApiKeys=Pw;window.toggleKeyVisibility=Mw;window.handleWelcomeVideoEnd=Ob;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=rb;window.updateFlutterFlowCredentialStatus=ab;window.openCommitConfirmModal=Ac;window.closeCommitConfirmModal=rg;window.closeCommitSuccessModal=Db;window.closeCommitTerminalModal=ug;window.finishProvisionedDeploy=jb;window.showCommitPartialModal=ag;window.showCommitUnconfirmedModal=lg;window.showCommitSuccessModal=sg;window.showCommitFailureModal=og;window.toggleCodePreview=Ub;window.confirmCommitToFlutterFlow=zb;window.runRefinement=qp;window.regenerateFromPastedErrors=zp;window.clearErrorInput=nb;window.setFlutterFlowEndpoint=yw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=wo;window.closeSignInModal=Jp;window.handleMagicLinkRequest=fb;window.handleSignOut=hb;window.handleSendNewLink=mb;window.handleClearCache=vb;window.handleDeleteAccount=yb;window.closeDeleteUnavailableModal=_b;window.startCheckout=Fb;window.openCustomerPortal=Rb;window.openPricingModal=Ii;window.closePricingModal=ig;let cs=null,hg=null,hn={1:"pending",2:"pending",3:"pending"},qn=1,Pl=null,Lc=null;const So={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Kb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Yb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function xo(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function pg(){y.runId+=1}function Nc(t){return document.getElementById(`pdot-${t}`)}const gg=window.matchMedia("(max-width: 920px)");function Kd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=gg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Jb(){Kd(),gg.addEventListener("change",Kd)}function Zb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Ys(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 Io(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){hn[t]=e;const n=Nc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=So[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 Xb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Ar(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${Qb()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function Qb(){const t=33.333333333333336,e=hn[qn];if(e==="active"&&Pl!==null){const n=(Date.now()-Pl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:Xb()/3*100}function ko(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?Yb[t]:Kb[t]),i&&(i.textContent=Zb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${So[t]}${a}`}}function eE(t){hn[t]==="pending"||hn[t]==="skipped"||(Lc=t,[1,2,3].forEach(e=>{const n=Nc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),ko(t))}function Oc(){Lc=null,[1,2,3].forEach(t=>{const e=Nc(t);e&&e.removeAttribute("aria-pressed")})}function mg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function tE(t,e,n){le(n)&&mg(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function Bc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function nE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Gn()}function iE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function rE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=rE;function sE(t,e){_p(t,document.getElementById("main-stage-container"),iE()),U0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function Co(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Fr(),kn(),Bt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),Io("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}hg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Oc(),Bc(),mg(""),[1,2,3].forEach(a=>zn(a,"pending")),Lt(1,n),oE()}function Lt(t,e){le(e)&&(qn=t,Pl=Date.now(),Oc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),ko(t),Ar())}function fn(t,e){le(e)&&(zn(t,"done"),Lc===null&&ko(t,{done:!0}),Ar())}function vg(t,{stage:e=1,runId:n,retry:i=yg}={}){if(!le(n))return;Po(),Fr(),kn(),Io("failed"),Bt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Oc(),ko(e),Ar();const o=mp(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=`${So[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>Ii()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Al}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Al}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Al(){pg(),ng(),y.isRunning=!1,Ys(!1),pn(),Io("settled"),kn(),Po(),Fr(),Bc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Bt(!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 yg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),Bc(),Sr()}function oE(){Po(),cs=setInterval(()=>{const t=(Date.now()-hg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Ar()},250)}function Po(){cs&&(clearInterval(cs),cs=null)}let ar=null;function Fr(){ar&&(clearTimeout(ar),ar=null)}function Pi(){Po(),Fr(),Io("settled"),Ar();const t=document.getElementById("pipeline-progress-fill");ar=setTimeout(()=>{ar=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function ki(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function _g(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function aE(){return y_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function lE(t){return` -
    - ${ki(t.severity)} -
    -
    ${W(t.message)}
    - ${t.suggestion?`
    ${W(t.suggestion)}
    `:""} - ${W(t.source)} -
    -
    - `}function cE(t){return` -
  • -
    - ${W(t.title)} - ${t.detail&&t.detail!==t.title?`

    ${W(t.detail)}

    `:""} -
    -
  • - `}function uE(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=>` -
    • - ${ki(u.severity)} - - ${W(u.message)} - ${u.suggestion?`${W(u.suggestion)}`:""} - -
    • - `).join("")} -
    - `:"",a=t.warnings.length?` -
    -

    ${ki("warning")} Bundle

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

    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=>` -
    1. - ${W(u.title)} - ${u.detail&&u.detail!==u.title?`${W(u.detail)}`:""} -
    2. - `).join("")} -
    -
    - `:"";e.innerHTML=` -
    -
    -

    ${W(t.title)}

    -

    ${W(t.summary)}

    -
    -
    Artifact${t.artifacts.length===1?"":"s"}
    ${t.artifacts.map(u=>W(u.artifactType||u.type||u.name)).join(" · ")}
    -
    Public API
    ${t.artifacts.flatMap(u=>u.publicApi||[]).map(W).join(" · ")||"No parameters returned"}
    -
    Manual Steps Required
    ${l||"None reported"}
    -
    Review
    ${W(t.status||"Not reported")}
    -
    - ${o} - ${a} -
    -
    - -
    - Is the generated code correct? -
    - - -
    - -
    -
    -
    - `}function dE(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(lE).join(""):`
    ${ki(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` -
  • ${W(l.name)}${l.version?` ${W(l.version)}`:""}${l.reason?`

    ${W(l.reason)}

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

    ${W(l.description)}

    `:""}
  • - `).join(""):'
  • No relationships for this file
  • ';return` -
    -
    - ${ki(e.status)} ${W(_g(e.status))} -

    ${W(e.artifactName)}

    - ${e.description?`

    ${W(e.description)}

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

    Code Review findings

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

    Manual FlutterFlow steps for this file

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

    Dependencies

    -
      ${r}
    -
    -
    -

    Deployment

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

    Public API

    -
    ${o}
    -
    -
    -

    Imports

    -
    ${s}
    -
    -
    -

    Relationships

    -
      ${a}
    -
    -
    - `}function fE(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=""),Yd();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&&Dc(o.dataset.artifactId)},Yd()),e&&e.classList.add("visible")}function Yd(){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")wg();else{const a=s.dataset.artifactId;a&&Dc(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 Rr(){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=aE(),o=wc();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")}uE(s),fE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` -`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=vp(a),!nE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=dE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Tr(t,e){const n=document.getElementById("main-stage-container"),i=D0(n),r=document.body.classList.contains("results-fullscreen");Fr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),Bt(!0),y.selectedArtifactId||(y.selectedArtifactId=bi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Rr(),pn(),hE(),r||_p(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function hE(){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=""),Fl=!1}function Dc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Rr()}function wg(){y.resultsViewMode="summary",Rr()}function pE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=wc(),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 Fl=!1;async function gE(t){const e=document.getElementById("btn-feedback-up"),n=document.getElementById("btn-feedback-down"),i=document.getElementById("results-feedback-status");if(!e||!n||Fl)return;const r=l=>{i&&(i.textContent="",i.offsetWidth,i.textContent=l)},s=l=>{Fl=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 kc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function mE(){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 bg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function vE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function Bt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function Eg(){const t=H.isVerified&&!!H.email,e=fe.tier||"free",n=t&&Ci(),i=!t||Ot(),s=n?"Checking…":i?Yl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Pc();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 yE(){Eg();const t=document.getElementById("credits-modal");t&&Ve(t)}function _E(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function Sg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),lc?.cancelTyping?.(),y.isRunning&&(pg(),ng(),y.isRunning=!1,Ys(!1),Pi(),y.artifactBundle?Rr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")Bt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&Bt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let Jd=!1;function jc(){const t=window.location.hash.replace(/^#/,"");Sg(t||"home",!1,Jd),Jd=!0}window.addEventListener("popstate",t=>{jc()});window.addEventListener("hashchange",()=>{jc()});window.copyResultsCode=pE;window.selectArtifact=Dc;window.selectResultsSummary=wg;window.submitResultsFeedback=gE;window.showErrorInputPanel=mE;window.hideErrorInputPanel=bg;window.setGenerationStageVisible=Bt;window.switchView=Sg;window.selectPipelineStage=eE;window.editPipelinePrompt=Al;window.retryPipelineRun=yg;window.openCreditsModal=yE;window.closeCreditsModal=_E; diff --git a/dist/index.html b/dist/index.html index be0cc03..c8f09cc 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3273,7 +3273,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/src/composerAdapter.js b/src/composerAdapter.js index c1f3790..72c9dc0 100644 --- a/src/composerAdapter.js +++ b/src/composerAdapter.js @@ -16,10 +16,13 @@ * typed prompt rests long enough to read, then backspaces out at a held-key * pace and leaves the empty field on its hint text. */ -const HERO_DEMO_HOLD_MS = 5200; -const HERO_DEMO_TYPE_MS = 73; -const HERO_DEMO_READ_MS = 1600; -const HERO_DEMO_ERASE_MS = 35; +export const HERO_DEMO_HOLD_MS = 5200; +export const HERO_DEMO_TYPE_MS = 73; +export const HERO_DEMO_READ_MS = 1600; +export const HERO_DEMO_ERASE_MS = 35; + +/** A chip fill types its prompt at this pace (prototype fillChip). */ +const CHIP_TYPE_MS = 22; // The hero demo's media-query listener is tracked per composer element so a // repeat initComposer on the same DOM replaces the previous instance's @@ -31,6 +34,39 @@ export function canSubmit(value, isBusy) { return Boolean(value && value.trim()) && !isBusy; } +/** + * The hero demo as a timeline: what shows `elapsed` ms after the demo starts, + * for an example `length` characters long. Like a GSAP timeline or a Remotion + * typewriter, every frame is derived from the clock rather than from how many + * timer callbacks have run, so a late tick lands everything already due — a + * busy main thread drops frames, never stretches the demo. + * + * Character k types in at hold + (k-1)·type; the full example then rests for + * the read beat; character k erases at erase + (k-1)·erase. Returns the + * characters showing, whether a key just landed (`keying`: the caret holds + * solid) or the field is idle (it blinks), whether the demo is over, and the + * ms until the next change. + */ +export function heroDemoFrame(elapsed, length) { + const typedAt = HERO_DEMO_HOLD_MS + (length - 1) * HERO_DEMO_TYPE_MS; + const eraseAt = typedAt + HERO_DEMO_READ_MS; + if (elapsed < HERO_DEMO_HOLD_MS) { + return { chars: 0, keying: false, done: false, next: HERO_DEMO_HOLD_MS - elapsed }; + } + if (elapsed < typedAt) { + const chars = Math.floor((elapsed - HERO_DEMO_HOLD_MS) / HERO_DEMO_TYPE_MS) + 1; + const next = HERO_DEMO_HOLD_MS + chars * HERO_DEMO_TYPE_MS - elapsed; + return { chars, keying: true, done: false, next }; + } + if (elapsed < eraseAt) { + return { chars: length, keying: false, done: false, next: eraseAt - elapsed }; + } + const erased = Math.min(length, Math.floor((elapsed - eraseAt) / HERO_DEMO_ERASE_MS) + 1); + const done = erased === length; + const next = done ? 0 : eraseAt + erased * HERO_DEMO_ERASE_MS - elapsed; + return { chars: length - erased, keying: true, done, next }; +} + /** * Wire the composer to the DOM and the existing pipeline. Call once after the * composer markup exists. The ghost layer mirrors the textarea so the demo @@ -147,31 +183,20 @@ export function initComposer({ onSubmit }) { mirrorTyped(); syncSend(); composer.classList.add("is-demo-typing"); - let index = 0; - const step = (delta, keying) => { - index += delta; - field.value = demoPrompt.slice(0, index); - mirrorTyped(); - composer.classList.toggle("is-demo-keying", keying); - }; - // Erasing the last character retires the caret and restores the hint. - const eraseNext = () => { + // Each tick renders the timeline frame due now (heroDemoFrame) and sleeps + // until the next change. Erasing the last character retires the caret and + // restores the hint. + const startedAt = performance.now(); + const tick = () => { if (!heroDemoTyping) return; - step(-1, true); - if (index > 0) heroDemoTimer = setTimeout(eraseNext, HERO_DEMO_ERASE_MS); - else cancelHeroDemo(); - }; - // The last character lands idle, so the caret blinks while the full - // example rests. - const typeNext = () => { - if (!heroDemoTyping) return; - const more = index + 1 < demoPrompt.length; - step(1, more); - heroDemoTimer = more - ? setTimeout(typeNext, HERO_DEMO_TYPE_MS) - : setTimeout(eraseNext, HERO_DEMO_READ_MS); + const frame = heroDemoFrame(performance.now() - startedAt, demoPrompt.length); + field.value = demoPrompt.slice(0, frame.chars); + mirrorTyped(); + composer.classList.toggle("is-demo-keying", frame.keying); + if (frame.done) cancelHeroDemo(); + else heroDemoTimer = setTimeout(tick, frame.next); }; - heroDemoTimer = setTimeout(typeNext, HERO_DEMO_HOLD_MS); + heroDemoTimer = setTimeout(tick, HERO_DEMO_HOLD_MS); } // End a running demo early by landing its end state — the empty field on @@ -263,9 +288,14 @@ export function initComposer({ onSubmit }) { chipTyping = true; syncSend(); composer.classList.add("is-demo-typing", "is-demo-keying"); - let index = 0; + // Like the hero demo, the fill reads its progress off the clock: a late + // tick lands every character already due instead of stretching the fill. + const startedAt = performance.now(); chipTimer = setInterval(() => { - index += 1; + const index = Math.min( + text.length, + Math.floor((performance.now() - startedAt) / CHIP_TYPE_MS), + ); field.value = text.slice(0, index); mirrorTyped(); if (index >= text.length) { @@ -274,7 +304,7 @@ export function initComposer({ onSubmit }) { } else { syncSend(); } - }, 22); + }, CHIP_TYPE_MS); } chips.forEach((chip) => { diff --git a/src/composerAdapter.test.js b/src/composerAdapter.test.js index 883b167..5bfffa5 100644 --- a/src/composerAdapter.test.js +++ b/src/composerAdapter.test.js @@ -1,6 +1,18 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { canSubmit } from "./composerAdapter.js"; +import { + HERO_DEMO_ERASE_MS, + HERO_DEMO_HOLD_MS, + HERO_DEMO_READ_MS, + HERO_DEMO_TYPE_MS, + canSubmit, + heroDemoFrame, +} from "./composerAdapter.js"; + +const LENGTH = "A circular progress gauge with a gradient stroke".length; +const TYPED_AT = HERO_DEMO_HOLD_MS + (LENGTH - 1) * HERO_DEMO_TYPE_MS; +const ERASE_AT = TYPED_AT + HERO_DEMO_READ_MS; +const DONE_AT = ERASE_AT + (LENGTH - 1) * HERO_DEMO_ERASE_MS; test("canSubmit refuses empty, whitespace-only and busy input", () => { assert.equal(canSubmit("", false), false); @@ -9,3 +21,71 @@ test("canSubmit refuses empty, whitespace-only and busy input", () => { assert.equal(canSubmit("A progress gauge", true), false); assert.equal(canSubmit("A progress gauge", false), true); }); + +test("hero demo holds empty with a blinking caret, then types one character per beat", () => { + assert.deepEqual(heroDemoFrame(0, LENGTH), { + chars: 0, + keying: false, + done: false, + next: HERO_DEMO_HOLD_MS, + }); + assert.equal(heroDemoFrame(HERO_DEMO_HOLD_MS - 1, LENGTH).chars, 0); + assert.deepEqual(heroDemoFrame(HERO_DEMO_HOLD_MS, LENGTH), { + chars: 1, + keying: true, + done: false, + next: HERO_DEMO_TYPE_MS, + }); + assert.equal(heroDemoFrame(HERO_DEMO_HOLD_MS + HERO_DEMO_TYPE_MS, LENGTH).chars, 2); +}); + +test("hero demo rests on the full example with the caret blinking, then erases", () => { + assert.deepEqual(heroDemoFrame(TYPED_AT, LENGTH), { + chars: LENGTH, + keying: false, + done: false, + next: HERO_DEMO_READ_MS, + }); + assert.equal(heroDemoFrame(ERASE_AT - 1, LENGTH).keying, false); + assert.deepEqual(heroDemoFrame(ERASE_AT, LENGTH), { + chars: LENGTH - 1, + keying: true, + done: false, + next: HERO_DEMO_ERASE_MS, + }); + assert.equal(heroDemoFrame(DONE_AT - 1, LENGTH).chars, 1); + assert.deepEqual(heroDemoFrame(DONE_AT, LENGTH), { + chars: 0, + keying: true, + done: true, + next: 0, + }); + assert.equal(heroDemoFrame(DONE_AT + 60000, LENGTH).done, true); +}); + +test("a late tick lands everything already due instead of stretching the demo", () => { + // Ten typing beats plus a little: a timer that fired 700ms late still shows + // the eleventh character, exactly as an on-time tick would. + const late = heroDemoFrame(HERO_DEMO_HOLD_MS + 10 * HERO_DEMO_TYPE_MS + 5, LENGTH); + assert.equal(late.chars, 11); + assert.equal(late.next, HERO_DEMO_TYPE_MS - 5); + // A tick that sleeps through the whole erase still ends the demo on time. + assert.equal(heroDemoFrame(DONE_AT + 1, LENGTH).done, true); +}); + +test("sampled every millisecond, the demo types up and erases down one character at a time", () => { + const seen = []; + for (let elapsed = 0; elapsed <= DONE_AT; elapsed += 1) { + const frame = heroDemoFrame(elapsed, LENGTH); + if (seen[seen.length - 1] !== frame.chars) seen.push(frame.chars); + // `next` always points at the exact moment the frame changes. + if (!frame.done) { + assert.ok(frame.next > 0, `next at ${elapsed}ms`); + assert.notDeepEqual(heroDemoFrame(elapsed + frame.next, LENGTH), frame); + assert.deepEqual(heroDemoFrame(elapsed + frame.next - 0.5, LENGTH).chars, frame.chars); + } + } + const up = Array.from({ length: LENGTH + 1 }, (_, index) => index); + const down = up.slice(0, -1).reverse(); + assert.deepEqual(seen, [...up, ...down]); +}); From b953e9a6cd7b6ee9f8cb496ee264699e00cb1f20 Mon Sep 17 00:00:00 2001 From: Stuart Date: Sun, 11 Oct 2026 16:03:11 +1100 Subject: [PATCH 06/10] test: stop three animation specs racing the wall clock under load Under parallel local runs these failed intermittently. Baseline on #126's tree, before this change: 5/20 in one --repeat-each batch. - stu445 morph: a fixed 1250ms sleep read the reveal before a slow morph had handed off. It now polls for the reveal, and waits for the 1400ms motion sample to exist before reading it. Same expected values. - stu389 field: counted frames over 500ms against a >5 bar, and read 5 at about 10fps. It now counts over 1500ms with the same bar. - stu390 logo loop: two re-entry checks compared counts from separate windows (framesB < framesA * c). The file's own comment says this trips when a slow runner stalls the baseline. They now use the file's existing framesPerDisplayFrame same-window ratio (< 1.6x), which still catches a doubled loop. After: 60/60 and 135/135 across repeat batches, and 3 consecutive clean full runs (265/265). --- e2e/stu389-hero-mark-field.spec.js | 4 +++- e2e/stu390-logo-loop.spec.js | 22 ++++++++++++++-------- e2e/stu445-exact-fidelity.spec.js | 10 ++++++---- 3 files changed, 23 insertions(+), 13 deletions(-) diff --git a/e2e/stu389-hero-mark-field.spec.js b/e2e/stu389-hero-mark-field.spec.js index 78adc4d..7eecf9b 100644 --- a/e2e/stu389-hero-mark-field.spec.js +++ b/e2e/stu389-hero-mark-field.spec.js @@ -273,7 +273,9 @@ test.describe("frame measurements before and after disabling the effect", () => // A genuine frame metric: count requestAnimationFrame callbacks the field // drives over a fixed window. A module that never renders yields 0 here. - const framesOn = await countRafFrames(page, 500); + // The window is long enough that a loaded machine's dropped frames can't + // push a field that is running under the bar. + const framesOn = await countRafFrames(page, 1500); expect(framesOn, "with the effect enabled the field should animate, not sit idle").toBeGreaterThan(5); await page.emulateMedia({ reducedMotion: "reduce" }); diff --git a/e2e/stu390-logo-loop.spec.js b/e2e/stu390-logo-loop.spec.js index 7ea4b46..f4f2aed 100644 --- a/e2e/stu390-logo-loop.spec.js +++ b/e2e/stu390-logo-loop.spec.js @@ -201,10 +201,13 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { document.dispatchEvent(new Event("visibilitychange")); }); await expect.poll(() => running(page), { timeout: 3000 }).toBe(true); - const framesReenter = await steadyFramesIn(page); - expect(framesReenter, "a restored loop should stay a single loop").toBeGreaterThan(5); - // If a second loop had leaked in, the painted-frame rate would ~double. - expect(framesReenter).toBeLessThan(framesOn * 1.6); + const reenter = await framesPerDisplayFrame(page, 500); + expect(reenter.logo, "a restored loop should stay a single loop").toBeGreaterThan(5); + expect(reenter.display, "the window should contain real display frames").toBeGreaterThan(0); + // If a second loop had leaked in, it would paint ~2x per display frame. + // Measured against display frames in the same window, so a loaded machine + // can't stall an earlier baseline and fake a doubling. + expect(reenter.logo).toBeLessThan(reenter.display * 1.6); }); test("CSS-hidden pipeline (display:none) stops rendering with no raf leak", async ({ page }) => { @@ -220,11 +223,14 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { const framesHidden = await framesIn(page, 500); expect(framesHidden, "no logo frames once the pipeline is display:none").toBe(0); - // Re-enter: still a single loop, never a doubled one. + // Re-enter: still a single loop, never a doubled one — painted frames + // per display frame in one window, as above. await revealPipeline(page); - const framesBack = await steadyFramesIn(page); - expect(framesBack).toBeGreaterThan(5); - expect(framesBack).toBeLessThan(framesOn * 1.7); + await expect.poll(() => running(page), { timeout: 3000 }).toBe(true); + const back = await framesPerDisplayFrame(page, 500); + expect(back.logo).toBeGreaterThan(5); + expect(back.display).toBeGreaterThan(0); + expect(back.logo).toBeLessThan(back.display * 1.6); }); test("viewport-offscreen arena stops rendering even though it is not display:none", async ({ page }) => { diff --git a/e2e/stu445-exact-fidelity.spec.js b/e2e/stu445-exact-fidelity.spec.js index e342bea..c9eb522 100644 --- a/e2e/stu445-exact-fidelity.spec.js +++ b/e2e/stu445-exact-fidelity.spec.js @@ -140,10 +140,12 @@ test('morph keyframes, opaque ghost, hidden destination and reading-order reveal await expect(page.locator('.composer-morph')).toHaveCount(1); expect(await page.locator('.composer-morph').evaluate(el => getComputedStyle(el).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)'); await expect(page.locator('#main-stage-container')).toHaveCSS('visibility','hidden'); - await page.waitForTimeout(1250); - const reveal = await page.locator('#progress-title-text').evaluate(el => ({ name:getComputedStyle(el).animationName, delay:getComputedStyle(el).animationDelay, duration:getComputedStyle(el).animationDuration })); - expect(reveal).toEqual({ name:'fidelity-rise', delay:'0.32s', duration:'0.5s' }); - await page.waitForTimeout(300); + // Wait for the reveal and the last motion sample themselves, not for + // wall-clock sleeps: under load the 1120ms morph and the sampling timers + // land late, and a fixed sleep then reads the panel before it reveals. + const reveal = () => page.locator('#progress-title-text').evaluate(el => ({ name:getComputedStyle(el).animationName, delay:getComputedStyle(el).animationDelay, duration:getComputedStyle(el).animationDuration })); + await expect.poll(reveal).toEqual({ name:'fidelity-rise', delay:'0.32s', duration:'0.5s' }); + await page.waitForFunction(() => window.motionEvidence[0]?.samples.some(s => s.t === 1400)); const [motion] = await page.evaluate(() => window.motionEvidence); expect(motion.options.duration).toBe(1120); expect(motion.frames.map(f => f.offset)).toEqual([0,.14,.28,1]); From cba2b30a110b54f8af9c10beb73c4c3623460faf Mon Sep 17 00:00:00 2001 From: Stuart Date: Sun, 11 Oct 2026 16:12:06 +1100 Subject: [PATCH 07/10] fix(paywall): show only the screen on submit; pricing waits for View Plans Submitting a prompt at the limit used to open the pricing dialog on top of the "Free generations used" screen. Now it shows only the screen, and its View Plans button opens pricing when the user chooses. The openModal option had no other caller, so it is removed. Specs: stu382 asserts pricing stays closed on submit and opens from View Plans. stu391 asserts the run attempt leaves pricing closed. Mutation-checked: re-opening pricing on submit fails both. --- app.js | 5 +- .../{index-3BNsfJIv.js => index-AYQV7JZN.js} | 66 +++++++++---------- dist/index.html | 2 +- e2e/stu382-plans-paywall.spec.js | 14 ++-- e2e/stu391-tutorial-onboarding.spec.js | 8 +-- 5 files changed, 51 insertions(+), 44 deletions(-) rename dist/assets/{index-3BNsfJIv.js => index-AYQV7JZN.js} (92%) diff --git a/app.js b/app.js index 9a557b0..33d4598 100644 --- a/app.js +++ b/app.js @@ -6560,7 +6560,7 @@ async function canRunPipeline(prompt) { const { count } = getUsage() const limit = getRunLimit() if (count >= limit) { - showPaywallExhausted(count, limit, { openModal: true, prompt }) + showPaywallExhausted(count, limit, { prompt }) return false } const warningThreshold = Math.floor(limit * 0.8) @@ -6625,8 +6625,9 @@ function showPaywallExhausted(count, limit, options = {}) { if (promptEl) promptEl.textContent = options.prompt } + // Only the screen: its View Plans button opens pricing when the user + // chooses, rather than a dialog stacked over it. paywall.classList.remove('hidden') - if (options.openModal) openPricingModal() } function getEffectiveModel(selectedModel) { diff --git a/dist/assets/index-3BNsfJIv.js b/dist/assets/index-AYQV7JZN.js similarity index 92% rename from dist/assets/index-3BNsfJIv.js rename to dist/assets/index-AYQV7JZN.js index 5a585ea..5810630 100644 --- a/dist/assets/index-3BNsfJIv.js +++ b/dist/assets/index-AYQV7JZN.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 E=typeof window<"u"?window:void 0,Be=typeof globalThis<"u"?globalThis:E,qe=Be?.navigator,F=Be?.document,_e=Be?.location,Ml=Be?.fetch,wa=Be!=null&&Be.XMLHttpRequest&&"withCredentials"in new Be.XMLHttpRequest?Be.XMLHttpRequest:void 0,Yc=Be?.AbortController,Mg=Be?.CompressionStream,Je=qe?.userAgent;function tf(){return!(!E||E.navigator.onLine===!1)}var Ti=typeof globalThis<"u"?globalThis:E;Ti&&typeof self>"u"&&(Ti.self=Ti),Ti&&typeof File>"u"&&(Ti.File=function(){});var N=E??{},oe={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Jc(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 ce(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){Jc(s,i,r,o,a,"next",l)}function a(l){Jc(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 nf(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 Zc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Xc(t){return typeof t=="string"||t}function Qc(t){return typeof t=="string"?t:void 0}var Mi,$g=["$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"],Kt=(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})({}),eu=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Lg=["$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"],Ng=["token"],rf="NativeGzipValidationError",ba=t=>t.length>=2&&t[0]===31&&t[1]===139,tu=(t,e)=>t===eu.GZipJS||e===eu.GZipJS||e==="gzip",nu=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Or=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=rf,e},Og=(function(){var t=ce((function*(e,n){18>e.size&&Or("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());ba(i)&&i[2]===8||Or("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Mi)return Mi;Mi=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;Mi[c]=d>>>0}return Mi})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Or("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Or("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Ea(){return Ea=ce((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=ce((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 Og(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ea.apply(this,arguments)}var Bg=["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"],iu=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Bg.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Zs=function(t){return t.trim()},Sa=function(t){return t.replace(/^\$/,"")};function sf(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 of=Object.prototype,af=of.hasOwnProperty,Xs=of.toString,U=Array.isArray||function(t){return Xs.call(t)==="[object Array]"},Ue=t=>typeof t=="function",me=t=>t===Object(t)&&!U(t),rn=t=>{if(me(t)){for(var e in t)if(af.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,Q=t=>Xs.call(t)=="[object String]",xa=t=>Q(t)&&t.trim().length===0,Qe=t=>t===null,q=t=>C(t)||Qe(t),Ae=t=>Xs.call(t)=="[object Number]"&&t==t,Vt=t=>Ae(t)&&t>0,wt=t=>Xs.call(t)==="[object Boolean]",Dg=t=>t instanceof FormData,jg=t=>j(Lg,t),Ug=t=>j(Ng,t);function lf(t){return t===null||typeof t!="object"}function ds(t,e){return{}.toString.call(t)==="[object "+e+"]"}function $l(t){return typeof Event<"u"&&cf(t,Event)}function cf(t,e){try{return t instanceof e}catch{return!1}}var Hg=[!0,"true",1,"1","yes"],Do=t=>j(Hg,t),Wg=[!1,"false",0,"0","no"];function Rt(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Ae(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),Rt(r||n,e,n,i))}class qg{constructor(e){this.tt={},this.et=e.et,this.it=Rt(e.bucketSize,0,100,e.rt),this.nt=Rt(e.refillRate,0,this.it,e.rt),this.st=Rt(e.refillInterval,0,864e5,e.rt)}ot(e,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 lt="Mobile",fs="iOS",sn="Android",mi="Tablet",uf=sn+" "+mi,df="iPad",ff="Apple",hf=ff+" Watch",er="Safari",vi="BlackBerry",pf="Samsung",gf=pf+"Browser",mf=pf+" Internet",Hn="Chrome",zg=Hn+" OS",vf=Hn+" "+fs,Ll="Internet Explorer",yf=Ll+" "+lt,Nl="Opera",Vg=Nl+" Mini",Ol="Edge",_f="Microsoft "+Ol,di="Firefox",wf=di+" "+fs,cr="Nintendo",ur="PlayStation",fi="Xbox",bf=sn+" "+lt,Ef=lt+" "+er,qi="Windows",Ia=qi+" Phone",ru="Nokia",ka="Ouya",Sf="Generic",Gg=Sf+" "+lt.toLowerCase(),xf=Sf+" "+mi.toLowerCase(),Ca="Konqueror",If="Oculus Browser",hs="Vivaldi",kf="Yandex",ps="Whale",Pa="DuckDuckGo",Cf="Pale Moon",gs="Waterfox",tr="Brave",Pf="Google Search App",Se="(\\d+(\\.\\d+)?)",jo=new RegExp("Version/"+Se),Kg=new RegExp(fi,"i"),Yg=new RegExp(ur+" \\w+","i"),Jg=new RegExp(cr+" \\w+","i"),Bl=new RegExp(vi+"|PlayBook|BB10","i"),Zg={"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"},Af=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?tr:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Pf:j(t," OPR/")&&j(t,"Mini")?Vg:j(t," OPR/")?Nl:Bl.test(t)?vi:j(t,"IE"+lt)||j(t,"WPDesktop")?yf:j(t,"OculusBrowser")?If:j(t,gf)?mf:j(t,Ol)||j(t,"Edg/")?_f:j(t,hs+"/")?hs:j(t,"YaBrowser/")?kf:j(t,ps+"/")?ps:j(t,Pa+"/")||j(t,"Ddg/")?Pa:j(t,"FBIOS")?"Facebook "+lt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?vf:j(t,"CrMo")||j(t,Hn)?Hn:j(t,sn)&&j(t,er)?bf:j(t,"FxiOS")?wf:j(t.toLowerCase(),Ca.toLowerCase())?Ca:j(t,tr+"/")?tr:((s,o)=>o&&j(o,ff)||(function(a){return j(a,er)&&!j(a,Hn)&&!j(a,sn)})(s))(t,e)?j(t,lt)?Ef:er:j(t,"PaleMoon/")?Cf:j(t,gs+"/")?gs:j(t,di)?di:j(t,"MSIE")||j(t,"Trident/")?Ll:j(t,"Gecko")?di:"")},Xg={[yf]:[new RegExp("rv:"+Se)],[_f]:[new RegExp(Ol+"?\\/"+Se)],[Hn]:[new RegExp("("+Hn+"|CrMo)\\/"+Se)],[vf]:[new RegExp("CriOS\\/"+Se)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Se)],[er]:[jo],[Ef]:[jo],[Nl]:[new RegExp("(Opera|OPR)\\/"+Se)],[di]:[new RegExp(di+"\\/"+Se)],[wf]:[new RegExp("FxiOS\\/"+Se)],[Ca]:[new RegExp("Konqueror[:/]?"+Se,"i")],[vi]:[new RegExp(vi+" "+Se),jo],[bf]:[new RegExp("android\\s"+Se,"i")],[mf]:[new RegExp(gf+"\\/"+Se)],[If]:[new RegExp("OculusBrowser\\/"+Se)],[hs]:[new RegExp(hs+"\\/"+Se)],[kf]:[new RegExp("YaBrowser\\/"+Se)],[ps]:[new RegExp(ps+"\\/"+Se)],[tr]:[new RegExp(tr+"\\/"+Se)],[Pa]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Se)],[Cf]:[new RegExp("PaleMoon\\/"+Se)],[gs]:[new RegExp(gs+"\\/"+Se)],[Pf]:[new RegExp("GSA\\/"+Se)],[Ll]:[new RegExp("(rv:|MSIE )"+Se)],Mozilla:[new RegExp("rv:"+Se)]},Qg=function(t,e,n,i){var r=Af(t,e,n,i),s=Xg[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},su=[[new RegExp(fi+"; "+fi+" (.*?)[);]","i"),t=>[fi,t&&t[1]||""]],[new RegExp(cr,"i"),[cr,""]],[new RegExp(ur,"i"),[ur,""]],[Bl,[vi,""]],[new RegExp(qi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ia,""];if(new RegExp(lt).test(e)&&!/IEMobile\b/.test(e))return[qi+" "+lt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Zg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[qi,i]}return[qi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[fs,[t[3],t[4],t[5]||"0"].join(".")]:[fs,""]],[/(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("("+sn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+sn+")","i"),t=>t&&t[2]?[sn,[t[2],t[3],t[4]||"0"].join(".")]:[sn,""]],[/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/,[zg,""]],[/Linux|debian/i,["Linux",""]]],ou=function(t){return Jg.test(t)?cr:Yg.test(t)?ur:Kg.test(t)?fi:new RegExp(ka,"i").test(t)?ka:new RegExp("("+Ia+"|WPDesktop)","i").test(t)?Ia:/iPad/.test(t)?df:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?hf:Bl.test(t)?vi:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(ru,"i").test(t)?ru:/(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(lt).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)?sn:uf:new RegExp("(pda|"+lt+")","i").test(t)?Gg:new RegExp(mi,"i").test(t)&&!new RegExp(mi+" pc","i").test(t)?xf:""},em=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function au(t,e){return typeof(n=t)=="string"&&em.test(n)?t:e();var n}function wn(t){return t&&t.split("#")[0]}function Dl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function lu(t,e,n){return Ff.apply(this,arguments)}function Ff(){return(Ff=ce((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=Dl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var tm=t=>t instanceof Error,Rf={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}},nm=Rf.info;function Tf(t){if(wt(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=>Tf(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function ms(t){var e=[];for(var n in t){var i=t[n];Qe(i)||C(i)||e.push({key:n,value:Tf(i)})}return e}function im(t,e){var n=Rf[t.level||"info"]||nm,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),q(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),q(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:ms(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 Mf(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 $f(t,e,n,i){return{resourceLogs:[{resource:{attributes:ms(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let rm=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:im(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 ce((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return ce((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Kt.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=$f(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(Kt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return ce((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Kt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Kt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Mf(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Kt.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(Kt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Dl((()=>{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(Kt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return ce((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield lu(n,t):yield n}))()}flushWithTimeout(t){var e=this;return ce((function*(){var n=e.flush();yield lu(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 Uo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function cu(t){return String(t)+"000000"}function uu(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 sm=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=ce((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=uu(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(Uo.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,Uo)]+=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=Dl((()=>{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 ce((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:ms(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=cu(Date.now()),n=new Map;for(var i of t.values()){var r,s=uu(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=ms((r=i.attributes)!==null&&r!==void 0?r:{}),l=cu(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:Uo})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var Br,du,Ho;function om(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Ho&&n.length===du||(du=n.length,Ho=n.reduce(((i,r)=>{Br||(Br={});var s=Br[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,Br[r]=[u,c];break}}return i}),{})),Ho}}class am{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 ce((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 ce((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:om(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 yi="?";function Aa(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?yi:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Lf=(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]:yi,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},lm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,cm=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,um=/\((\S*)(?::(\d+))(?::(\d+))\)/,dm=(t,e)=>{var n=lm.exec(t);if(n)return Aa(e,n[1],yi,+n[2],+n[3]);var i=cm.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=um.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Lf(i[1]||yi,i[2]);return Aa(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},fm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,hm=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,pm=(t,e)=>{var n=fm.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=hm.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]||yi,o=Lf(s,r);return Aa(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},fu=/\(error: (.*)\)/;class gm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=Q(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 ds(e,"DOMException")}isDOMError(e){return ds(e,"DOMError")}}class mm{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 cf(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 vm{constructor(){}match(e){return!!ds(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 Q(e.message)&&e.message.length>0}pe(e){var n=e;if(Q(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 ym=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class _m{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(ym);return r&&(n=r[1],i=r[2]),[n,i]}}var wm=["fatal","error","warning","log","info","debug"];function Nf(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 bm{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 $l(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: "+Nf(e)}isSeverityLevel(e){return Q(e)&&!xa(e)&&wm.indexOf(e)>=0}getStack(e){try{return Q(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:Q(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(tm(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Em{match(e){return $l(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Nf(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Sm{match(e){return lf(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 xm{match(e){return ds(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!$l(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 lf(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 vs="$message",ys="$timestamp",Im=new Set([vs,ys]),Wo={enabled:!0,max_bytes:32768};function _s(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Wo.enabled,max_bytes:Cm(t.max_bytes,Wo.max_bytes)}:k({},Wo)}class km{constructor(e){this.Ke=[],this.Je=0,this.Ne=_s(e)}setConfig(e){this.Ne=_s(e),this.Xe()}add(e){var n=(function(r){var s;try{s=sf(r)}catch{return}try{var o=JSON.parse(s);if(!me(o))return;var a=o,l=a[vs],u=a[ys];return!Q(l)||l.trim().length===0||!Q(u)&&!Ae(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 Cm(t,e){if(!Ae(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Of=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(E&&(oe.DEBUG||E.POSTHOG_DEBUG||n)&&!C(E.console)&&E.console){for(var s=("__rrweb_original__"in E.console[r])?E.console[r].__rrweb_original__:E.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)=>Of(t+" "+r,s)};return i},A=Of("[PostHog.js]"),ve=A.createLogger,Pm=ve("[ExternalScriptsLoader]"),qo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Pm.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)};N.__PosthogExtensions__=N.__PosthogExtensions__||{},N.__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)}qo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");qo(t,o,n)}},N.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);qo(t,i,n)};oe.DEBUG=!1,oe.LIB_VERSION="1.415.7",oe.LIB_NAME="web";var Bf="$people_distinct_id",dr="$device_id",zo="$device_model",zi="__alias",Vi="__timers",Fa="$autocapture_disabled_server_side",Ra="$heatmaps_enabled_server_side",Ta="$exception_capture_enabled_server_side",Ma="$error_tracking_suppression_rules",$a="$error_tracking_capture_extension_exceptions",La="$web_vitals_enabled_server_side",jl="$dead_clicks_enabled_server_side",Ul="$product_tours_enabled_server_side",Na="$web_vitals_allowed_metrics",jn="$session_recording_remote_config",Df="$replay_sample_rate",jf="$replay_override_sampling",Uf="$replay_override_linked_flag",Hf="$replay_override_url_trigger",Wf="$replay_override_event_trigger",li="$sesid",Hl="$session_is_sampled",$n="$enabled_feature_flags",Gi="$active_feature_flags",Zr="$early_access_features",Oa="$feature_flag_details",Ki="$feature_flag_payloads",Xr="$feature_flag_request_id",ws="$minimal_flag_called_events",Pt="$override_feature_flags",Ln="$override_feature_flag_payloads",Gt="$stored_person_properties",Nn="$stored_group_properties",Ba="$surveys",bs="$surveys_loaded_at",Da="$surveys_activated",Qr="$surveys_activated_session",es="$surveys_activated_timestamps",Yi="ph_product_tours",Bn="$flag_call_reported",Ji="$flag_call_reported_session_id",ts="$feature_flag_errors",nr="$feature_flag_evaluated_at",ft="$user_state",ja="$client_session_props",Ua="$capture_rate_limit",Ha="$initial_campaign_params",Wa="$initial_referrer_info",Es="$initial_person_info",Ss="$epp",Dr="$posthog_cookieless",qf="$cookieless_mode",zf="$sdk_debug_extensions_init_method",Vf="$sdk_debug_extensions_init_time_ms",Gf="$sdk_debug_recording_script_not_loaded",Wl="PostHog loadExternalDependency extension not found.",On="on_reject",Xt="always",ei="anonymous",Pn="identified",qa="identified_only",xs="visibilitychange",Is="beforeunload",si="$pageview",Vo="$pageleave",Go="$identify",hu="$groupidentify";function jr(t,e){U(t)&&t.forEach(e)}function ae(t,e){if(!q(t))if(U(t))t.forEach(e);else if(Dg(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)af.call(t,n)&&e(t[n],n)}var ge=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 ns(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 pu=function(t){try{return t()}catch{return}},Am=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)}}},ql=function(t){var e={};return ae(t,(function(n,i){(Q(n)&&n.length>0||Ae(n))&&(e[i]=n)})),e},Fm=["herokuapp.com","vercel.app","netlify.app"];function Rm(t){var e=t?.hostname;if(!Q(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Fm)if(n===i)return!1;return!0}function we(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 za(t){return t.name==="ph_toolbar_internal"}var Kf=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 Ae(t)&&isFinite(t)&&Math.floor(t)===t});class ks{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 ks(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 ks(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 Tm{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 ks.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 Mm}}var gu,Yf=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};E&&!C(E.crypto)&&crypto.getRandomValues&&(Yf=t=>crypto.getRandomValues(t));class Mm{nextUint32(){return this.R.length>this.O||(Yf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Yt=()=>$m().toString(),$m=()=>(gu||(gu=new Tm)).generate(),$i="",Lm=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:Kf,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(h,g){if(g===void 0&&(g=F),$i)return $i;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),b="dmn_chk_"+Yt();!$i&&v--;){var w=m.slice(v).join("."),_=b+"=1;domain=."+w+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(b)&&(g.cookie=_+";max-age=0",$i=w)}return $i})(c);if(!f){var p=(h=>{var g=h.match(Lm);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}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}}},Ko=null,ue={N(){if(!Qe(Ko))return Ko;var t=!0;if(C(E))t=!1;else try{var e="__mplssupport__";ue.F(e,"xyz"),ue.P(e)!=='"xyz"'&&(t=!1),ue.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Ko=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return E?.localStorage.getItem(t)}catch(e){ue.j(e)}return null},H(t){try{return JSON.parse(ue.P(t))||{}}catch{}return null},F(t,e){try{return E?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ue.j(n)}return!1},q(t){try{E?.localStorage.removeItem(t)}catch(e){ue.j(e)}}},Nm=[dr,"distinct_id",li,Hl,Ss,Es,ft],Ur={},Om={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>Ur[t]||null,H:t=>Ur[t]||null,F:(t,e)=>(Ur[t]=e,!0),q(t){delete Ur[t]}},An=null,xe={N(){if(!Qe(An))return An;if(An=!0,C(E))An=!1;else try{var t="__support__";xe.F(t,"xyz"),xe.P(t)!=='"xyz"'&&(An=!1),xe.q(t)}catch{An=!1}return An},j(t){A.error("sessionStorage error: ",t)},P(t){try{return E?.sessionStorage.getItem(t)}catch(e){xe.j(e)}return null},H(t){try{return JSON.parse(xe.P(t))||null}catch{}return null},F(t,e){try{return E?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){xe.j(n)}return!1},q(t){try{E?.sessionStorage.removeItem(t)}catch(e){xe.j(e)}}};class Bm{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===Xt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===On}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 Do(e)?1:j(Wg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?ue:Qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Qt:ue;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Do(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[qe?.doNotTrack,qe?.msDoNotTrack,N.doNotTrack].some((e=>Do(e)))}}function Jf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Ue(i))return e;try{var r=i(e);return Q(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var Zf="__POSTHOG_TOOLBAR__",Dm=1,jm=3,Um=11;function mu(t){return t instanceof Element&&(t.id===Zf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function bn(t){return!!t&&t.nodeType===Dm}function rt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Xf(t){return!!t&&t.nodeType===jm}function Qf(t){return!!t&&t.nodeType===Um&&bn(t.host)}var eh=1e3;function zl(t){return t?Zs(t).split(/\s+/):[]}function vu(t,e){var n=(function(i){var r,s=E==null||(r=E.location)==null?void 0:r.href;return C(s)?void 0:Jf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function Cs(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return zl(e)}function th(t){return q(t)?null:Zs(t).split(/(\s+)/).filter((e=>ir(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function fr(t){var e="";return Ga(t)&&!sh(t)&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;Xf(n)&&n.textContent&&(e+=(i=th(n.textContent))!==null&&i!==void 0?i:"")})),Zs(e)}function Yo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Vl=["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 nh(t){var e=t.parentNode;return!(!e||!bn(e))&&e}var Hm=[".ph-no-autocapture","[data-ph-no-autocapture]"],ih=["next","previous","prev",">","<"],Wm=[...ih,"+","-","−","–"],yu=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,_u=[".ph-no-rageclick",".ph-no-capture"],qm=["","text","search","email","password","url","tel","number"];function wu(t,e){if(!E||Gl(t))return!1;var n,i,r,s,o;if(wt(e)?(n=!!e&&_u,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:_u,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!bn(l))&&(!!rt(l,"textarea")||(rt(l,"input")?j(qm,(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=rh(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=ih;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,p=d.ariaLabel;return c.some((h=>yu(f,h)||yu(p,h)))}))})(i,a.map((l=>{var u;return{safeText:fr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!Va(a,n)}var Gl=t=>!t||rt(t,"html")||!bn(t),rh=(t,e)=>{if(!E||Gl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!rt(r,"body");)if(Qf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=nh(r);if(!s)break;if(e||Vl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=E.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function Ga(t){for(var e=new Set,n=0,i=t;i.parentNode&&!rt(i,"body");i=i.parentNode){if(n++>=eh||e.has(i))return!1;e.add(i);var r=Cs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(Cs(t),"ph-include"))return!0;var s=t.type||"";if(Q(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!Q(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 sh(t){return!!(rt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||rt(t,"select")||rt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var bu=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}))$"),Eu=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,zm=[16,15,14,13],Vm=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Su=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),xu=/[0-9A-Za-z_]/;function Gm(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 ir(t,e){if(e===void 0&&(e=!0),q(t))return!1;if(Q(t)){t=Zs(t);var n=e?bu.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Eu.lastIndex=0;s=Eu.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of zm){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(bu.test(d)&&Gm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Vm.test(t):(function(r){var s;for(Su.lastIndex=0;s=Su.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&xu.test(o)&&xu.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Iu(t){var e=fr(t);return ir(e=(e+" "+oh(t)).trim())?e:""}function oh(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=fr(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+oh(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function ku(t){return t.replace(/"|\\"/g,'\\"')}function Km(t){var e=t.attr__class;if(e)return U(e)?e:zl(e)}var Hr=ve("[Dead Clicks]"),Ym=()=>!0,Jm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(jl)),i=t.instance.config.capture_dead_clicks;return wt(i)?i:!!me(i)||n};class Cu{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({[jl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=N.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Hr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=N.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=me(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=N.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),Hr.info("starting...")}}else Hr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Hr.info("stopping..."))}}var Jo=ve("[SegmentIntegration]"),ah="posthog-js";function lh(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,p,h,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,b=((d=c.exception)==null?void 0:d.values)||[],w=b.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=b[0])==null?void 0:f.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=b[0])==null?void 0:h.value)||c.message,$sentry_exception_type:(g=b[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 Zm{constructor(e,n,i,r,s,o){this.name=ah,this.setupOnce=function(a){a(lh(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Pu{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=E?.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?Rt(a/o,0,1,A):1,p=o>1?Rt(l/o,0,1,A):1,h=u>1?Rt(c/u,0,1,A):1,g=u>1?Rt(d/u,0,1,A):1;r=ge(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Zo=["flags","surveys"],Xm={[Bf]:{exposure:"hidden"},[zi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Vi]:{exposure:"hidden"},[Fa]:{exposure:"event"},[Ra]:{exposure:"hidden"},[Ta]:{exposure:"event"},[Ma]:{exposure:"hidden"},[$a]:{exposure:"event"},[La]:{exposure:"event"},[jl]:{exposure:"event"},[Ul]:{exposure:"hidden"},[Na]:{exposure:"event"},[jn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[li]:{exposure:"hidden"},[Hl]:{exposure:"event"},[Df]:{exposure:"event",shouldSkipFromEventProperties:t=>Qe(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"},[$n]:{exposure:"hidden",storageGroup:"flags"},[Gi]:{exposure:"hidden",storageGroup:"flags"},[Zr]:{exposure:"hidden"},[Oa]:{exposure:"hidden",storageGroup:"flags"},[Ki]:{exposure:"hidden",storageGroup:"flags"},[Xr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ws]:{exposure:"hidden",storageGroup:"flags"},[Pt]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Gt]:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[Ba]:{exposure:"hidden",storageGroup:"surveys"},[bs]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Da]:{exposure:"event"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Yi]:{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"},[Bn]:{exposure:"hidden"},[Ji]:{exposure:"hidden"},[ts]:{exposure:"hidden"},[nr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[Ua]:{exposure:"hidden"},[Ha]:{exposure:"hidden"},[Wa]:{exposure:"hidden"},[Es]:{exposure:"hidden"},[Ss]:{exposure:"hidden"},[jf]:{exposure:"event"},[Uf]:{exposure:"event"},[Hf]:{exposure:"event"},[Wf]:{exposure:"event"},[zf]:{exposure:"event"},[Vf]:{exposure:"event"},[Gf]:{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"}},Qm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Fn=t=>{var e=Xm[t];if(e)return e;for(var n of Qm){var i=n[1];if(t.indexOf(n[0])===0)return i}},ci=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return sf(t)}},Ps=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},_i=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," ")},hr=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},ch=(t,e)=>t>=e&&tf(),uh=(t,e,n,i)=>{if(t===0){if(tf()){var r=e+1;return r===n&&i(),r}return e}return 0},Wr="https?://(.*)",wi=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],ev=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...wi],pr="",tv=["li_fat_id"];function dh(t,e,n){if(!F)return{};var i,r=e?[...wi,...n||[]]:[],s=fh(hr(F.URL,r,pr),t),o=(i={},ae(tv,(function(a){var l=Kf(a);i[a]=l||null})),i);return ge(o,s)}function fh(t,e){var n=ev.concat(e||[]),i={};return ae(n,(function(r){var s=_i(t,r);i[r]=s||null})),i}function hh(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(!Qe(e)){i.$search_engine=e;var r=F?_i(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Au(){return navigator.language||navigator.userLanguage}var Fs="$direct";function ph(){return F?.referrer||Fs}function gh(t,e,n){n===void 0&&(n=!1);var i=t?[...wi,...e||[]]:[],r=n?wn(_e?.href):_e?.href,s=r?.substring(0,1e3);return{r:ph().substring(0,1e3),u:s?hr(s,i,pr):void 0}}function mh(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?wn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==Fs?Fs:(n=Ps(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=Ps(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=fh(s);ge(o,l)}if(i){var u=hh(i);ge(o,u)}return o}function vh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function nv(){try{return new Date().getTimezoneOffset()}catch{return}}var iv={flags:nr,surveys:bs},rv=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ti="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(),E){var r=()=>this.flush();we(E,"beforeunload",r,{capture:!1}),we(E,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Ae(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){rv.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=[...Nm,...o];return k({},ue,{H(u){try{var c={};try{c=Qt.H(u)||{}}catch{}var d,f=JSON.parse(ue.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];Qe(g)||g===""||(p[h]=g)}d=ge(f,p)}else d=ge(c,f);return ue.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=ue.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Qt.F(u,m,d,f,p,h)}catch(v){ue.j(v)}return g},q(u,c){try{E?.localStorage.removeItem(u),Qt.q(u,c)}catch(d){ue.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&ue.N()?(n=ue,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&xe.N()?n=xe:s==="memory"?n=Om: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 ae(this.props,((n,i)=>{var r=Fn(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=ge({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Zo){var n=ue.H(this.Si(e));if(n&&!rn(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ge(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Fn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=iv[e];if(!i)return!1;var r=n[i],s=this.props[i];return Ae(r)&&Ae(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Fn(e))==null?void 0:n.storageGroup:void 0,r=i?ue.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,ti))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,ti),Zo)){var s,o=i[r];(!rn(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(ue,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ae(this.props,((i,r)=>{var s,o=(s=Fn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===ti)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ae(e,((r,s)=>{var o;i[s]=(o=Fn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===ti||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!==ti&&(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 Zo)ue.q(this.Si(r));i?delete this.ci[ti]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(me(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ae(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(me(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ae(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||me(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=dh(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);rn(ql(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?hh(e):{})}update_referrer_info(){var e;this.register_once({$referrer:ph(),$referring_domain:F!=null&&F.referrer&&((e=Ps(F.referrer))==null?void 0:e.host)||Fs},void 0)}set_initial_person_info(){this.props[Ha]||this.props[Wa]||this.register_once({[Es]:gh(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={};ae([Wa,Ha],(r=>{var s=this.props[r];s&&ae(s,(function(o,a){e["$initial_"+Sa(a)]=o}))}));var n=this.props[Es];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=mh(r,s),a={};return ae(o,(function(l,u){a["$initial_"+Sa(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ge(e,i)}return e}safe_merge(e){return ae(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,p)=>f===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[Vi]||{};i[e]=n,this.Pi(Vi,i),this.save()}remove_event_timer(e){var n=this.props[Vi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(Vi,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=Fn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Fn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function qr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Ue(n.then)&&n.then(void 0,(()=>{}))}}}}var He={GZipJS:"gzip-js",Base64:"base64"},Li={Activation:"events",Cancellation:"cancelEvents"},Qo={Popover:"popover",API:"api",Widget:"widget"},en={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ea={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},Ka={Popover:"popover",Inline:"inline"},sv={SHOWN:"product tour shown"},Fu={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Ru=ve("[RateLimiter]");class ov{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=>{Ru.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Ru.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(Ua))!==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=(Ae(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(Ua,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")&&_e!=null&&_e.pathname)return""+((e=_e.origin)!==null&&e!==void 0?e:"")+_e.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 mn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void mn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return mn.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){mn.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||mn.warn("Failed to fetch remote config from PostHog."):mn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){mn.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){mn.error("Error loading feature flags",r)}}}var pt=Uint8Array,Xe=Uint16Array,bi=Uint32Array,Kl=new pt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Yl=new pt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Tu=new pt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_h=function(t,e){for(var n=new Xe(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]},wh=_h(Kl,2),Ya=wh[1];wh[0][28]=258,Ya[258]=28;for(var Mu=_h(Yl,0)[1],bh=new Xe(32768),be=0;32768>be;++be){var ni=(43690&be)>>>1|(21845&be)<<1;bh[be]=((65280&(ni=(61680&(ni=(52428&ni)>>>2|(13107&ni)<<2))>>>4|(3855&ni)<<4))>>>8|(255&ni)<<8)>>>1}var rr=function(t,e,n){for(var i=t.length,r=0,s=new Xe(e);i>r;++r)++s[t[r]-1];var o,a=new Xe(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Xe(i),r=0;i>r;++r)o[r]=bh[a[t[r]-1]++]>>>15-t[r];return o},Vn=new pt(288);for(be=0;144>be;++be)Vn[be]=8;for(be=144;256>be;++be)Vn[be]=9;for(be=256;280>be;++be)Vn[be]=7;for(be=280;288>be;++be)Vn[be]=8;var Rs=new pt(32);for(be=0;32>be;++be)Rs[be]=5;var av=rr(Vn,9),lv=rr(Rs,5),Eh=function(t){return(t/8>>0)+(7&t&&1)},Sh=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Xe?Xe:t instanceof bi?bi:pt)(n-e);return i.set(t.subarray(e,n)),i},qt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Ni=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},ta=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 pt(0),0];if(r==1){var o=new pt(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 p=new Xe(f+1),h=Ja(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var b=s[i].s;if(e>=p[b])break;g+=v-(1<>>=m;g>0;){var w=s[i].s;e>p[w]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new pt(p),h]},Ja=function(t,e,n){return t.s==-1?Math.max(Ja(t.l,e,n+1),Ja(t.r,e,n+1)):e[t.s]=n},$u=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Xe(++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]},Oi=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Za=function(t,e,n){var i=n.length,r=Eh(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)},Lu=function(t,e,n,i,r,s,o,a,l,u,c){qt(e,c++,n),++r[256];for(var d=ta(r,15),f=d[0],p=d[1],h=ta(s,15),g=h[0],m=h[1],v=$u(f),b=v[0],w=v[1],_=$u(g),x=_[0],I=_[1],T=new Xe(19),S=0;b.length>S;++S)T[31&b[S]]++;for(S=0;x.length>S;++S)T[31&x[S]]++;for(var P=ta(T,7),R=P[0],L=P[1],$=19;$>4&&!R[Tu[$-1]];--$);var O,J,G,M,K=u+5<<3,ie=Oi(r,Vn)+Oi(s,Rs)+o,B=Oi(r,f)+Oi(s,g)+o+14+3*$+Oi(T,R)+(2*T[16]+3*T[17]+7*T[18]);if(ie>=K&&B>=K)return Za(e,c,t.subarray(l,l+u));if(qt(e,c,1+(ie>B)),c+=2,ie>B){O=rr(f,p),J=f,G=rr(g,m),M=g;var X=rr(R,L);for(qt(e,c,w-257),qt(e,c+5,I-1),qt(e,c+10,$-4),c+=14,S=0;$>S;++S)qt(e,c+3*S,R[Tu[S]]);c+=3*$;for(var fe=[b,x],se=0;2>se;++se){var ee=fe[se];for(S=0;ee.length>S;++S)qt(e,c,X[Pe=31&ee[S]]),c+=R[Pe],Pe>15&&(qt(e,c,ee[S]>>>5&127),c+=ee[S]>>>12)}}else O=av,J=Vn,G=lv,M=Rs;for(S=0;a>S;++S)if(i[S]>255){var Pe;Ni(e,c,O[257+(Pe=i[S]>>>18&31)]),c+=J[Pe+257],Pe>7&&(qt(e,c,i[S]>>>23&31),c+=Kl[Pe]);var ke=31&i[S];Ni(e,c,G[ke]),c+=M[ke],ke>3&&(Ni(e,c,i[S]>>>5&8191),c+=Yl[ke])}else Ni(e,c,O[i[S]]),c+=J[i[S]];return Ni(e,c,O[256]),c+J[256]},cv=new bi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),uv=(function(){for(var t=new bi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),na=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function dv(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=uv[255&p^f[h]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,p,h,g,m){var v=d.length,b=new pt(h+v+5*(1+Math.floor(v/7e3))+g),w=b.subarray(h,b.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=Za(w,_,d.subarray(x,I)):(w[x]=!0,_=Za(w,_,d.subarray(x,v)))}else{for(var T=cv[f-1],S=T>>>13,P=8191&T,R=(1<x;++x){var Pe=G(x),ke=32767&x,je=$[Pe];if(L[ke]=je,$[Pe]=ke,x>=se){var St=v-x;if((B>7e3||fe>24576)&&St>423){_=Lu(d,w,0,M,K,ie,X,fe,ee,x-ee,_),fe=B=X=0,ee=x;for(var ye=0;286>ye;++ye)K[ye]=0;for(ye=0;30>ye;++ye)ie[ye]=0}var et=2,xt=0,Cn=P,Le=ke-je&32767;if(St>2&&Pe==G(x-Le))for(var Re=Math.min(S,St)-1,Dt=Math.min(32767,x),Zn=Math.min(258,St);Dt>=Le&&--Cn&&ke!=je;){if(d[x+et]==d[x+et-Le]){for(var Ke=0;Zn>Ke&&d[x+Ke]==d[x+Ke-Le];++Ke);if(Ke>et){if(et=Ke,xt=Le,Ke>Re)break;var Xn=Math.min(Le,Ke-2),jt=0;for(ye=0;Xn>ye;++ye){var Ut=x-Le+ye+32768&32767,ut=Ut-L[Ut]+32768&32767;ut>jt&&(jt=ut,je=Ut)}}}Le+=(ke=je)-(je=L[ke])+32768&32767}if(xt){M[fe++]=268435456|Ya[et]<<18|Mu[xt];var Ht=31&Ya[et],Fi=31&Mu[xt];X+=Kl[Ht]+Yl[Fi],++K[257+Ht],++ie[Fi],se=x+et,++B}else M[fe++]=d[x],++K[d[x]]}}_=Lu(d,w,!0,M,K,ie,X,fe,ee,x-ee,_)}return Sh(b,0,h+Eh(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var p=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&na(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),na(u,c-8,n.d()),na(u,c-4,i),u}var fv=!!wa||!!Ml,xh="text/plain",is=!1,Ih=(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:"")},Qs=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("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return ae(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},ia=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===He.GZipJS){var i=dv((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new pt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new pt(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Sh(c,0,d)})(ci(e)),{mtime:0});return{contentType:xh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===He.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(ci(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:ci(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=ci(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},kh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Qs(t.url,{compression:He.Base64}),encodedBody:ia(k({},t,{compression:He.Base64,Ji:void 0}))}:{url:Ih(t.url,"compression"),encodedBody:ia(k({},t,{compression:void 0,Ji:void 0}))};try{e=ia(t)}catch(r){if(tu(t.compression,_i(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&tu(t.compression,_i(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?ba(new Uint8Array(n)):ArrayBuffer.isView(n)&&ba(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(is=!0,i()):{url:t.url,encodedBody:e}},Ch=t=>{try{return kh(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},hv=(function(){var t=ce((function*(e){var n=ci(e.data),i=yield(function(s,o,a){return Ea.apply(this,arguments)})(n,oe.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:xh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),pv=/Failed to fetch|NetworkError|Load failed/i,Ph=t=>t?.name==="TypeError"&&pv.test(t?.message||""),Ah=t=>{var e=Ch(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ae(t.headers,(function(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Yc){var d=new Yc;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||Ph(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;Ml(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(h){u&&clearTimeout(u.timeout),f(h)}}},Xa=t=>{try{var e,n=kh(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(qe.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 Xa(k({},t,{data:d(u.slice(0,c))})),void Xa(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Ah(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Nu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Qs(n===He.GZipJS?Ih(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===He.GZipJS?{}:{compression:n}))},rs=[];Ml&&rs.push({transport:"fetch",method:Ah}),wa&&rs.push({transport:"XHR",method(t){var e=Ch(t);if(e){var n=new wa,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ae(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)}}}),qe!=null&&qe.sendBeacon&&rs.push({transport:"sendBeacon",method:Xa});var Qa=3e3;class gv{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Rt(n?.flush_interval_ms||Qa,250,5e3,A.createLogger("flush interval"),Qa),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)&&ae(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 ae(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 mv=["retriesPerformedSoFar"];class vv{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(E)&&"onLine"in E.navigator&&(this.dr=E.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},we(E,"online",this.vr),we(E,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=nf(e,mv);Vt(n)&&(i.url=Qs(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(E)||(this.vr&&(E.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(E.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 yv{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(){we(E,"scroll",this.yr,{capture:!0}),we(E,"scrollend",this.yr,{capture:!0}),we(E,"resize",this.yr)}scrollElement(){if(!this._r)return E?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=E?.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 E?e==="y"?E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop||0:E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var _v=t=>gh(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Ou{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ja]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||_v,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ja]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?mh(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 ae(ql(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Sa(i)]=n})),e}}class Jl{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 Bi=ve("[SessionId]");class Bu{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 Jl,this.Lr=(u,c)=>!(!Vt(u)||!Vt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Xt)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||Yt,this.Nr=i||Yt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Bi.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=xe.H(this.jr),a=xe.H(this.Br);o&&!a?this.Or=o:xe.q(this.jr),xe.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){Bi.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&&xe.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&xe.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?xe.H(this.jr):null}Zr(e){var n=this.Pr;return!Qe(n)&&!Qe(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({[li]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Vt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(li):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Qe(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({[li]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Vt(e)?e:0,i=Vt(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[li];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&&E&&(E.removeEventListener(Is,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&xe.q(this.Br)},we(E,Is,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Xt)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=Vt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||Bi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),Bi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Bi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Vt(a)&&e&&!u?a:i,v=Vt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var b={noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(s,l,b))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Fh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&iu(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>iu(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Rh(){return(Rh=ce((function*(){var t=qe?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return Q(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 Ts=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 ra(t,e,n){return ci({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Th={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=>Ts(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Ts(n,i))))),icontains:(t,e)=>e.map(zr).some((n=>t.map(zr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(zr).every((n=>t.map(zr).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 Mh(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Qe(r))return!1;var s=[String(r)],o=Th[i.operator];return!!o&&o(i.values,s)}))}var el="custom",Du="i.posthog.com",wv=/^\/static\//;class bv{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("."+Du,".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":el),this.en[this.apiHost]}rn(e){if(wv.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===el)return this.apiHost+n;var r=Du+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function $h(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var te=ve("[Surveys]"),Lh="seenSurvey_",Nh=t=>{try{var e=(n=>((i,r)=>""+Lh+(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){te.error("Failed to persist survey seen state",n)}},Ev=[Qo.Popover,Qo.Widget,Qo.API],Sv={ignoreConditions:!1,ignoreDelay:!1,displayType:Ka.Popover},xv=ve("[PostHog ExternalIntegrations]"),Iv={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class kv{constructor(e){this._instance=e}ai(e,n){var i;(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return xv.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=N.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Iv[l],(()=>{var c;(c=N.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=N.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=N.__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 Cv{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return ce((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&&Ue(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 Pv{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 ju="extensionsRemoteConfig";class Av{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Pv(e),this.onEvent=n=>qr(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 qr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(ju,i);return this.un&&i(this.un),qr(r)},this.vn=new Cv(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(dr))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(dr);return typeof e=="string"?e:void 0}get library(){return{name:oe.LIB_NAME,version:oe.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 ce((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 qr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(ju,e))}sendRequest(e,n){var i=this;return ce((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?Qs(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 sr={},sa=0,Ms=()=>{},Uu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Di="Surveys module not available",Hu="sanitize_properties is deprecated. Use before_send instead",Oh="Invalid value for property_denylist config: ",Fv=["token","distinct_id",qf],oi="posthog",Bh=!fv&&Je?.indexOf("MSIE")===-1&&Je?.indexOf("Mozilla")===-1,oa=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:Rm(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Ms,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:_e&&Q(_e?.search)&&_e.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:(E==null||(e=E.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:qa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Qa},error_tracking:{},_onCapture:Ms},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Wm,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))},Rv=[["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"]],Wu=t=>{var e={};for(var n of Rv){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=ge({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),Q(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(Oh+t.property_denylist)),s};class Tv{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 tt{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===Xt||this.config.cookieless_mode===On&&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 Tv,this.mn=!1,this.version=oe.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Jl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=oa(),this.SentryIntegration=Zm,this.sentryIntegration=i=>(function(r,s){var o=lh(r,s);return{name:ah,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 yv(this),this.pageViewManager=new Pu(this),this.rateLimiter=new ov(this),this.requestRouter=new bv(this),this.consent=new Bm(this),this.externalIntegrations=new kv(this);var n=(e=tt.__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=Q(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=Q(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!==oi){var r,s=(r=sr[i])!==null&&r!==void 0?r:new tt;return s._init(e,n,i),sr[i]=s,sr[oi][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=Q(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=oa(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=oa(n.defaults),u=Wu(n),c=ge({},l,u,{name:i,token:a});me(l.rageclick)&&me(u.rageclick)&&(c.rageclick=ge({},l.rageclick,u.rageclick)),me(l.session_recording)&&me(u.session_recording)&&(c.session_recording=ge({},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:He.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&&xe.N()){var f=xe.H(this.bn);U(f)&&f.forEach((I=>{Q(I)&&this.yn.add(I)}))}else xe.q(this.bn);var p=k({},this.persistence.props),h=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new gv((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new vv(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Bu(this),this.sessionPropsManager=new Ou(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.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)),oe.DEBUG=oe.DEBUG||this.config.debug,oe.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p,s:h}),!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(),b=this.persistence.get_property(ft);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===ei)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Pn)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 w=this.config.get_device_id(Yt()),_=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(ft,n.bootstrap.isIdentifiedID?Pn:ei),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Dr,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Yt());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ft,ei)}return we(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var S=I.config.segment;if(!S)return T();(function(P,R){var L=P.config.segment;if(!L)return R();var $=J=>{var G=()=>J.anonymousId()||Yt();P.config.get_device_id=G,J.id()&&(P.register({distinct_id:J.id(),$device_id:G()}),P.persistence.set_property(ft,Pn)),R()},O=L.user();"then"in O&&Ue(O.then)?O.then($):$(O)})(I,(()=>{S.register((P=>{typeof Promise<"u"&&Promise.resolve||Jo.warn("This browser does not have Promise support, and can not use the segment integration");var R=(L,$)=>{if(!$)return L;L.event.userId||L.event.anonymousId===P.get_distinct_id()||(Jo.info("No userId set, resetting PostHog"),P.reset()),L.event.userId&&L.event.userId!==P.get_distinct_id()&&(Jo.info("UserId set, identifying with PostHog"),P.identify(L.event.userId));var O=P.calculateEventProperties($,L.event.properties);return L.event.properties=Object.assign({},O,L.event.properties),L};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:L=>R(L,L.event.event),page:L=>R(L,si),identify:L=>R(L,Go),screen:L=>R(L,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),Ue(this.config._onCapture)&&this.config._onCapture!==Ms&&(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 Rh.apply(this,arguments)})().then((I=>{I&&this.register({[zo]:I})})).catch(Ms),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=tt.__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)),Ue(this.featureFlags.onReloading)&&Ue(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({},tt.__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,Jm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[zf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Vf]: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,He.GZipJS)?He.GZipJS:j(r.supportedCompression,He.Base64)?He.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:qa}),(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&&_e!=null&&_e.hostname){var e=_e.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 yh(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()&&jr(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(Vo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(Vo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Bh?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=He.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((b=>k({},b,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Nu(o.url,o.method,o.compression,o.timestampMode);var p=rs.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var b=0;m.length>b;b++)if(m[b].transport===f)return m[b]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){Ph(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===He.GZipJS&&Mg&&typeof Promise<"u"&&!is?hv(o).then((m=>{g(m)})).catch((m=>{if(nu(m))return is=!0,void g(k({},o,{compression:void 0,url:Nu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var b="name"in v?String(v.name):"";return nu(v)||b===rf})(m)&&(is=!0),g(o)})):h(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){sa++;try{var n,i=[],r=[],s=[];jr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(Ue(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&&Ue(this[n])?s.push(a):r.push(a)}));var o=function(a,l){jr(a,(function(u){try{if(U(u[0])){var c=l;ae(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{sa--}}push(e){if(sa>0&&U(e)&&Q(e[0])){var n=tt.prototype[e[0]];Ue(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)&&Q(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&&!Q(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,p=au(i?.uuid,Yt),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===si&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(ws)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,b,w,_=g?void 0:this.Vn(i?.$set_once,e!==hu,e===Go);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=$=>Q($)?$.slice(0,s):$,l=new Set,h=(function $(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var G;if(l.add(O),U(O))G=[],jr(O,(K=>{G.push($(K))}));else{var M={};ae(O,((K,ie)=>{l.has(K)||(M[ie]=$(K))})),G=M}return G}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function($,O){O===void 0&&(O=[]);var J={},G=M=>{$[M]!==void 0&&(J[M]=$[M])};return $g.forEach(G),O.forEach(G),J})(h.properties,Fv)),e===en.DISMISSED||e===en.SENT){var x=n?.[ea.SURVEY_ID],I=n?.[ea.SURVEY_ITERATION];Nh({id:x,current_iteration:I}),h.$set=k({},h.$set,{[(v={id:x,current_iteration:I},b=e===en.SENT?"responded":"dismissed",w="$survey_"+b+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+b+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===en.SHOWN&&(h.$set=k({},h.$set,{[ea.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===sv.SHOWN){var T=n?.[Fu.TOUR_TYPE];T&&(h.$set=k({},h.$set,{[Fu.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var S=k({},h.properties.$set,h.$set);if(rn(S)||this.setPersonPropertiesForFlags(S),!q(this.config.before_send)){var P=this.Pt(h);if(!P)return;(h=P).uuid=au(h.uuid,Yt)}this.dn.emit("eventCaptured",h);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),L={method:"POST",url:R,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"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(L):this.In.enqueue(L),h}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Av(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[qf]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!Q(a.distinct_id)&&!Ae(a.distinct_id)||xa(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,S){var P,R,L,$;if(S===void 0&&(S=!1),!Je)return{};var O,J=x?[...wi,...I||[]]:[],G=(function(Zn){for(var Ke=0;su.length>Ke;Ke++){var Xn=su[Ke],jt=Xn[1],Ut=Xn[0].exec(Zn),ut=Ut&&(Ue(jt)?jt(Ut,Zn):jt);if(ut)return ut}return["",""]})(Je),M=G[0],K=G[1],ie=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},B={};C(T)||(B.detectGoogleSearchApp=T);var X={},fe=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,se=(R=navigator)==null?void 0:R.maxTouchPoints,ee=E==null||(L=E.screen)==null?void 0:L.width,Pe=E==null||($=E.screen)==null?void 0:$.height,ke=E?.devicePixelRatio;C(fe)||(X.userAgentDataPlatform=fe),C(se)||(X.maxTouchPoints=se),C(ee)||(X.screenWidth=ee),C(Pe)||(X.screenHeight=Pe),C(ke)||(X.devicePixelRatio=ke);var je,St,ye,et,xt,Cn,Le,Re,Dt=ge(ql({$os:M,$os_version:K,$browser:Af(Je,navigator.vendor,ie,B),$device:ou(Je),$device_type:(St=Je,ye=X,Re=ou(St),Re===df||Re===uf||Re==="Kobo"||Re==="Kindle Fire"||Re===xf?mi:Re===cr||Re===fi||Re===ur||Re===ka?"Console":Re===hf?"Wearable":Re?lt:ye?.userAgentDataPlatform==="Android"&&((et=ye?.maxTouchPoints)!==null&&et!==void 0?et:0)>0?600>Math.min((xt=ye?.screenWidth)!==null&&xt!==void 0?xt:0,(Cn=ye?.screenHeight)!==null&&Cn!==void 0?Cn:0)/((Le=ye?.devicePixelRatio)!==null&&Le!==void 0?Le:1)?lt:mi:"Desktop"),$timezone:vh(),$timezone_offset:nv()}),{$current_url:hr(S?wn(_e?.href):_e?.href,J,pr),$host:_e?.host,$pathname:_e?.pathname,$raw_user_agent:Je.length>1e3?Je.substring(0,997)+"...":Je,$browser_version:Qg(Je,navigator.vendor,ie,B),$browser_language:Au(),$browser_language_prefix:(je=Au(),typeof je=="string"?je.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:oe.LIB_NAME,$lib_version:oe.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return oe.SDK_DIST_CHANNEL&&(Dt.$sdk_dist_channel=oe.SDK_DIST_CHANNEL),Dt})(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&&ge(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ge(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===el&&(a.$lib_custom_api_host=this.config.api_host),u=e!==si||s?e!==Vo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=ge(a,u),e===si&&F&&(a.title=F.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}Je&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ae(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var b of this._n.slice())try{ge(v,b())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=ge({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ae(this.config.property_denylist,(function(x){delete a[x]})):A.error(Oh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(A.error(Hu),a=w(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=ge({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(Hu),a=l(a,"$set_once")),n&&(this.mn=!0),rn(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||!xe.N())xe.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?xe.F(this.bn,n):xe.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:Di}),()=>{})}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:Di})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Di})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Sv),(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:Di}}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:Di})}Jn(e){return!e||xa(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Dr?(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(Ae(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(dr)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(zi)&&(this.unregister(zi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ft)||ei)===ei,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ft,Pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Go,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=ra(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ft,Pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=ra(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Bn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=ra(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=>Q(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(hu,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var p,h=this.get_property(dr),g=this.get_property(zo),m=this.get_property(jn),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(p=this.persistence)==null||p.register({[jn]: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(ft,ei),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Xt)this.register_once({distinct_id:Dr,$device_id:null},"");else{var b=this.config.get_device_id(Yt());this.register_once({distinct_id:b,$device_id:e?b:h},""),e||C(g)||this.register({[zo]: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 ce((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(Bf)?(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(zi,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(me(e)){var i,r,s,o,a,l,u,c,d,f,p,h;ge(this.config,Wu(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);wt(m)&&(this.config.debug=m),wt(this.config.debug)&&(this.config.debug?(oe.DEBUG=!0,ue.N()&&ue.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(oe.DEBUG=!1,ue.N()&&ue.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){oe.LIB_NAME=e,oe.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:tt.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:oi;return n!==oi&&(n=oi+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ft))===Pn||((n=this.sessionPersistence)==null?void 0:n.get_property(ft))===Pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===qa&&!this._isIdentified()&&rn(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[zi])&&((n=this.persistence)==null||(n=n.props)==null||!n[Ss]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(Ss,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==On)}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!==Xt){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 Bu(this),this.pageViewManager=new Pu(this),this.persistence&&(this.sessionPropsManager=new Ou(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=tt.__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==On&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(Uu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Xt?(this.config.cookieless_mode===On&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===On&&(this.register({distinct_id:Dr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(Uu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Xt||(this.config.cookieless_mode===On?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return qe?Fh(qe,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(si,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(xs,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),we(F,xs,this.kn)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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&&!q(n[i]),l=r in n&&!q(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(q(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Ug),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),q(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return jg(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!rn(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&&q(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=wt(e)&&!e,i=ue.N()&&ue.P("ph_debug")==="true";return!n&&(!!i||e)}}tt.__defaultExtensionClasses={},tt.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]]=Am(t.prototype[e[n]])})(tt,["identify"]);class qu{constructor(e){this.disabled=e===!1;var n=me(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 aa="$copy_autocapture",la=ve("[AutoCapture]");function ca(t,e){return e.length>t?e.slice(0,t)+"...":e}function Mv(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!bn(e));return e}function $v(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!bn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!rt(f,"body")&&eh>c.length;)if(Qf(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!bn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},b=!1,w=!1;if(ae(c,(S=>{var P=Ga(S);if(rt(S,"a")){var R=S.getAttribute("href");b=!!(P&&R&&ir(R))&&(u?wn(R):R)}j(Cs(S),"ph-no-capture")&&(w=!0),m.push((function($,O,J,G,M){M===void 0&&(M=!1);var K=$.tagName.toLowerCase(),ie={tag_name:K};Vl.indexOf(K)>-1&&!J&&(ie.$el_text=K.toLowerCase()==="a"||K.toLowerCase()==="button"?ca(1024,Iu($)):ca(1024,fr($)));var B=Cs($);B.length>0&&(ie.classes=B.filter((function(ee){return ee!==""}))),ae($.attributes,(function(ee){var Pe;if((!sh($)||["name","id","class","aria-label"].indexOf(ee.name)!==-1)&&(G==null||!G.includes(ee.name))&&!O&&ir(ee.value)&&(!Q(Pe=ee.name)||Pe.substring(0,10)!=="_ngcontent"&&Pe.substring(0,7)!=="_nghost")){var ke=ee.value;ee.name==="class"&&(ke=zl(ke).join(" ")),ie["attr__"+ee.name]=ca(1024,ee.name==="href"&&M?wn(ke):ke)}}));for(var X=1,fe=1,se=$;se=Mv(se);)X++,se.tagName===$.tagName&&fe++;return ie.nth_child=X,ie.nth_of_type=fe,ie})(S,s,o,a,u));var L=(function($){if(!Ga($))return{};var O={};return ae($.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var G=J.name.replace("data-ph-capture-attribute-",""),M=J.value;G&&M&&ir(M)&&(O[G]=M)}})),O})(S);ge(v,L)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=rt(t,"a")||rt(t,"button")?Iu(t):fr(t)),b){var _,x;m[0].attr__href=b;var I=(_=Ps(b))==null?void 0:_.host,T=E==null||(x=E.location)==null?void 0:x.host;I&&T&&I!==T&&(h=b)}return{props:ge({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((P=>{var R,L,$="";if(P.tag_name&&($+=P.tag_name),P.attr_class)for(var O of(P.attr_class.sort(),P.attr_class))$+="."+O.replace(/"/g,"");var J=k({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(L=P.nth_of_type)!==null&&L!==void 0?L:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),G={};return ns(J).sort(((M,K)=>M[0].localeCompare(K[0]))).forEach((M=>{var K=M[1];return G[ku(M[0].toString())]=ku(K.toString())})),($+=":")+ns(G).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(S){return S.map((P=>{var R,L,$={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(L=P.attr__href)==null?void 0:L.slice(0,2048),attr_class:Km(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return ns(P).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>$.attributes[O[0]]=O[1])),$}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var ji=ve("[ExceptionAutocapture]"),zu=()=>{},Lv=ve("[TracingHeaders]"),Rn=ve("[Web Vitals]"),Vu=9e5,Gu="disabled",Ku="lazy_loading",Ui="awaiting_config",Vr="missing_config";ve("[SessionRecording]"),ve("[SessionRecording]");var tl="[SessionRecording]",zt=ve(tl),Nv=ve("[Heatmaps]");function ua(t){return me(t)&&"clientX"in t&&"clientY"in t&&Ae(t.clientX)&&Ae(t.clientY)}var Gr=ve("[Product Tours]"),da=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Ul))},Ov=["$set_once","$set"],It=ve("[SiteApps]"),Yu="Error while initializing PostHog app with config id ";function ii(t,e,n){if(q(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 Bv{constructor(e){this.ns=new Jl,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"||!ii(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=>ii(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&ii((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=>ii(u.text,n.text,n.text_matching||"exact")||ii(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;!q(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=>ii(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||Mh(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 Dv{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&&Mh(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===Li.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 Bv(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,Li.Activation),this.ks=this.Ps(e,Li.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,Li.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,Li.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&&(rn(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Ae(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=>Ae(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 jv extends Dv{constructor(e){super(e)}Js(){return Da}Ys(){return Qr}Ms(){return es}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[es]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(es)}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 Ae(r)&&r>0}ra(){return en.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 te}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({[Qr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Qr)}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 $h(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===en.SHOWN?"consume":"ignore":e===en.SHOWN?"persist":e===en.DISMISSED||e===en.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Kr="SDK is not enabled or survey functionality is not yet loaded",Ju="Disabled. Not loading surveys.",Uv=E!=null&&E.location?As(E.location.hash,"__posthog")||As(location.hash,"state"):null,Zu="_postHogToolbarParams",Xu=ve("[Toolbar]"),Qu=ve("[FeatureFlags]");class Hv{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||(Qu.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)||Qu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var ed=ve("[FeatureFlags]"),Tn=ve("[FeatureFlags]",{debugEnabled:!0}),fa=`" failed. Feature flags didn't load in time.`,td="connection_error",nd=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},id=t=>{var e={};for(var n of ns(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},kt=ve("[Error tracking]"),rd="Refusing to render web experiment since the viewer is a likely bot",Wv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Ts(e,t),not_regex:(t,e)=>!Ts(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Oe{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Oe.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Oe.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);Q(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];Oe.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())Oe.aa(rd);else if(!this.Ne.disable_web_experiments){if(q(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Oe.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=Oe.getWindowLocation();if(e!=null&&e.search){var n=_i(e?.search,"__experiment_id"),i=_i(e?.search,"__experiment_variant");n&&i&&(Oe.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&&(Oe.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!q(e.conditions)&&Oe.da(e,n)&&Oe.va(e)}static da(e,n){var i;if(q(e.conditions)||q((i=e.conditions)==null?void 0:i.url))return!0;var r=Oe.getWindowLocation();if(r){var s,o,a,l=Jf(n,r.href);return(s=e.conditions)==null||!s.url||Wv[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return E?.location}static va(e){var n;if(q(e.conditions)||q((n=e.conditions)==null?void 0:n.utm))return!0;var i=dh();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,h=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&h&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Oe.aa(rd):n!=="control"?i.forEach((r=>{if(r.selector){var s;Oe.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)}))}})):Oe.aa("Control variants leave the page unmodified.")}_is_bot(){return qe&&this._instance?Fh(qe,this.Ne.custom_blocked_useragents):void 0}}var dt=ve("[Conversations]"),Mn="Conversations not available yet.",sd="console",Dh="__posthogHandledLogsRequestError",ha=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Dh]=!0,n},od=t=>!!t&&typeof t=="object"&&t[Dh]===!0,eo={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=ed,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 Hv(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 E&&we(E,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){E?.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=[],E?.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[Gi,Ki,Xr,Pt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa($n);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(nr);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($n))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Ki))!==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:Xc(f),variant:Qc(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(Oa),e=this.Oa(Pt),n=this.Oa(Ln);if(!n&&!e)return t||{};var i=ge({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],p=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Xc(i),variant:Qc(i),payload:Zc(e[n])}}))}getFlagVariants(){var t=this.Oa($n),e=this.Oa(Pt);if(!e)return t||{};for(var n=ge({},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(Ki),e=this.Oa(Ln);if(!e)return t||{};for(var n=ge({},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(Bn)}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(Gt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Nn),timezone:vh()};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({[ts]:[td]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?He.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?td:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[ts]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(p,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return ch(this.Sa,3)}Ua(t){this.Sa=uh(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+fa)}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(Xr)||void 0,u=this.Oa(nr)||void 0,c=this.Oa(Bn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Ji);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Bn]:c,[Ji]:n});else{var h,g,m,v,b,w,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Bn]:c},n?{[Ji]:n}:{}));var S=this.getFeatureFlagDetails(t),P=[...(h=this.Oa(ts))!==null&&h!==void 0?h:[]];C(s)&&P.push("flag_missing");var R={$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(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),C(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var L,$=(w=S==null||(_=S.reason)==null?void 0:_.description)!==null&&w!==void 0?w:S==null||(x=S.reason)==null?void 0:x.code;$&&(R.$feature_flag_reason=$),S!=null&&(I=S.metadata)!=null&&I.id&&(R.$feature_flag_id=S.metadata.id),C(S?.original_variant)&&C(S?.original_enabled)||(R.$feature_flag_original_response=C(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(T=S.metadata)!=null&&T.original_payload&&(R.$feature_flag_original_payload=S==null||(L=S.metadata)==null?void 0:L.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[Bn]:c,[Ji]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Zc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+fa)}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 ce((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"?He.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+fa),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=ed);var c=((I,T)=>{var S=I.flags;return S?k({},I,{featureFlags:Object.fromEntries(Object.keys(S).map((P=>{var R;return[P,(R=S[P].variant)!==null&&R!==void 0?R:S[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((P=>S[P].enabled)).filter((P=>{var R;return(R=S[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=S[P].metadata)==null?void 0:R.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,p=c.featureFlagPayloads;if(f){var h=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Gi]:f,[$n]:m,[ws]:!1}}var b=f,w=p,_=d;if(l!=null&&l.partialResponse)b=k({},s,b),w=k({},o,w),_=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)})));b=k({},s,Object.fromEntries(Object.entries(b).filter((I=>x.has(I[0]))))),w=k({},o,Object.fromEntries(Object.entries(w||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else b=k({},s,b),w=k({},o,w),_=k({},a,_);return k({[Gi]:Object.keys(id(b)),[$n]:b||{},[Ki]:w||{},[Oa]:_||{},[ws]:r.minimalFlagCalledEvents===!0},h?{[Xr]:h}:{},g?{[nr]: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([Pt,Ln]),this.Va(),void Tn.info("All overrides cleared");if(U(t))return this.F({[Pt]:nd(t)}),this.Va(),void Tn.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[Pt]=U(r)?nd(r):r),s&&(i[Ln]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([Pt,Ln]):r===!1?this.q(Pt):s===!1&&this.q(Ln),this.Va(),r===!1?Tn.info("Flag overrides cleared"):r&&Tn.info("Flag overrides set",{flags:r}),void(s===!1?Tn.info("Payload overrides cleared"):s&&Tn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[Pt]:t}),this.Va(),void Tn.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(Zr)||[]).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({[Gi]:Object.keys(id(o)),[$n]:o,[Gt]:k({},this.Oa(Gt)||{},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(Zr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return ce((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({[Zr]: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(Gt)||{},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({[Gt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Gt)||{});t.forEach((i=>{delete n[i]})),this.F({[Gt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Gt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(Nn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[Nn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Nn)||{};this.F({[Nn]:k({},e,{[t]:{}})})}else this.q(Nn)}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}}},qv={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===Ui||this.Ya===Vr?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=Gu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=E==null||(e=E.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 zt.error("started without valid sessionManager"),new Error(tl+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Xt)throw new Error(tl+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&we(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(jn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return E&&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),zt.info("starting")):(this.Ya=Gu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==Ui&&this.Ya!==Vr&&(this.Ya=Ku),N!=null&&(e=N.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=N.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return zt.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(Hl),(e=this.Mr)==null||e.unregister(Df)}uo(t,e){if(q(t))return null;var n,i=Ae(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(zt.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;q(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[jn]: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===Ui&&(this.Ya=Vr,zt.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):zt.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(jn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(jn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return zt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!q(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=N.__PosthogExtensions__)==null||!e.initSessionRecording)return zt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Gf]:!0});var r;if(this.Ja||(this.Ja=(r=N.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Vr||this.Ya===Ui?void 0:(this.Ya=Ui,zt.info("persisted remote config is stale, requesting fresh config before starting"),void new yh(this._instance).load());this.Ya=Ku,(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({[Uf]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[jf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Hf:Wf]:!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))}}},zv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new qu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=me(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(E&&F){var t=n=>{n=n||E?.event;try{this.bo(n)}catch(i){la.error("Failed to capture event",i)}};if(we(F,"submit",t,{capture:!0}),we(F,"change",t,{capture:!0}),we(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||E?.event;try{this.bo(n,aa)}catch(i){la.error("Failed to capture copy/cut event",i)}};we(F,"copy",e,{capture:!0}),we(F,"cut",e,{capture:!0})}}}else la.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;wt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Fa]: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[Fa],i=this.co,r=this.instance.Qi()&&!this.fo;if(Qe(i)&&!wt(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=Yo(t);Xf(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())&&wu(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===aa;if(i&&(function(d,f,p,h,g,m){var v;if(!E||Gl(d)||p!=null&&p.url_allowlist&&!vu(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&vu(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>f.type===S)))return!1}var w=rh(d,h),_=w.parentIsUsefulElement,x=w.targetElementList;if(!(function(S,P){var R=P?.element_allowlist;if(C(R))return!0;var L,$=function(J){if(R.some((G=>J.tagName.toLowerCase()===G)))return{v:!0}};for(var O of S)if(L=$(O))return L.v;return!1})(x,p)||!Va(x,p?.css_selector_allowlist)||Va(x,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Hm))return!1;try{var I=E.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&&(Vl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=$v(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===aa){var l,u=th(E==null||(l=E.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 Ue(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(E==null||(e=E.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(){E&&E.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(E&&((e=E.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return zu;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 Ue(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];Ue(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 zu}})(E.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=E==null||(e=E.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(si,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};we(E,"popstate",t),this.wo=()=>{E&&E.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[Ra]),this.rageclicks=new qu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return me(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return q(this.Ne.capture_heatmaps)?q(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Nv.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({[Ra]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ua(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(){E&&F&&(this.Po=this.cr.bind(this),we(E,Is,this.Po),this.Ro=t=>this.ke(t||E?.event),we(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||E?.event),we(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Cu(this.instance,Ym,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),we(F,xs,this.Oo),this.vo=!0)}Eo(){var t;E&&F&&(this.Po&&E.removeEventListener(Is,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(xs,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&&bn(u)&&!rt(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:E)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=nh(u)}return!1})(Yo(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"),!mu(t.target)&&ua(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&wu(Yo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!mu(t.target)&&ua(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(E){var e=this.Ne.disable_capture_url_hashes?wn(E.location.href):E.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...wi,...n||[]]:[],r=hr(e,i,pr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!rn(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Cu,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},q(n?.name)||q(n?.value))Rn.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=Ae(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 Rn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=N.__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 Rn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[La]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=me(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return q(n)?((e=this._instance.persistence)==null?void 0:e.props[Na])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(me(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=me(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=me(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=me(this.Wo)&&Ae(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Vu;return t>0&&6e4>=t?Vu:t}get isEnabled(){var t=_e?.protocol;if(t!=="http:"&&t!=="https:")return Rn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=me(this.Wo)?this.Wo.web_vitals:wt(this.Wo)?this.Wo:void 0;return wt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Rn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=me(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=me(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[La]:n}),this._instance.persistence.register({[Na]: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=N.__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?Rn.error("failed to load script",r):t()}))}Bo(t){var e=t||E?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?wn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...wi,...i||[]]:[];return hr(n,r,pr)}Rn.error("Could not determine current URL")}}},Vv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(E&&this.isEnabled&&(n=N.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=N.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=N.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=N.__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){ji.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Ta]),this.Jo=new qg(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:ji})),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 me(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?(ji.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return ji.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({[Ta]: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)?ji.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 am([new gm,new xm,new vm,new mm,new Em,new bm,new _m,new Sm],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var p=fu.test(f)?f.replace(fu,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((b=>{return k({},b,{filename:b.filename||(w=v,w[w.length-1]||{}).filename,function:b.function||yi});var w}))})(u)}})("web:javascript",dm,pm)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(Ma))!==null&&e!==void 0?e:[],this.el=_s(this.il()),this.rl=new km(this.el)}onConfigChange(){this.el=_s(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({[Ma]:this.Xo,[$a]:o})}}}get nl(){var t,e=!!this._instance.get_property($a),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(!Q(t)||t.trim().length===0)return void kt.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)=>Im.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&&kt.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[vs]:t,[ys]:new Date().toISOString()},i))}catch(s){kt.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 kt.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 kt.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 kt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&q(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 kt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void kt.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 kt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[vs]:t,[ys]:new Date().toISOString()})}sl(t){return me(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 Q(r)&&r.length>0&&n.$exception_types.push(r),Q(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=Th[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 kt.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!q(t)&&U(t)}}},Gv=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({[Ul]:!!e.productTours}),!da(this._instance))return!this.vl&&q((n=this.Mr)==null?void 0:n.props[Yi])||Gr.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&&da(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Gr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=N.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=N.__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[Yi];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(da(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||Gr.warn(o):Gr.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({[Yi]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){q(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(Yi)}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)}}},eo),Kv={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=N._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var p=t.$set_once,h=t.$set;return{event:k({},nf(t,Ov),{properties:k({},t.properties,h?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(It.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)||(It.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,p=(m,v,b)=>{if(m!=null&&m[v]){var w=m[v];m[v]=b(w),c.push((()=>{m[v]=w}))}},h=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:h(v))).filter((v=>!Qe(v)));return p(u,"appendChild",(m=>function(v){var b=h(v);return b?m.call(this,b):v})),p(u,"insertBefore",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):v})),p(u,"replaceChild",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):b})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];var x=g(w);return w.length&&!x.length?void 0:v.apply(this,x)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,b){var w=h(b);return w?m.call(this,v,w):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&&(It.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,It.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){It.error(Yu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){It.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){It.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 It.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;N["__$$ph_site_app_"+u]=r._instance,(l=N.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return It.error(Yu+u,d)}))};for(var a of s.siteApps)o()}else It.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Yv={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=N.__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=N.__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=N.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Lv.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()}}},Jv=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 te.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(q(e))return te.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,te.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)te.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)te.info(Ju);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())te.info("Not loading surveys in cookieless mode without consent.");else{var t=N?.__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(Wl);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 te.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new jv(this._instance),te.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){te.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 te.info(Ju),t([]);var n,i=this._instance.get_property(Ba);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?te.error(a):r.error||te.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&($h(p)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[Ba]:c,[bs]: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(bs);return Ae(t)&&Date.now()-t>3e5}Bl(){return Ae(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};Nh(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){te.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!q(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);te.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(q(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(q(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(q(this._surveyManager))return te.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 q(this._surveyManager)?(te.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(q(this._surveyManager))te.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Ev.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(te.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;te.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),te.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);te.warn("Survey element not found")}else te.warn("Surveys of type "+r.type+" cannot be rendered in the app");else te.warn("Survey not found")}}displaySurvey(t,e){var n;if(q(this._surveyManager))te.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!==Ka.Popover&&e.initialResponses&&te.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 te.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==Ka.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else te.warn("Survey not found")}}cancelPendingSurvey(t){q(this._surveyManager)?te.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},eo),Zv={toolbar:class{constructor(t){this.instance=t}Wl(t){N.ph_toolbar_state=t}Vl(){var t;return(t=N.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),za(this.instance.config)||!E||!F)return!1;t=t??E.location,n=n??E.history;try{if(!e){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}e=E?.localStorage}var i,r=Uv||As(t.hash,"__posthog")||As(t.hash,"state"),s=r?pu((()=>JSON.parse(atob(decodeURIComponent(r)))))||pu((()=>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(Zu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=N.ph_load_toolbar||N.ph_load_editor;!q(e)&&Ue(e)?e(t,this.instance):Xu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(Zf));if(!E||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(E.localStorage.setItem(Zu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=N.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Xu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),we(E,"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)}}},Xv=k({experiments:Oe},eo),Qv={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;q(e)||(wt(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||za(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=N?.__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(Wl);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 dt.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,dt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else dt.error("Cannot complete initialization: remote config is null")}eu(t,e){dt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():dt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Qe(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":za(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?q(this.Jl)||!this.Jl.token?"missing_token":N!=null&&N.__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 ce((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(dt.warn(Mn),null)}))()}getMessages(t,e){var n=this;return ce((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(dt.warn(Mn),null)}))()}markAsRead(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(dt.warn(Mn),null)}))()}getTickets(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(dt.warn(Mn),null)}))()}requestRestoreLink(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(dt.warn(Mn),null)}))()}restoreFromToken(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(dt.warn(Mn),null)}))()}restoreFromUrlToken(){var t=this;return ce((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(dt.warn(Mn),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()}}},ey={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ve("[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(od)||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),E&&we(E,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=C(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(f=w?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=w?.["deployment.environment"])!==null&&h!==void 0?h:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,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 rm(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},sd);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;!q(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){od(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=N?.__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(Wl)}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===Kt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Kt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.LIB_VERSION}}Ot(t){return new Promise((e=>{if(ch(this.Sa,3))e({kind:"fatal",error:ha(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:ha(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:ha(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=uh(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,oe.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,sd,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=$f(s,Mf(n,oe.LIB_NAME,oe.LIB_VERSION),i,oe.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,q(r)||(e.sessionStartTimestamp=r),q(s)||(e.lastActivityTimestamp=s)}if(N!=null&&(t=N.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?wn(N.location.href):N.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},ty={metrics:class{constructor(t){this.rt=ve("[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 sm(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:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.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)}}},ny=k({},eo,qv,zv,Vv,Gv,Kv,Jv,Yv,Zv,Xv,Qv,ey,ty);tt.__defaultExtensionClasses=k({},ny);var jh=(function(){oe.SDK_DIST_CHANNEL="npm";var t=sr[oi]=new tt;return(function(){function e(){e.done||(e.done=!0,Bh=!1,ae(sr,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():we(F,"DOMContentLoaded",e,{capture:!1}):E&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const iy=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let nt=null,$s=null,Uh="";const nl=new Map;function Hh(t){return[...t.querySelectorAll(iy)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function ry(t){for(const n of document.body.children)n===t||n.tagName==="SCRIPT"||(nl.set(n,{inert:n.inert,ariaHidden:n.getAttribute("aria-hidden")}),n.inert=!0,n.setAttribute("aria-hidden","true"));const e=document.activeElement;e&&e!==document.body&&!t.contains(e)&&e.blur()}function sy(){for(const[t,e]of nl)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);nl.clear()}function Wh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=nt&&nt!==n?nt:null,r=$s;if(i&&Ge(i,{restoreFocus:!1,force:!0}),nt!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),$s=a,Uh=document.body.style.overflow,ry(n),document.body.style.overflow="hidden"}nt=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(nt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Hh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function Ge(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Wh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==nt)return!0;sy(),document.body.style.overflow=Uh,nt=null;const i=$s;return $s=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function ad(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 oy(t){if(!Wh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ge(t)}document.addEventListener("keydown",t=>{if(!nt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),oy(nt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Hh(nt);if(!e.length){t.preventDefault(),(nt.querySelector(".modal-content")||nt).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 ay(){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 Zl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),ly=Object.freeze({free:2,professional:50,power:2e3}),cy="(contact us)",uy=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 ${cy}`])}),qh="CodeFile",zh="GeneratedCode",dy={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function vn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function il(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function fy(t={},e=0){const n=il(t.artifactType||t.type||qh),i=il(t.artifactName||t.name||t.fileName||`${zh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Vh(t={},e=0){const n=vn(t),i=n.artifactType||n.type||qh,r=n.artifactName||n.name||zh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:il(n.id)||fy({...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:Gh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:Kh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:vn(n.metadata),codeType:n.codeType||dy[i]||"O"}}function Gh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=vn(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(vn(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function Kh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=vn(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 rl(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 gr(t,e={}){const n=[],i=typeof t=="string"?rl(t):t,s=vn(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)=>Vh(d,f)),l=new Map(o.map((d,f)=>[vn(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=Kh(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:Gh(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:vn(s.metadata)}}function Ei(t){return gr(t).artifacts[0]||Vh()}function an(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Si(t){return JSON.stringify(t,null,2)}function hy(t){return Si({task:"architect",userRequest:String(t??"")})}function py(t){const e=an(t);return e&&typeof e=="object"&&typeof e.task=="string"?Si(e):Si({task:"generate_bundle",bundleSpec:e})}function gy(t){return Si({task:"review_bundle",generatedBundle:an(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 Xl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=an(e)),n}function my({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return Si({task:"regenerate_artifact",artifactId:i,bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(r)})}function Yh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Si({task:"regenerate_bundle",bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(i??"")})}const ld={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"},vy=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function st(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yy(t){return st(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||st(t.filterSummary)||st(t.filterResults):!1}function Jh(t,e=0){if(!st(t)||e>3)return null;if(yy(t))return t;for(const n of vy){const i=t[n];if(st(i)){const r=Jh(i,e+1);if(r)return r}}return null}function Ls(t){return Array.isArray(t)?t.some(Ls):st(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(Ls):!1}function sl(t){return Array.isArray(t)?t.some(sl):st(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(sl):!1}function Zh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function _y(t,e){if(st(t))for(const[n,i]of Object.entries(t)){if(!st(i))continue;const r=st(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>st(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Zh(n))}}function wy(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>st(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!Ls(r))continue;const s=Zh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=st(o)?Object.entries(o).filter(([,l])=>Ls(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function by(t){return ld[t]?ld[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function cd(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 Ey(t){const e=Jh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);_y(e.filterSummary,n),wy(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=sl(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Sy(t,e){const n=Ey(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(by))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${cd(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 ${cd(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 xy(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ud(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of xy(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 E=typeof window<"u"?window:void 0,Be=typeof globalThis<"u"?globalThis:E,qe=Be?.navigator,F=Be?.document,_e=Be?.location,Ml=Be?.fetch,wa=Be!=null&&Be.XMLHttpRequest&&"withCredentials"in new Be.XMLHttpRequest?Be.XMLHttpRequest:void 0,Yc=Be?.AbortController,Mg=Be?.CompressionStream,Je=qe?.userAgent;function tf(){return!(!E||E.navigator.onLine===!1)}var Ri=typeof globalThis<"u"?globalThis:E;Ri&&typeof self>"u"&&(Ri.self=Ri),Ri&&typeof File>"u"&&(Ri.File=function(){});var N=E??{},oe={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Jc(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 ce(t){return function(){var e=this,n=arguments;return new Promise((function(i,r){var s=t.apply(e,n);function o(l){Jc(s,i,r,o,a,"next",l)}function a(l){Jc(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 nf(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 Zc=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Xc(t){return typeof t=="string"||t}function Qc(t){return typeof t=="string"?t:void 0}var Ti,$g=["$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"],Kt=(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})({}),eu=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Lg=["$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"],Ng=["token"],rf="NativeGzipValidationError",ba=t=>t.length>=2&&t[0]===31&&t[1]===139,tu=(t,e)=>t===eu.GZipJS||e===eu.GZipJS||e==="gzip",nu=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",Or=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=rf,e},Og=(function(){var t=ce((function*(e,n){18>e.size&&Or("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());ba(i)&&i[2]===8||Or("invalid-header");var r=new DataView(yield e.slice(e.size-8).arrayBuffer());r.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Ti)return Ti;Ti=[];for(var c=0;256>c;c++){for(var d=c,f=0;8>f;f++)d=1&d?3988292384^d>>>1:d>>>1;Ti[c]=d>>>0}return Ti})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&Or("invalid-crc");var s=n.length>>>0;r.getUint32(4,!0)!==s&&Or("invalid-size")}));return function(e,n){return t.apply(this,arguments)}})();function Ea(){return Ea=ce((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=ce((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 Og(l,i),l}catch(u){if(n!=null&&n.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}})),Ea.apply(this,arguments)}var Bg=["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"],iu=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return Bg.concat(e).some((i=>{var r=i.toLowerCase();return n.indexOf(r)!==-1}))};function j(t,e){return t.indexOf(e)!==-1}var Zs=function(t){return t.trim()},Sa=function(t){return t.replace(/^\$/,"")};function sf(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 of=Object.prototype,af=of.hasOwnProperty,Xs=of.toString,U=Array.isArray||function(t){return Xs.call(t)==="[object Array]"},Ue=t=>typeof t=="function",me=t=>t===Object(t)&&!U(t),rn=t=>{if(me(t)){for(var e in t)if(af.call(t,e))return!1;return!0}return!1},C=t=>t===void 0,Q=t=>Xs.call(t)=="[object String]",xa=t=>Q(t)&&t.trim().length===0,Qe=t=>t===null,q=t=>C(t)||Qe(t),Ae=t=>Xs.call(t)=="[object Number]"&&t==t,Vt=t=>Ae(t)&&t>0,wt=t=>Xs.call(t)==="[object Boolean]",Dg=t=>t instanceof FormData,jg=t=>j(Lg,t),Ug=t=>j(Ng,t);function lf(t){return t===null||typeof t!="object"}function ds(t,e){return{}.toString.call(t)==="[object "+e+"]"}function $l(t){return typeof Event<"u"&&cf(t,Event)}function cf(t,e){try{return t instanceof e}catch{return!1}}var Hg=[!0,"true",1,"1","yes"],Do=t=>j(Hg,t),Wg=[!1,"false",0,"0","no"];function Rt(t,e,n,i,r){return e>n&&(i.warn("min cannot be greater than max."),e=n),Ae(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),Rt(r||n,e,n,i))}class qg{constructor(e){this.tt={},this.et=e.et,this.it=Rt(e.bucketSize,0,100,e.rt),this.nt=Rt(e.refillRate,0,this.it,e.rt),this.st=Rt(e.refillInterval,0,864e5,e.rt)}ot(e,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 lt="Mobile",fs="iOS",sn="Android",mi="Tablet",uf=sn+" "+mi,df="iPad",ff="Apple",hf=ff+" Watch",Qi="Safari",vi="BlackBerry",pf="Samsung",gf=pf+"Browser",mf=pf+" Internet",Hn="Chrome",zg=Hn+" OS",vf=Hn+" "+fs,Ll="Internet Explorer",yf=Ll+" "+lt,Nl="Opera",Vg=Nl+" Mini",Ol="Edge",_f="Microsoft "+Ol,di="Firefox",wf=di+" "+fs,lr="Nintendo",cr="PlayStation",fi="Xbox",bf=sn+" "+lt,Ef=lt+" "+Qi,Wi="Windows",Ia=Wi+" Phone",ru="Nokia",ka="Ouya",Sf="Generic",Gg=Sf+" "+lt.toLowerCase(),xf=Sf+" "+mi.toLowerCase(),Ca="Konqueror",If="Oculus Browser",hs="Vivaldi",kf="Yandex",ps="Whale",Pa="DuckDuckGo",Cf="Pale Moon",gs="Waterfox",er="Brave",Pf="Google Search App",Se="(\\d+(\\.\\d+)?)",jo=new RegExp("Version/"+Se),Kg=new RegExp(fi,"i"),Yg=new RegExp(cr+" \\w+","i"),Jg=new RegExp(lr+" \\w+","i"),Bl=new RegExp(vi+"|PlayBook|BB10","i"),Zg={"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"},Af=function(t,e,n,i){e=e||"";var r=(function(s){return s!=null&&s.brave?er:null})(n);return r||(i!=null&&i.detectGoogleSearchApp&&j(t,"GSA/")?Pf:j(t," OPR/")&&j(t,"Mini")?Vg:j(t," OPR/")?Nl:Bl.test(t)?vi:j(t,"IE"+lt)||j(t,"WPDesktop")?yf:j(t,"OculusBrowser")?If:j(t,gf)?mf:j(t,Ol)||j(t,"Edg/")?_f:j(t,hs+"/")?hs:j(t,"YaBrowser/")?kf:j(t,ps+"/")?ps:j(t,Pa+"/")||j(t,"Ddg/")?Pa:j(t,"FBIOS")?"Facebook "+lt:j(t,"UCWEB")||j(t,"UCBrowser")?"UC Browser":j(t,"CriOS")?vf:j(t,"CrMo")||j(t,Hn)?Hn:j(t,sn)&&j(t,Qi)?bf:j(t,"FxiOS")?wf:j(t.toLowerCase(),Ca.toLowerCase())?Ca:j(t,er+"/")?er:((s,o)=>o&&j(o,ff)||(function(a){return j(a,Qi)&&!j(a,Hn)&&!j(a,sn)})(s))(t,e)?j(t,lt)?Ef:Qi:j(t,"PaleMoon/")?Cf:j(t,gs+"/")?gs:j(t,di)?di:j(t,"MSIE")||j(t,"Trident/")?Ll:j(t,"Gecko")?di:"")},Xg={[yf]:[new RegExp("rv:"+Se)],[_f]:[new RegExp(Ol+"?\\/"+Se)],[Hn]:[new RegExp("("+Hn+"|CrMo)\\/"+Se)],[vf]:[new RegExp("CriOS\\/"+Se)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Se)],[Qi]:[jo],[Ef]:[jo],[Nl]:[new RegExp("(Opera|OPR)\\/"+Se)],[di]:[new RegExp(di+"\\/"+Se)],[wf]:[new RegExp("FxiOS\\/"+Se)],[Ca]:[new RegExp("Konqueror[:/]?"+Se,"i")],[vi]:[new RegExp(vi+" "+Se),jo],[bf]:[new RegExp("android\\s"+Se,"i")],[mf]:[new RegExp(gf+"\\/"+Se)],[If]:[new RegExp("OculusBrowser\\/"+Se)],[hs]:[new RegExp(hs+"\\/"+Se)],[kf]:[new RegExp("YaBrowser\\/"+Se)],[ps]:[new RegExp(ps+"\\/"+Se)],[er]:[new RegExp(er+"\\/"+Se)],[Pa]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Se)],[Cf]:[new RegExp("PaleMoon\\/"+Se)],[gs]:[new RegExp(gs+"\\/"+Se)],[Pf]:[new RegExp("GSA\\/"+Se)],[Ll]:[new RegExp("(rv:|MSIE )"+Se)],Mozilla:[new RegExp("rv:"+Se)]},Qg=function(t,e,n,i){var r=Af(t,e,n,i),s=Xg[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},su=[[new RegExp(fi+"; "+fi+" (.*?)[);]","i"),t=>[fi,t&&t[1]||""]],[new RegExp(lr,"i"),[lr,""]],[new RegExp(cr,"i"),[cr,""]],[Bl,[vi,""]],[new RegExp(Wi,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Ia,""];if(new RegExp(lt).test(e)&&!/IEMobile\b/.test(e))return[Wi+" "+lt,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var i=Zg[n[1]]||"";return/arm/i.test(e)&&(i="RT"),[Wi,i]}return[Wi,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[fs,[t[3],t[4],t[5]||"0"].join(".")]:[fs,""]],[/(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("("+sn+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+sn+")","i"),t=>t&&t[2]?[sn,[t[2],t[3],t[4]||"0"].join(".")]:[sn,""]],[/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/,[zg,""]],[/Linux|debian/i,["Linux",""]]],ou=function(t){return Jg.test(t)?lr:Yg.test(t)?cr:Kg.test(t)?fi:new RegExp(ka,"i").test(t)?ka:new RegExp("("+Ia+"|WPDesktop)","i").test(t)?Ia:/iPad/.test(t)?df:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?hf:Bl.test(t)?vi:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(ru,"i").test(t)?ru:/(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(lt).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)?sn:uf:new RegExp("(pda|"+lt+")","i").test(t)?Gg:new RegExp(mi,"i").test(t)&&!new RegExp(mi+" pc","i").test(t)?xf:""},em=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function au(t,e){return typeof(n=t)=="string"&&em.test(n)?t:e();var n}function wn(t){return t&&t.split("#")[0]}function Dl(t,e){var n=setTimeout(t,e);return n?.unref&&n?.unref(),n}function lu(t,e,n){return Ff.apply(this,arguments)}function Ff(){return(Ff=ce((function*(t,e,n){var i;try{return yield Promise.race([t,new Promise(((r,s)=>{i=Dl((()=>{try{n?.(),r()}catch(o){s(o)}}),e)}))])}finally{clearTimeout(i)}}))).apply(this,arguments)}var tm=t=>t instanceof Error,Rf={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}},nm=Rf.info;function Tf(t){if(wt(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=>Tf(e)))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function ms(t){var e=[];for(var n in t){var i=t[n];Qe(i)||C(i)||e.push({key:n,value:Tf(i)})}return e}function im(t,e){var n=Rf[t.level||"info"]||nm,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),q(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),q(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:ms(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 Mf(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 $f(t,e,n,i){return{resourceLogs:[{resource:{attributes:ms(e)},scopeLogs:[{scope:{name:n,version:i},logRecords:t}]}]}}let rm=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:im(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 ce((function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally((()=>{t.ct=null}))),t.ct}))()}Ft(){var t=this;return ce((function*(){var e;t.Et();var n=(e=t._instance.getPersistedProperty(Kt.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=$f(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(Kt.LogsQueue))!==null&&o!==void 0?o:[],r+=l.length,c.kind==="fatal"))throw c.error}}))()}Dt(t){var e=this;return ce((function*(){var n,i=Math.max(0,t-e.ft),r=(n=e._instance.getPersistedProperty(Kt.LogsQueue))!==null&&n!==void 0?n:[];e._instance.setPersistedProperty(Kt.LogsQueue,r.slice(i)),yield e.dt()}))()}Lt(){return Mf(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var n=(e=this._instance.getPersistedProperty(Kt.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(Kt.LogsQueue,n),this.kt>n.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Dl((()=>{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(Kt.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return ce((function*(){e.Et();var n=e.flush().catch((()=>{}));t!==void 0?yield lu(n,t):yield n}))()}flushWithTimeout(t){var e=this;return ce((function*(){var n=e.flush();yield lu(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 Uo=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function cu(t){return String(t)+"000000"}function uu(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 sm=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=ce((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=uu(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(Uo.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,Uo)]+=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=Dl((()=>{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 ce((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:ms(n)},scopeMetrics:[{scope:{name:i,version:r},metrics:e}]}]};var e,n,i,r}Xt(t){var e=cu(Date.now()),n=new Map;for(var i of t.values()){var r,s=uu(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=ms((r=i.attributes)!==null&&r!==void 0?r:{}),l=cu(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:Uo})}return Array.from(n.values())}Yt(t){var e,n;for(var i of t){var r=i[0],s=i[1],o=this.Bt.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,s.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((n=s.total)!==null&&n!==void 0?n:0);break;case"gauge":break;case"histogram":if(s.hist)if(o.hist){o.hist.count+=s.hist.count,o.hist.sum+=s.hist.sum,o.hist.min=Math.min(o.hist.min,s.hist.min),o.hist.max=Math.max(o.hist.max,s.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=s.hist.bucketCounts[a]}else o.hist=s.hist}else this.Qt()&&this.Bt.set(r,s)}}};var Br,du,Ho;function om(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Ho&&n.length===du||(du=n.length,Ho=n.reduce(((i,r)=>{Br||(Br={});var s=Br[r];if(s)i[s[0]]=s[1];else for(var o=t(r),a=o.length-1;a>=0;a--){var l=o[a],u=l?.filename,c=e[r];if(u&&c){i[u]=c,Br[r]=[u,c];break}}return i}),{})),Ho}}class am{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 ce((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 ce((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:om(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 yi="?";function Aa(t,e,n,i,r){var s={platform:t,filename:e,function:n===""?yi:n,in_app:!0};return C(i)||(s.lineno=i),C(r)||(s.colno=r),s}var Lf=(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]:yi,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},lm=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,cm=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,um=/\((\S*)(?::(\d+))(?::(\d+))\)/,dm=(t,e)=>{var n=lm.exec(t);if(n)return Aa(e,n[1],yi,+n[2],+n[3]);var i=cm.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var r=um.exec(i[2]);r&&(i[2]=r[1],i[3]=r[2],i[4]=r[3])}var s=Lf(i[1]||yi,i[2]);return Aa(e,s[1],s[0],i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},fm=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,hm=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,pm=(t,e)=>{var n=fm.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var i=hm.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]||yi,o=Lf(s,r);return Aa(e,r=o[1],s=o[0],n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},fu=/\(error: (.*)\)/;class gm{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var i=Q(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 ds(e,"DOMException")}isDOMError(e){return ds(e,"DOMError")}}class mm{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 cf(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 vm{constructor(){}match(e){return!!ds(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 Q(e.message)&&e.message.length>0}pe(e){var n=e;if(Q(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 ym=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class _m{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(ym);return r&&(n=r[1],i=r[2]),[n,i]}}var wm=["fatal","error","warning","log","info","debug"];function Nf(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 bm{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 $l(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: "+Nf(e)}isSeverityLevel(e){return Q(e)&&!xa(e)&&wm.indexOf(e)>=0}getStack(e){try{return Q(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:Q(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(tm(i))return i}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}}class Em{match(e){return $l(e)}coerce(e,n){var i,r=e.constructor.name;return{type:r,value:r+" captured as exception with keys: "+Nf(e),stack:(i=n.syntheticException)==null?void 0:i.stack,synthetic:!0}}}class Sm{match(e){return lf(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 xm{match(e){return ds(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!$l(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 lf(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 vs="$message",ys="$timestamp",Im=new Set([vs,ys]),Wo={enabled:!0,max_bytes:32768};function _s(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Wo.enabled,max_bytes:Cm(t.max_bytes,Wo.max_bytes)}:k({},Wo)}class km{constructor(e){this.Ke=[],this.Je=0,this.Ne=_s(e)}setConfig(e){this.Ne=_s(e),this.Xe()}add(e){var n=(function(r){var s;try{s=sf(r)}catch{return}try{var o=JSON.parse(s);if(!me(o))return;var a=o,l=a[vs],u=a[ys];return!Q(l)||l.trim().length===0||!Q(u)&&!Ae(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 Cm(t,e){if(!Ae(t)||t===1/0||t===-1/0)return e;var n=Math.floor(t);return 0>n?e:n}var Of=function(t,e){var n=(e===void 0?{}:e).debugEnabled,i={k(r){if(E&&(oe.DEBUG||E.POSTHOG_DEBUG||n)&&!C(E.console)&&E.console){for(var s=("__rrweb_original__"in E.console[r])?E.console[r].__rrweb_original__:E.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)=>Of(t+" "+r,s)};return i},A=Of("[PostHog.js]"),ve=A.createLogger,Pm=ve("[ExternalScriptsLoader]"),qo=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Pm.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)};N.__PosthogExtensions__=N.__PosthogExtensions__||{},N.__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)}qo(t,i,n)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");qo(t,o,n)}},N.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var i=t.requestRouter.endpointFor("api",e);qo(t,i,n)};oe.DEBUG=!1,oe.LIB_VERSION="1.415.7",oe.LIB_NAME="web";var Bf="$people_distinct_id",ur="$device_id",zo="$device_model",qi="__alias",zi="__timers",Fa="$autocapture_disabled_server_side",Ra="$heatmaps_enabled_server_side",Ta="$exception_capture_enabled_server_side",Ma="$error_tracking_suppression_rules",$a="$error_tracking_capture_extension_exceptions",La="$web_vitals_enabled_server_side",jl="$dead_clicks_enabled_server_side",Ul="$product_tours_enabled_server_side",Na="$web_vitals_allowed_metrics",jn="$session_recording_remote_config",Df="$replay_sample_rate",jf="$replay_override_sampling",Uf="$replay_override_linked_flag",Hf="$replay_override_url_trigger",Wf="$replay_override_event_trigger",li="$sesid",Hl="$session_is_sampled",$n="$enabled_feature_flags",Vi="$active_feature_flags",Zr="$early_access_features",Oa="$feature_flag_details",Gi="$feature_flag_payloads",Xr="$feature_flag_request_id",ws="$minimal_flag_called_events",Pt="$override_feature_flags",Ln="$override_feature_flag_payloads",Gt="$stored_person_properties",Nn="$stored_group_properties",Ba="$surveys",bs="$surveys_loaded_at",Da="$surveys_activated",Qr="$surveys_activated_session",es="$surveys_activated_timestamps",Ki="ph_product_tours",Bn="$flag_call_reported",Yi="$flag_call_reported_session_id",ts="$feature_flag_errors",tr="$feature_flag_evaluated_at",ft="$user_state",ja="$client_session_props",Ua="$capture_rate_limit",Ha="$initial_campaign_params",Wa="$initial_referrer_info",Es="$initial_person_info",Ss="$epp",Dr="$posthog_cookieless",qf="$cookieless_mode",zf="$sdk_debug_extensions_init_method",Vf="$sdk_debug_extensions_init_time_ms",Gf="$sdk_debug_recording_script_not_loaded",Wl="PostHog loadExternalDependency extension not found.",On="on_reject",Xt="always",ei="anonymous",Pn="identified",qa="identified_only",xs="visibilitychange",Is="beforeunload",si="$pageview",Vo="$pageleave",Go="$identify",hu="$groupidentify";function jr(t,e){U(t)&&t.forEach(e)}function ae(t,e){if(!q(t))if(U(t))t.forEach(e);else if(Dg(t))t.forEach(((i,r)=>e(i,r)));else for(var n in t)af.call(t,n)&&e(t[n],n)}var ge=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 ns(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 pu=function(t){try{return t()}catch{return}},Am=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)}}},ql=function(t){var e={};return ae(t,(function(n,i){(Q(n)&&n.length>0||Ae(n))&&(e[i]=n)})),e},Fm=["herokuapp.com","vercel.app","netlify.app"];function Rm(t){var e=t?.hostname;if(!Q(e))return!1;var n=e.split(".").slice(-2).join(".");for(var i of Fm)if(n===i)return!1;return!0}function we(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 za(t){return t.name==="ph_toolbar_internal"}var Kf=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 Ae(t)&&isFinite(t)&&Math.floor(t)===t});class ks{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 ks(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 ks(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 Tm{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 ks.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 Mm}}var gu,Yf=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};E&&!C(E.crypto)&&crypto.getRandomValues&&(Yf=t=>crypto.getRandomValues(t));class Mm{nextUint32(){return this.R.length>this.O||(Yf(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var Yt=()=>$m().toString(),$m=()=>(gu||(gu=new Tm)).generate(),Mi="",Lm=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Qt={N:()=>!!F,j(t){A.error("cookieStore error: "+t)},P:Kf,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(h,g){if(g===void 0&&(g=F),Mi)return Mi;if(!g||["localhost","127.0.0.1"].includes(h))return"";for(var m=h.split("."),v=Math.min(m.length,8),b="dmn_chk_"+Yt();!Mi&&v--;){var w=m.slice(v).join("."),_=b+"=1;domain=."+w+";path=/";g.cookie=_+";max-age=3",g.cookie.includes(b)&&(g.cookie=_+";max-age=0",Mi=w)}return Mi})(c);if(!f){var p=(h=>{var g=h.match(Lm);return g?g[0]:""})(c);p!==f&&A.info("Warning: cookie subdomain discovery mismatch",p,f),f=p}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}}},Ko=null,ue={N(){if(!Qe(Ko))return Ko;var t=!0;if(C(E))t=!1;else try{var e="__mplssupport__";ue.F(e,"xyz"),ue.P(e)!=='"xyz"'&&(t=!1),ue.q(e)}catch{t=!1}return t||A.error("localStorage unsupported; falling back to cookie store"),Ko=t,t},j(t){A.error("localStorage error: "+t)},P(t){try{return E?.localStorage.getItem(t)}catch(e){ue.j(e)}return null},H(t){try{return JSON.parse(ue.P(t))||{}}catch{}return null},F(t,e){try{return E?.localStorage.setItem(t,JSON.stringify(e)),!0}catch(n){ue.j(n)}return!1},q(t){try{E?.localStorage.removeItem(t)}catch(e){ue.j(e)}}},Nm=[ur,"distinct_id",li,Hl,Ss,Es,ft],Ur={},Om={N:()=>!0,j(t){A.error("memoryStorage error: "+t)},P:t=>Ur[t]||null,H:t=>Ur[t]||null,F:(t,e)=>(Ur[t]=e,!0),q(t){delete Ur[t]}},An=null,xe={N(){if(!Qe(An))return An;if(An=!0,C(E))An=!1;else try{var t="__support__";xe.F(t,"xyz"),xe.P(t)!=='"xyz"'&&(An=!1),xe.q(t)}catch{An=!1}return An},j(t){A.error("sessionStorage error: ",t)},P(t){try{return E?.sessionStorage.getItem(t)}catch(e){xe.j(e)}return null},H(t){try{return JSON.parse(xe.P(t))||null}catch{}return null},F(t,e){try{return E?.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(n){xe.j(n)}return!1},q(t){try{E?.sessionStorage.removeItem(t)}catch(e){xe.j(e)}}};class Bm{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===Xt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===On}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 Do(e)?1:j(Wg,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,n=e==="localStorage"?ue:Qt;if(!this.ni||this.ni!==n){this.ni=n;var i=e==="localStorage"?Qt:ue;i.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Do(i.P(this.ri))),i.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[qe?.doNotTrack,qe?.msDoNotTrack,N.doNotTrack].some((e=>Do(e)))}}function Jf(t,e){var n,i=t==null||(n=t.config)==null?void 0:n.get_current_url;if(!Ue(i))return e;try{var r=i(e);return Q(r)&&r?r:e}catch(s){return A.error("Error in get_current_url, falling back to window.location.href",s),e}}var Zf="__POSTHOG_TOOLBAR__",Dm=1,jm=3,Um=11;function mu(t){return t instanceof Element&&(t.id===Zf||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function bn(t){return!!t&&t.nodeType===Dm}function rt(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function Xf(t){return!!t&&t.nodeType===jm}function Qf(t){return!!t&&t.nodeType===Um&&bn(t.host)}var eh=1e3;function zl(t){return t?Zs(t).split(/\s+/):[]}function vu(t,e){var n=(function(i){var r,s=E==null||(r=E.location)==null?void 0:r.href;return C(s)?void 0:Jf(i,s)})(e);return!!(n&&t&&t.some((i=>n.match(i))))}function Cs(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return zl(e)}function th(t){return q(t)?null:Zs(t).split(/(\s+)/).filter((e=>nr(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function dr(t){var e="";return Ga(t)&&!sh(t)&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;Xf(n)&&n.textContent&&(e+=(i=th(n.textContent))!==null&&i!==void 0?i:"")})),Zs(e)}function Yo(t){var e;return C(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Vl=["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 nh(t){var e=t.parentNode;return!(!e||!bn(e))&&e}var Hm=[".ph-no-autocapture","[data-ph-no-autocapture]"],ih=["next","previous","prev",">","<"],Wm=[...ih,"+","-","−","–"],yu=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,_u=[".ph-no-rageclick",".ph-no-capture"],qm=["","text","search","email","password","url","tel","number"];function wu(t,e){if(!E||Gl(t))return!1;var n,i,r,s,o;if(wt(e)?(n=!!e&&_u,i=void 0,r=!1):(n=(s=e?.css_selector_ignorelist)!==null&&s!==void 0?s:_u,i=e?.content_ignorelist,r=(o=e?.ignore_text_selection)!==null&&o!==void 0&&o),n===!1||r&&(function(l){return!(!l||!bn(l))&&(!!rt(l,"textarea")||(rt(l,"input")?j(qm,(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=rh(t,!1).targetElementList;return!(function(l,u){if(l===!1||C(l))return!1;var c;if(l===!0)c=ih;else{if(!U(l))return!1;if(l.length>10)return A.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map((d=>d.toLowerCase()))}return u.some((d=>{var f=d.safeText,p=d.ariaLabel;return c.some((h=>yu(f,h)||yu(p,h)))}))})(i,a.map((l=>{var u;return{safeText:dr(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}})))&&!Va(a,n)}var Gl=t=>!t||rt(t,"html")||!bn(t),rh=(t,e)=>{if(!E||Gl(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,i=[t],r=t;r.parentNode&&!rt(r,"body");)if(Qf(r.parentNode))i.push(r.parentNode.host),r=r.parentNode.host;else{var s=nh(r);if(!s)break;if(e||Vl.indexOf(s.tagName.toLowerCase())>-1)n=!0;else try{var o=E.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}catch{}i.push(s),r=s}return{parentIsUsefulElement:n,targetElementList:i}};function Ga(t){for(var e=new Set,n=0,i=t;i.parentNode&&!rt(i,"body");i=i.parentNode){if(n++>=eh||e.has(i))return!1;e.add(i);var r=Cs(i);if(j(r,"ph-sensitive")||j(r,"ph-no-capture"))return!1}if(j(Cs(t),"ph-include"))return!0;var s=t.type||"";if(Q(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!Q(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 sh(t){return!!(rt(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||rt(t,"select")||rt(t,"textarea")||t.getAttribute("contenteditable")==="true")}var bu=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}))$"),Eu=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,zm=[16,15,14,13],Vm=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Su=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),xu=/[0-9A-Za-z_]/;function Gm(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 nr(t,e){if(e===void 0&&(e=!0),q(t))return!1;if(Q(t)){t=Zs(t);var n=e?bu.test((t||"").replace(/[- ]/g,"")):(function(r){var s;for(Eu.lastIndex=0;s=Eu.exec(r);){var o=s[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of zm){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(bu.test(d)&&Gm(d))return!0}}}return!1})(t);if(n)return!1;var i=e?Vm.test(t):(function(r){var s;for(Su.lastIndex=0;s=Su.exec(r);){var o=s[1],a=s[3];if(!(o&&a&&xu.test(o)&&xu.test(a)))return!0}return!1})(t);if(i)return!1}return!0}function Iu(t){var e=dr(t);return nr(e=(e+" "+oh(t)).trim())?e:""}function oh(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ae(t.childNodes,(function(n){var i;if(n&&((i=n.tagName)==null?void 0:i.toLowerCase())==="span")try{var r=dr(n);e=(e+" "+r).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+oh(n)).trim())}catch(s){A.error("[AutoCapture]",s)}})),e}function ku(t){return t.replace(/"|\\"/g,'\\"')}function Km(t){var e=t.attr__class;if(e)return U(e)?e:zl(e)}var Hr=ve("[Dead Clicks]"),Ym=()=>!0,Jm=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(jl)),i=t.instance.config.capture_dead_clicks;return wt(i)?i:!!me(i)||n};class Cu{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({[jl]:n.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai((()=>{this.oi()})):this.stop()}ai(e){var n,i;(n=N.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture?e():(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(r=>{r?Hr.error("failed to load script",r):e()}))}oi(){var e;if(F){if(!this.si&&(e=N.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=me(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=N.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.si.start(F),Hr.info("starting...")}}else Hr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,Hr.info("stopping..."))}}var Jo=ve("[SegmentIntegration]"),ah="posthog-js";function lh(t,e){var n=e===void 0?{}:e,i=n.organization,r=n.projectId,s=n.prefix,o=n.severityAllowList,a=o===void 0?["error"]:o,l=n.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,f,p,h,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var m=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=m,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var v,b=((d=c.exception)==null?void 0:d.values)||[],w=b.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=b[0])==null?void 0:f.value)||c.message,$exception_type:(p=b[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:w,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((h=b[0])==null?void 0:h.value)||c.message,$sentry_exception_type:(g=b[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 Zm{constructor(e,n,i,r,s,o){this.name=ah,this.setupOnce=function(a){a(lh(e,{organization:n,projectId:i,prefix:r,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class Pu{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=E?.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?Rt(a/o,0,1,A):1,p=o>1?Rt(l/o,0,1,A):1,h=u>1?Rt(c/u,0,1,A):1,g=u>1?Rt(d/u,0,1,A):1;r=ge(r,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:f,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:h,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return i.pathname&&(r.$prev_pageview_pathname=i.pathname),i.timestamp&&(r.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),r}}var Zo=["flags","surveys"],Xm={[Bf]:{exposure:"hidden"},[qi]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[zi]:{exposure:"hidden"},[Fa]:{exposure:"event"},[Ra]:{exposure:"hidden"},[Ta]:{exposure:"event"},[Ma]:{exposure:"hidden"},[$a]:{exposure:"event"},[La]:{exposure:"event"},[jl]:{exposure:"event"},[Ul]:{exposure:"hidden"},[Na]:{exposure:"event"},[jn]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[li]:{exposure:"hidden"},[Hl]:{exposure:"event"},[Df]:{exposure:"event",shouldSkipFromEventProperties:t=>Qe(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"},[$n]:{exposure:"hidden",storageGroup:"flags"},[Vi]:{exposure:"hidden",storageGroup:"flags"},[Zr]:{exposure:"hidden"},[Oa]:{exposure:"hidden",storageGroup:"flags"},[Gi]:{exposure:"hidden",storageGroup:"flags"},[Xr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ws]:{exposure:"hidden",storageGroup:"flags"},[Pt]:{exposure:"hidden"},[Ln]:{exposure:"hidden"},[Gt]:{exposure:"hidden"},[Nn]:{exposure:"hidden"},[Ba]:{exposure:"hidden",storageGroup:"surveys"},[bs]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Da]:{exposure:"event"},[Qr]:{exposure:"hidden"},[es]:{exposure:"hidden"},[Ki]:{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"},[Bn]:{exposure:"hidden"},[Yi]:{exposure:"hidden"},[ts]:{exposure:"hidden"},[tr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ft]:{exposure:"hidden"},[ja]:{exposure:"hidden"},[Ua]:{exposure:"hidden"},[Ha]:{exposure:"hidden"},[Wa]:{exposure:"hidden"},[Es]:{exposure:"hidden"},[Ss]:{exposure:"hidden"},[jf]:{exposure:"event"},[Uf]:{exposure:"event"},[Hf]:{exposure:"event"},[Wf]:{exposure:"event"},[zf]:{exposure:"event"},[Vf]:{exposure:"event"},[Gf]:{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"}},Qm=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Fn=t=>{var e=Xm[t];if(e)return e;for(var n of Qm){var i=n[1];if(t.indexOf(n[0])===0)return i}},ci=(t,e)=>{try{return JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e)}catch{return sf(t)}},Ps=t=>{var e=F?.createElement("a");return C(e)?null:(e.href=t,e)},_i=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," ")},fr=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},ch=(t,e)=>t>=e&&tf(),uh=(t,e,n,i)=>{if(t===0){if(tf()){var r=e+1;return r===n&&i(),r}return e}return 0},Wr="https?://(.*)",wi=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],ev=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...wi],hr="",tv=["li_fat_id"];function dh(t,e,n){if(!F)return{};var i,r=e?[...wi,...n||[]]:[],s=fh(fr(F.URL,r,hr),t),o=(i={},ae(tv,(function(a){var l=Kf(a);i[a]=l||null})),i);return ge(o,s)}function fh(t,e){var n=ev.concat(e||[]),i={};return ae(n,(function(r){var s=_i(t,r);i[r]=s||null})),i}function hh(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(!Qe(e)){i.$search_engine=e;var r=F?_i(F.referrer,n):"";r.length&&(i.ph_keyword=r)}return i}function Au(){return navigator.language||navigator.userLanguage}var Fs="$direct";function ph(){return F?.referrer||Fs}function gh(t,e,n){n===void 0&&(n=!1);var i=t?[...wi,...e||[]]:[],r=n?wn(_e?.href):_e?.href,s=r?.substring(0,1e3);return{r:ph().substring(0,1e3),u:s?fr(s,i,hr):void 0}}function mh(t,e){var n;e===void 0&&(e=!1);var i=t.r,r=t.u,s=e?wn(r):r,o={$referrer:i,$referring_domain:i==null?void 0:i==Fs?Fs:(n=Ps(i))==null?void 0:n.host};if(s){o.$current_url=s;var a=Ps(s);o.$host=a?.host,o.$pathname=a?.pathname;var l=fh(s);ge(o,l)}if(i){var u=hh(i);ge(o,u)}return o}function vh(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function nv(){try{return new Date().getTimezoneOffset()}catch{return}}var iv={flags:tr,surveys:bs},rv=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],ti="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(),E){var r=()=>this.flush();we(E,"beforeunload",r,{capture:!1}),we(E,"pagehide",r,{capture:!1})}}ki(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Ae(n)&&n>0?n:0}isDisabled(){return!!this.xi}bi(e){rv.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=[...Nm,...o];return k({},ue,{H(u){try{var c={};try{c=Qt.H(u)||{}}catch{}var d,f=JSON.parse(ue.P(u)||"{}");if(a){var p={};for(var h in c){var g=c[h];Qe(g)||g===""||(p[h]=g)}d=ge(f,p)}else d=ge(c,f);return ue.F(u,d),d}catch{}return null},F(u,c,d,f,p,h){var g=ue.F(u,c,void 0,void 0,h);try{var m={};l.forEach((v=>{c[v]&&(m[v]=c[v])})),Object.keys(m).length&&Qt.F(u,m,d,f,p,h)}catch(v){ue.j(v)}return g},q(u,c){try{E?.localStorage.removeItem(u),Qt.q(u,c)}catch(d){ue.j(d)}}})})(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),r=!1,s=e.persistence.toLowerCase();return s==="localstorage"&&ue.N()?(n=ue,r=!0):s==="localstorage+cookie"&&i.N()?(n=i,r=!0):s==="sessionstorage"&&xe.N()?n=xe:s==="memory"?n=Om: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 ae(this.props,((n,i)=>{var r=Fn(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=ge({},e)),this.pi&&this.Ci()}}Ci(){for(var e of Zo){var n=ue.H(this.Si(e));if(n&&!rn(n)){var i=this.Mi(e);i.persisted=!0,this.Ti(e)||(i.fingerprint=this.Ei(n,e)),this.Ii(e,n)||ge(this.props,n)}}}Ti(e){return Object.keys(this.props).some((n=>{var i;return((i=Fn(n))==null?void 0:i.storageGroup)===e}))}Ii(e,n){var i=iv[e];if(!i)return!1;var r=n[i],s=this.props[i];return Ae(r)&&Ae(s)&&s>r}refreshKey(e){var n;if(!this.xi){var i=this.pi?(n=Fn(e))==null?void 0:n.storageGroup:void 0,r=i?ue.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,ti))}Li(){var e=this.Di(),n=e.main,i=e.groups;for(var r of(this.Oi(this.ii,this.yi,n,ti),Zo)){var s,o=i[r];(!rn(o)||(s=this.ci[r])!=null&&s.persisted)&&this.Oi(ue,this.Si(r),o,r)}}Di(){var e={},n={flags:{},surveys:{}};return ae(this.props,((i,r)=>{var s,o=(s=Fn(r))==null?void 0:s.storageGroup;o?n[o][r]=i:e[r]=i})),{main:e,groups:n}}Ei(e,n){if(n===ti)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var i={};return ae(e,((r,s)=>{var o;i[s]=(o=Fn(s))!=null&&o.volatile?"__volatile__":r})),JSON.stringify(i)}Oi(e,n,i,r){var s=this.Mi(r);if(r===ti||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!==ti&&(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 Zo)ue.q(this.Si(r));i?delete this.ci[ti]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,n,i){if(me(e)){C(n)&&(n="None"),this.$i=C(i)?this.ji:i;var r=!1;if(ae(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(me(e)){this.$i=C(n)?this.ji:n;var i=!1;if(ae(e,((r,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==r||me(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=dh(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);rn(ql(n))||this.register(n),this.mi=e}}update_search_keyword(){var e;this.register((e=F?.referrer)?hh(e):{})}update_referrer_info(){var e;this.register_once({$referrer:ph(),$referring_domain:F!=null&&F.referrer&&((e=Ps(F.referrer))==null?void 0:e.host)||Fs},void 0)}set_initial_person_info(){this.props[Ha]||this.props[Wa]||this.register_once({[Es]:gh(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={};ae([Wa,Ha],(r=>{var s=this.props[r];s&&ae(s,(function(o,a){e["$initial_"+Sa(a)]=o}))}));var n=this.props[Es];if(n){var i=(function(r,s){s===void 0&&(s=!1);var o=mh(r,s),a={};return ae(o,(function(l,u){a["$initial_"+Sa(u)]=l})),a})(n,this.Ne.disable_capture_url_hashes);ge(e,i)}return e}safe_merge(e){return ae(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var r=e.persistence!==n.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every(((f,p)=>f===d[p]))})(e.cookie_persisted_properties||[],n.cookie_persisted_properties||[]),s=r?this.bi(e):this.ii,o=this.wi(e);if(r||o!==this.pi){var a=this.props;this.clear(),this.ii=s,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,n){var i=this.props[zi]||{};i[e]=n,this.Pi(zi,i),this.save()}remove_event_timer(e){var n=this.props[zi]||{},i=n[e];return C(i)||(delete n[e],this.Pi(zi,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=Fn(e))!=null&&i.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var n,i=(n=Fn(e))==null?void 0:n.storageGroup;i&&(this.Mi(i).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function qr(t){var e=!0;return{dispose(){if(e){e=!1;var n=t();n&&Ue(n.then)&&n.then(void 0,(()=>{}))}}}}var He={GZipJS:"gzip-js",Base64:"base64"},$i={Activation:"events",Cancellation:"cancelEvents"},Qo={Popover:"popover",API:"api",Widget:"widget"},en={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ea={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},Ka={Popover:"popover",Inline:"inline"},sv={SHOWN:"product tour shown"},Fu={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},Ru=ve("[RateLimiter]");class ov{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=>{Ru.info((r||"events")+" is quota limited."),this.serverLimits[r]=new Date().getTime()+6e4}))}catch(r){return void Ru.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(Ua))!==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=(Ae(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(Ua,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")&&_e!=null&&_e.pathname)return""+((e=_e.origin)!==null&&e!==void 0?e:"")+_e.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 mn.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void mn.warn("Remote config is disabled. Falling back to local config.");this.Wi((e=>{if(!e)return mn.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){mn.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||mn.warn("Failed to fetch remote config from PostHog."):mn.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(r){mn.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){mn.error("Error loading feature flags",r)}}}var pt=Uint8Array,Xe=Uint16Array,bi=Uint32Array,Kl=new pt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Yl=new pt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Tu=new pt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_h=function(t,e){for(var n=new Xe(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]},wh=_h(Kl,2),Ya=wh[1];wh[0][28]=258,Ya[258]=28;for(var Mu=_h(Yl,0)[1],bh=new Xe(32768),be=0;32768>be;++be){var ni=(43690&be)>>>1|(21845&be)<<1;bh[be]=((65280&(ni=(61680&(ni=(52428&ni)>>>2|(13107&ni)<<2))>>>4|(3855&ni)<<4))>>>8|(255&ni)<<8)>>>1}var ir=function(t,e,n){for(var i=t.length,r=0,s=new Xe(e);i>r;++r)++s[t[r]-1];var o,a=new Xe(e);for(r=0;e>r;++r)a[r]=a[r-1]+s[r-1]<<1;for(o=new Xe(i),r=0;i>r;++r)o[r]=bh[a[t[r]-1]++]>>>15-t[r];return o},Vn=new pt(288);for(be=0;144>be;++be)Vn[be]=8;for(be=144;256>be;++be)Vn[be]=9;for(be=256;280>be;++be)Vn[be]=7;for(be=280;288>be;++be)Vn[be]=8;var Rs=new pt(32);for(be=0;32>be;++be)Rs[be]=5;var av=ir(Vn,9),lv=ir(Rs,5),Eh=function(t){return(t/8>>0)+(7&t&&1)},Sh=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var i=new(t instanceof Xe?Xe:t instanceof bi?bi:pt)(n-e);return i.set(t.subarray(e,n)),i},qt=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8},Li=function(t,e,n){var i=e/8>>0;t[i]|=n<<=7&e,t[i+1]|=n>>>8,t[i+2]|=n>>>16},ta=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 pt(0),0];if(r==1){var o=new pt(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 p=new Xe(f+1),h=Ja(n[c-1],p,0);if(h>e){i=0;var g=0,m=h-e,v=1<i;++i){var b=s[i].s;if(e>=p[b])break;g+=v-(1<>>=m;g>0;){var w=s[i].s;e>p[w]?g-=1<=0&&g;--i){var _=s[i].s;p[_]==e&&(--p[_],++g)}h=e}return[new pt(p),h]},Ja=function(t,e,n){return t.s==-1?Math.max(Ja(t.l,e,n+1),Ja(t.r,e,n+1)):e[t.s]=n},$u=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Xe(++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]},Ni=function(t,e){for(var n=0,i=0;e.length>i;++i)n+=t[i]*e[i];return n},Za=function(t,e,n){var i=n.length,r=Eh(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)},Lu=function(t,e,n,i,r,s,o,a,l,u,c){qt(e,c++,n),++r[256];for(var d=ta(r,15),f=d[0],p=d[1],h=ta(s,15),g=h[0],m=h[1],v=$u(f),b=v[0],w=v[1],_=$u(g),x=_[0],I=_[1],T=new Xe(19),S=0;b.length>S;++S)T[31&b[S]]++;for(S=0;x.length>S;++S)T[31&x[S]]++;for(var P=ta(T,7),R=P[0],L=P[1],$=19;$>4&&!R[Tu[$-1]];--$);var O,J,G,M,K=u+5<<3,ie=Ni(r,Vn)+Ni(s,Rs)+o,B=Ni(r,f)+Ni(s,g)+o+14+3*$+Ni(T,R)+(2*T[16]+3*T[17]+7*T[18]);if(ie>=K&&B>=K)return Za(e,c,t.subarray(l,l+u));if(qt(e,c,1+(ie>B)),c+=2,ie>B){O=ir(f,p),J=f,G=ir(g,m),M=g;var X=ir(R,L);for(qt(e,c,w-257),qt(e,c+5,I-1),qt(e,c+10,$-4),c+=14,S=0;$>S;++S)qt(e,c+3*S,R[Tu[S]]);c+=3*$;for(var fe=[b,x],se=0;2>se;++se){var ee=fe[se];for(S=0;ee.length>S;++S)qt(e,c,X[Pe=31&ee[S]]),c+=R[Pe],Pe>15&&(qt(e,c,ee[S]>>>5&127),c+=ee[S]>>>12)}}else O=av,J=Vn,G=lv,M=Rs;for(S=0;a>S;++S)if(i[S]>255){var Pe;Li(e,c,O[257+(Pe=i[S]>>>18&31)]),c+=J[Pe+257],Pe>7&&(qt(e,c,i[S]>>>23&31),c+=Kl[Pe]);var ke=31&i[S];Li(e,c,G[ke]),c+=M[ke],ke>3&&(Li(e,c,i[S]>>>5&8191),c+=Yl[ke])}else Li(e,c,O[i[S]]),c+=J[i[S]];return Li(e,c,O[256]),c+J[256]},cv=new bi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),uv=(function(){for(var t=new bi(256),e=0;256>e;++e){for(var n=e,i=9;--i;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),na=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function dv(t,e){e===void 0&&(e={});var n=(function(){var d=4294967295;return{p(f){for(var p=d,h=0;f.length>h;++h)p=uv[255&p^f[h]]^p>>>8;d=p},d(){return 4294967295^d}}})(),i=t.length;n.p(t);var r,s,o,a,l,u=(a=10+((r=e).filename&&r.filename.length+1||0),l=8,(function(d,f,p,h,g,m){var v=d.length,b=new pt(h+v+5*(1+Math.floor(v/7e3))+g),w=b.subarray(h,b.length-g),_=0;if(!f||8>v)for(var x=0;v>=x;x+=65535){var I=x+65535;v>I?_=Za(w,_,d.subarray(x,I)):(w[x]=!0,_=Za(w,_,d.subarray(x,v)))}else{for(var T=cv[f-1],S=T>>>13,P=8191&T,R=(1<x;++x){var Pe=G(x),ke=32767&x,je=$[Pe];if(L[ke]=je,$[Pe]=ke,x>=se){var St=v-x;if((B>7e3||fe>24576)&&St>423){_=Lu(d,w,0,M,K,ie,X,fe,ee,x-ee,_),fe=B=X=0,ee=x;for(var ye=0;286>ye;++ye)K[ye]=0;for(ye=0;30>ye;++ye)ie[ye]=0}var et=2,xt=0,Cn=P,Le=ke-je&32767;if(St>2&&Pe==G(x-Le))for(var Re=Math.min(S,St)-1,Dt=Math.min(32767,x),Zn=Math.min(258,St);Dt>=Le&&--Cn&&ke!=je;){if(d[x+et]==d[x+et-Le]){for(var Ke=0;Zn>Ke&&d[x+Ke]==d[x+Ke-Le];++Ke);if(Ke>et){if(et=Ke,xt=Le,Ke>Re)break;var Xn=Math.min(Le,Ke-2),jt=0;for(ye=0;Xn>ye;++ye){var Ut=x-Le+ye+32768&32767,ut=Ut-L[Ut]+32768&32767;ut>jt&&(jt=ut,je=Ut)}}}Le+=(ke=je)-(je=L[ke])+32768&32767}if(xt){M[fe++]=268435456|Ya[et]<<18|Mu[xt];var Ht=31&Ya[et],Ai=31&Mu[xt];X+=Kl[Ht]+Yl[Ai],++K[257+Ht],++ie[Ai],se=x+et,++B}else M[fe++]=d[x],++K[d[x]]}}_=Lu(d,w,!0,M,K,ie,X,fe,ee,x-ee,_)}return Sh(b,0,h+Eh(_)+g)})(s=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),c=u.length;return(function(d,f){var p=f.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>f.level?4:f.level==9?2:0,d[9]=3,f.mtime!=0&&na(d,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),p){d[3]=8;for(var h=0;p.length>=h;++h)d[h+10]=p.charCodeAt(h)}})(u,e),na(u,c-8,n.d()),na(u,c-4,i),u}var fv=!!wa||!!Ml,xh="text/plain",is=!1,Ih=(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:"")},Qs=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("="),p=f[0],h=n&&(d=a[p])!==null&&d!==void 0?d:f[1];return delete a[p],p+"="+h})))!==null&&i!==void 0?i:[],u=(function(c,d){var f,p;d===void 0&&(d="&");var h=[];return ae(c,(function(g,m){C(g)||C(m)||m==="undefined"||(f=encodeURIComponent((v=>v instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(m),h[h.length]=p+"="+f)})),h.join(d)})(a);return u&&l.push(u),l.length>0?s+"?"+l.join("&"):s},ia=t=>{if(t.Ji)return t.Ji;var e=t.data,n=t.compression;if(e){if(n===He.GZipJS){var i=dv((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new pt(a.length+(a.length>>>1)),d=0,f=function(m){c[d++]=m},p=0;u>p;++p){if(d+5>c.length){var h=new pt(d+8+(u-p<<1));h.set(c),c=h}var g=a.charCodeAt(p);128>g?f(g):2048>g?(f(192|g>>>6),f(128|63&g)):g>55295&&57344>g?(f(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),f(128|g>>>12&63),f(128|g>>>6&63),f(128|63&g)):(f(224|g>>>12),f(128|g>>>6&63),f(128|63&g))}return Sh(c,0,d)})(ci(e)),{mtime:0});return{contentType:xh,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(n===He.Base64){var r=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(ci(e)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:ci(a)))(r);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=ci(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},kh=t=>{var e,n,i=()=>t.transport==="sendBeacon"?{url:Qs(t.url,{compression:He.Base64}),encodedBody:ia(k({},t,{compression:He.Base64,Ji:void 0}))}:{url:Ih(t.url,"compression"),encodedBody:ia(k({},t,{compression:void 0,Ji:void 0}))};try{e=ia(t)}catch(r){if(tu(t.compression,_i(t.url,"compression")))return A.error("Failed to gzip request body, sending uncompressed payload",r),i();throw r}return e&&tu(t.compression,_i(t.url,"compression"))&&!((n=e.body)instanceof ArrayBuffer?ba(new Uint8Array(n)):ArrayBuffer.isView(n)&&ba(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(is=!0,i()):{url:t.url,encodedBody:e}},Ch=t=>{try{return kh(t)}catch(e){return A.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},hv=(function(){var t=ce((function*(e){var n=ci(e.data),i=yield(function(s,o,a){return Ea.apply(this,arguments)})(n,oe.DEBUG,{rethrow:!0});if(!i)return e;var r=yield i.arrayBuffer();return k({},e,{Ji:{contentType:xh,body:r,estimatedSize:r.byteLength}})}));return function(e){return t.apply(this,arguments)}})(),pv=/Failed to fetch|NetworkError|Load failed/i,Ph=t=>t?.name==="TypeError"&&pv.test(t?.message||""),Ah=t=>{var e=Ch(t);if(e){var n=e.url,i=e.encodedBody,r=i??{},s=r.contentType,o=r.body,a=r.estimatedSize,l=new Headers;ae(t.headers,(function(h,g){l.append(g,h)})),s&&l.append("Content-Type",s);var u=null,c=!1;if(Yc){var d=new Yc;u={signal:d.signal,timeout:setTimeout((()=>{var h,g;c=!0,d.abort((h=t.timeout,(g=new Error("PostHog request timed out"+(h?" after "+h+"ms":""))).name="AbortError",g))}),t.timeout)}}var f=h=>{c&&h?.name==="AbortError"||Ph(h)?A.warn(h):A.error(h),t.callback==null||t.callback({statusCode:0,error:h})};try{var p;Ml(n,k({method:t?.method||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then((h=>h.text().then((g=>{var m={statusCode:h.status,text:g};if(h.status===200)try{m.json=JSON.parse(g)}catch(v){A.error(v)}t.callback==null||t.callback(m)})))).catch(f).finally((()=>u?clearTimeout(u.timeout):null))}catch(h){u&&clearTimeout(u.timeout),f(h)}}},Xa=t=>{try{var e,n=kh(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(qe.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 Xa(k({},t,{data:d(u.slice(0,c))})),void Xa(k({},t,{data:d(u.slice(c))}))}A.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Ah(k({},t,{Yi:!0}))}catch(f){A.warn("Beacon send failed",f)}},Nu=(t,e,n,i)=>{var r=i==="query"?e==="POST"?"sent_at":"_":void 0;return Qs(n===He.GZipJS?Ih(t,"compression"):t,k({},r?{[r]:Date.now().toString()}:{},n===He.GZipJS?{}:{compression:n}))},rs=[];Ml&&rs.push({transport:"fetch",method:Ah}),wa&&rs.push({transport:"XHR",method(t){var e=Ch(t);if(e){var n=new wa,i=e.encodedBody;n.open(t.method||"GET",e.url,!0);var r=i??{},s=r.contentType,o=r.body;ae(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)}}}),qe!=null&&qe.sendBeacon&&rs.push({transport:"sendBeacon",method:Xa});var Qa=3e3;class gv{constructor(e,n){this.Xi=!0,this.tr=[],this.er=Rt(n?.flush_interval_ms||Qa,250,5e3,A.createLogger("flush interval"),Qa),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)&&ae(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 ae(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 mv=["retriesPerformedSoFar"];class vv{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!C(E)&&"onLine"in E.navigator&&(this.dr=E.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},we(E,"online",this.vr),we(E,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var n=e.retriesPerformedSoFar,i=nf(e,mv);Vt(n)&&(i.url=Qs(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(E)||(this.vr&&(E.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(E.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 yv{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(){we(E,"scroll",this.yr,{capture:!0}),we(E,"scrollend",this.yr,{capture:!0}),we(E,"resize",this.yr)}scrollElement(){if(!this._r)return E?.document.documentElement;var e=U(this._r)?this._r:[this._r];for(var n of e){var i=E?.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 E?e==="y"?E.scrollY||E.pageYOffset||E.document.documentElement.scrollTop||0:E.scrollX||E.pageXOffset||E.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var _v=t=>gh(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties,t?.config.disable_capture_url_hashes);class Ou{constructor(e,n,i,r){this.kr=s=>{var o=this.Sr();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.Cr(this._instance)};this.Mr.register({[ja]:a})}},this._instance=e,this.Tr=n,this.Mr=i,this.Cr=r||_v,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[ja]}getSetOnceProps(){var e,n=(e=this.Sr())==null?void 0:e.props;return n?"r"in n?mh(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 ae(ql(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Sa(i)]=n})),e}}class Jl{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 Oi=ve("[SessionId]");class Bu{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 Jl,this.Lr=(u,c)=>!(!Vt(u)||!Vt(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===Xt)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||Yt,this.Nr=i||Yt;var s=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*Rt(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Oi.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=xe.H(this.jr),a=xe.H(this.Br);o&&!a?this.Or=o:xe.q(this.jr),xe.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){Oi.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&&xe.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&xe.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?xe.H(this.jr):null}Zr(e){var n=this.Pr;return!Qe(n)&&!Qe(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({[li]:[n,e,i]}))}Gr(){var e,n=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return Vt(n)&&n>0}Qr(){this.Gr()?this.Mr.refreshKey(li):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Qe(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({[li]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],n=Vt(e)?e:0,i=Vt(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[li];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&&E&&(E.removeEventListener(Is,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&xe.q(this.Br)},we(E,Is,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.Ne.cookieless_mode===Xt)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=Vt(o)&&Math.abs(i-o)>864e5,c=!1,d=!1,f=!s,p=s,h=!f&&!e&&this.Lr(i,a);if(h){(h=this.Xr(i))||Oi.info("cross-tab refresh kept the session alive",{sessionId:s});var g=this.Jr();s=g[1],o=g[2]}f||h||u?(s=this.$r(),l=this.Nr(),Oi.info("new session ID generated",{sessionId:s,windowId:l,changeReason:{noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u}}),o=i,c=!0):(l||(l=this.Nr(),c=!0),(d=s!==p)&&(Oi.info("adopted cross-tab session id",{sessionId:s,windowId:l}),c=!0));var m=Vt(a)&&e&&!u?a:i,v=Vt(o)?o:new Date().getTime();this.Wr(l),this.Ur(s,m,v),e||this.qr();var b={noSessionId:f,activityTimeout:h,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach((w=>w(s,l,b))),{sessionId:s,windowId:l,sessionStartTimestamp:v,changeReason:c?b:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout((()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()}),1.1*this.sessionTimeoutMs))}}var Fh=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&iu(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>iu(r?.brand,e))))return!0}catch{}return!!t.webdriver};function Rh(){return(Rh=ce((function*(){var t=qe?.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),n=e?.model;return Q(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 Ts=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 ra(t,e,n){return ci({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var Th={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=>Ts(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!Ts(n,i))))),icontains:(t,e)=>e.map(zr).some((n=>t.map(zr).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(zr).every((n=>t.map(zr).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 Mh(t,e){return!t||Object.entries(t).every((n=>{var i=n[1],r=e?.[n[0]];if(C(r)||Qe(r))return!1;var s=[String(r)],o=Th[i.operator];return!!o&&o(i.values,s)}))}var el="custom",Du="i.posthog.com",wv=/^\/static\//;class bv{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("."+Du,".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":el),this.en[this.apiHost]}rn(e){if(wv.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===el)return this.apiHost+n;var r=Du+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}function $h(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var te=ve("[Surveys]"),Lh="seenSurvey_",Nh=t=>{try{var e=(n=>((i,r)=>""+Lh+(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){te.error("Failed to persist survey seen state",n)}},Ev=[Qo.Popover,Qo.Widget,Qo.API],Sv={ignoreConditions:!1,ignoreDelay:!1,displayType:Ka.Popover},xv=ve("[PostHog ExternalIntegrations]"),Iv={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class kv{constructor(e){this._instance=e}ai(e,n){var i;(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return xv.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=N.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[l]||e.ai(Iv[l],(()=>{var c;(c=N.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)})),!u&&(o=N.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=N.__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 Cv{constructor(e,n){this.rt=e,this.nn=n,this.sn=new Map,this.an=!1}add(e){var n=this;return ce((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&&Ue(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 Pv{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 ju="extensionsRemoteConfig";class Av{constructor(e){this.an=!1,this.instance=e,this.rt=A,this.un=e.hn,this.kv=new Pv(e),this.onEvent=n=>qr(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 qr((()=>{}));var i=s=>{try{n(s)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},r=this.instance.dn.on(ju,i);return this.un&&i(this.un),qr(r)},this.vn=new Cv(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(ur))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(ur);return typeof e=="string"?e:void 0}get library(){return{name:oe.LIB_NAME,version:oe.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 ce((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 qr(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(ju,e))}sendRequest(e,n){var i=this;return ce((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?Qs(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 rr={},sa=0,Ms=()=>{},Uu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Bi="Surveys module not available",Hu="sanitize_properties is deprecated. Use before_send instead",Oh="Invalid value for property_denylist config: ",Fv=["token","distinct_id",qf],oi="posthog",Bh=!fv&&Je?.indexOf("MSIE")===-1&&Je?.indexOf("Mozilla")===-1,oa=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:Rm(F?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Ms,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:_e&&Q(_e?.search)&&_e.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:(E==null||(e=E.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:qa,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Qa},error_tracking:{},_onCapture:Ms},(n=>({rageclick:n&&n>="2026-05-30"?{content_ignorelist:Wm,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))},Rv=[["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"]],Wu=t=>{var e={};for(var n of Rv){var i=n[0],r=n[1];C(t[i])||(e[r]=t[i])}var s=ge({},e,t),o=t.__preview_external_dependency_versioned_paths;return C(o)||(C(t.strict_script_versioning)&&(s.strict_script_versioning=!!o),Q(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(Oh+t.property_denylist)),s};class Tv{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 tt{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===Xt||this.config.cookieless_mode===On&&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 Tv,this.mn=!1,this.version=oe.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Jl,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=oa(),this.SentryIntegration=Zm,this.sentryIntegration=i=>(function(r,s){var o=lh(r,s);return{name:ah,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 yv(this),this.pageViewManager=new Pu(this),this.rateLimiter=new ov(this),this.requestRouter=new bv(this),this.consent=new Bm(this),this.externalIntegrations=new kv(this);var n=(e=tt.__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=Q(i)?{[i]:r}:i;this.setPersonProperties(o),s?.({})},set_once:(i,r,s)=>{var o=Q(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!==oi){var r,s=(r=rr[i])!==null&&r!==void 0?r:new tt;return s._init(e,n,i),rr[i]=s,rr[oi][i]=s,s}return this._init(e,n,i)}_init(e,n,i){var r,s;n===void 0&&(n={});var o,a=Q(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=oa(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=oa(n.defaults),u=Wu(n),c=ge({},l,u,{name:i,token:a});me(l.rageclick)&&me(u.rageclick)&&(c.rageclick=ge({},l.rageclick,u.rageclick)),me(l.session_recording)&&me(u.session_recording)&&(c.session_recording=ge({},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:He.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&&xe.N()){var f=xe.H(this.bn);U(f)&&f.forEach((I=>{Q(I)&&this.yn.add(I)}))}else xe.q(this.bn);var p=k({},this.persistence.props),h=k({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new gv((I=>this.Pn(I)),this.config.request_queue_config),this.Rn=new vv(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new Bu(this),this.sessionPropsManager=new Ou(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((I,T,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.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)),oe.DEBUG=oe.DEBUG||this.config.debug,oe.DEBUG&&A.info("Starting in debug mode",{this:this,config:n,thisC:k({},this.config),p,s:h}),!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(),b=this.persistence.get_property(ft);if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===ei)this.identify(m);else if(n.bootstrap.isIdentifiedID&&v!=null&&v!==m&&b===Pn)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 w=this.config.get_device_id(Yt()),_=n.bootstrap.isIdentifiedID?w:m;this.persistence.set_property(ft,n.bootstrap.isIdentifiedID?Pn:ei),this.register({distinct_id:m,$device_id:_})}}if(g)this.register_once({distinct_id:Dr,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(Yt());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(ft,ei)}return we(E,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(I,T){var S=I.config.segment;if(!S)return T();(function(P,R){var L=P.config.segment;if(!L)return R();var $=J=>{var G=()=>J.anonymousId()||Yt();P.config.get_device_id=G,J.id()&&(P.register({distinct_id:J.id(),$device_id:G()}),P.persistence.set_property(ft,Pn)),R()},O=L.user();"then"in O&&Ue(O.then)?O.then($):$(O)})(I,(()=>{S.register((P=>{typeof Promise<"u"&&Promise.resolve||Jo.warn("This browser does not have Promise support, and can not use the segment integration");var R=(L,$)=>{if(!$)return L;L.event.userId||L.event.anonymousId===P.get_distinct_id()||(Jo.info("No userId set, resetting PostHog"),P.reset()),L.event.userId&&L.event.userId!==P.get_distinct_id()&&(Jo.info("UserId set, identifying with PostHog"),P.identify(L.event.userId));var O=P.calculateEventProperties($,L.event.properties);return L.event.properties=Object.assign({},O,L.event.properties),L};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:L=>R(L,L.event.event),page:L=>R(L,si),identify:L=>R(L,Go),screen:L=>R(L,"$screen")}})(I)).then((()=>{T()}))}))})(this,(()=>this.On())):this.On(),Ue(this.config._onCapture)&&this.config._onCapture!==Ms&&(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 Rh.apply(this,arguments)})().then((I=>{I&&this.register({[zo]:I})})).catch(Ms),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=tt.__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)),Ue(this.featureFlags.onReloading)&&Ue(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({},tt.__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,Jm)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach((f=>{f.initialize&&d.push((()=>{f.initialize==null||f.initialize()}))})),d.push((()=>{if(this.Nn){var f=this.Nn;this.Nn=void 0,this.sn.forEach((p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(f)))}})),this.qn(d,u)}qn(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.qn(e,n)}),0);var i=e.shift();if(i)try{i()}catch(s){A.error("Error initializing extension:",s)}}var r=Math.round(performance.now()-n);this.register_for_session({[zf]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Vf]: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,He.GZipJS)?He.GZipJS:j(r.supportedCompression,He.Base64)?He.Base64:void 0),(i=r.analytics)!=null&&i.endpoint&&(this.analyticsDefaultEndpoint=r.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:qa}),(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&&_e!=null&&_e.hostname){var e=_e.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 yh(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()&&jr(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(Vo),(i=this.logs)==null||i.flushLogs("sendBeacon"),(r=this.In)==null||r.unload(),(s=this.Rn)==null||s.unload()):this.zn()&&this.capture(Vo,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Bh?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=He.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((b=>k({},b,{sent_at:v}))):k({},m,{sent_at:v})})(o.data))),o.url=Nu(o.url,o.method,o.compression,o.timestampMode);var p=rs.filter((m=>!o.disableTransport||!m.transport||!o.disableTransport.includes(m.transport))),h=(r=(s=(function(m,v){for(var b=0;m.length>b;b++)if(m[b].transport===f)return m[b]})(p))==null?void 0:s.method)!==null&&r!==void 0?r:p[0].method;if(!h)throw new Error("No available transport method");var g=m=>{try{h(m)}catch(v){Ph(v)?A.warn(v):A.error(v),o.callback==null||o.callback({statusCode:0,error:v})}};f!=="sendBeacon"&&o.data&&o.compression===He.GZipJS&&Mg&&typeof Promise<"u"&&!is?hv(o).then((m=>{g(m)})).catch((m=>{if(nu(m))return is=!0,void g(k({},o,{compression:void 0,url:Nu(n.url,n.method,void 0,n.timestampMode)}));(v=>{if(!v||typeof v!="object")return!1;var b="name"in v?String(v.name):"";return nu(v)||b===rf})(m)&&(is=!0),g(o)})):h(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){sa++;try{var n,i=[],r=[],s=[];jr(e,(a=>{if(a)if(U(n=a[0]))s.push(a);else if(Ue(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&&Ue(this[n])?s.push(a):r.push(a)}));var o=function(a,l){jr(a,(function(u){try{if(U(u[0])){var c=l;ae(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{sa--}}push(e){if(sa>0&&U(e)&&Q(e[0])){var n=tt.prototype[e[0]];Ue(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)&&Q(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&&!Q(n?.$current_url)&&(A.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),e!=="$exception"||i!=null&&i.Wn||A.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,f=i?.timestamp||d,p=au(i?.uuid,Yt),h={uuid:p,event:e,properties:this.calculateEventProperties(e,n||{},f,p)};e===si&&this.config.__preview_capture_bot_pageviews&&u&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),c&&(h.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&h.properties.$feature_flag_has_experiment===!1&&this.get_property(ws)===!0;i?.$set&&!g&&(h.$set=i?.$set);var m=i?.$unset;m&&(h.$unset=m);var v,b,w,_=g?void 0:this.Vn(i?.$set_once,e!==hu,e===Go);if(_&&(h.$set_once=_),i!=null&&i._noTruncate||(s=this.config.properties_string_max_length,o=h,a=$=>Q($)?$.slice(0,s):$,l=new Set,h=(function $(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var G;if(l.add(O),U(O))G=[],jr(O,(K=>{G.push($(K))}));else{var M={};ae(O,((K,ie)=>{l.has(K)||(M[ie]=$(K))})),G=M}return G}})(o)),h.timestamp=f,C(i?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=d),g&&(h.properties=(function($,O){O===void 0&&(O=[]);var J={},G=M=>{$[M]!==void 0&&(J[M]=$[M])};return $g.forEach(G),O.forEach(G),J})(h.properties,Fv)),e===en.DISMISSED||e===en.SENT){var x=n?.[ea.SURVEY_ID],I=n?.[ea.SURVEY_ITERATION];Nh({id:x,current_iteration:I}),h.$set=k({},h.$set,{[(v={id:x,current_iteration:I},b=e===en.SENT?"responded":"dismissed",w="$survey_"+b+"/"+v.id,v.current_iteration&&v.current_iteration>0&&(w="$survey_"+b+"/"+v.id+"/"+v.current_iteration),w)]:!0})}else e===en.SHOWN&&(h.$set=k({},h.$set,{[ea.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===sv.SHOWN){var T=n?.[Fu.TOUR_TYPE];T&&(h.$set=k({},h.$set,{[Fu.TOUR_LAST_SEEN_DATE+"/"+T]:new Date().toISOString()}))}var S=k({},h.properties.$set,h.$set);if(rn(S)||this.setPersonPropertiesForFlags(S),!q(this.config.before_send)){var P=this.Pt(h);if(!P)return;(h=P).uuid=au(h.uuid,Yt)}this.dn.emit("eventCaptured",h);var R=(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),L={method:"POST",url:R,data:h,compression:"best-available",timestampMode:i?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(R)?"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(L):this.In.enqueue(L),h}A.critical("This capture call is ignored due to client rate limiting.")}}else A.error("No event name provided to posthog.capture")}else A.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(n=>e(n.event,n)))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Av(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[qf]=!0),e==="$snapshot"){var l=k({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!Q(a.distinct_id)&&!Ae(a.distinct_id)||xa(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,S){var P,R,L,$;if(S===void 0&&(S=!1),!Je)return{};var O,J=x?[...wi,...I||[]]:[],G=(function(Zn){for(var Ke=0;su.length>Ke;Ke++){var Xn=su[Ke],jt=Xn[1],Ut=Xn[0].exec(Zn),ut=Ut&&(Ue(jt)?jt(Ut,Zn):jt);if(ut)return ut}return["",""]})(Je),M=G[0],K=G[1],ie=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},B={};C(T)||(B.detectGoogleSearchApp=T);var X={},fe=(P=navigator)==null||(P=P.userAgentData)==null?void 0:P.platform,se=(R=navigator)==null?void 0:R.maxTouchPoints,ee=E==null||(L=E.screen)==null?void 0:L.width,Pe=E==null||($=E.screen)==null?void 0:$.height,ke=E?.devicePixelRatio;C(fe)||(X.userAgentDataPlatform=fe),C(se)||(X.maxTouchPoints=se),C(ee)||(X.screenWidth=ee),C(Pe)||(X.screenHeight=Pe),C(ke)||(X.devicePixelRatio=ke);var je,St,ye,et,xt,Cn,Le,Re,Dt=ge(ql({$os:M,$os_version:K,$browser:Af(Je,navigator.vendor,ie,B),$device:ou(Je),$device_type:(St=Je,ye=X,Re=ou(St),Re===df||Re===uf||Re==="Kobo"||Re==="Kindle Fire"||Re===xf?mi:Re===lr||Re===fi||Re===cr||Re===ka?"Console":Re===hf?"Wearable":Re?lt:ye?.userAgentDataPlatform==="Android"&&((et=ye?.maxTouchPoints)!==null&&et!==void 0?et:0)>0?600>Math.min((xt=ye?.screenWidth)!==null&&xt!==void 0?xt:0,(Cn=ye?.screenHeight)!==null&&Cn!==void 0?Cn:0)/((Le=ye?.devicePixelRatio)!==null&&Le!==void 0?Le:1)?lt:mi:"Desktop"),$timezone:vh(),$timezone_offset:nv()}),{$current_url:fr(S?wn(_e?.href):_e?.href,J,hr),$host:_e?.host,$pathname:_e?.pathname,$raw_user_agent:Je.length>1e3?Je.substring(0,997)+"...":Je,$browser_version:Qg(Je,navigator.vendor,ie,B),$browser_language:Au(),$browser_language_prefix:(je=Au(),typeof je=="string"?je.split("-")[0]:void 0),$screen_height:E?.screen.height,$screen_width:E?.screen.width,$viewport_height:E?.innerHeight,$viewport_width:E?.innerWidth,$lib:oe.LIB_NAME,$lib_version:oe.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return oe.SDK_DIST_CHANNEL&&(Dt.$sdk_dist_channel=oe.SDK_DIST_CHANNEL),Dt})(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&&ge(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ge(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===el&&(a.$lib_custom_api_host=this.config.api_host),u=e!==si||s?e!==Vo||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),a=ge(a,u),e===si&&F&&(a.title=F.title),!C(o)){var h=i.getTime()-o;a.$duration=parseFloat((h/1e3).toFixed(3))}Je&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),m=this.sessionPersistence.properties();ae(["$referrer","$referring_domain"],(x=>{x in g&&delete m[x]}));var v={};if(this._n.length>0)for(var b of this._n.slice())try{ge(v,b())}catch(x){A.error("Failed to produce browser extension event properties",x)}(a=ge({},c,g,m,k({},v,a))).$is_identified=this._isIdentified(),U(this.config.property_denylist)?ae(this.config.property_denylist,(function(x){delete a[x]})):A.error(Oh+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(A.error(Hu),a=w(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=ge({},s,o||{},e||{}),l=this.config.sanitize_properties;return l&&(A.error(Hu),a=l(a,"$set_once")),n&&(this.mn=!0),rn(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||!xe.N())xe.q(this.bn);else{var n=[];this.yn.forEach((i=>n.push(i))),n.length>0?xe.F(this.bn,n):xe.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:Bi}),()=>{})}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:Bi})}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,n):e([],{isLoaded:!1,error:Bi})}renderSurvey(e,n){var i;(i=this.surveys)==null||i.renderSurvey(e,n)}displaySurvey(e,n){var i;n===void 0&&(n=Sv),(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:Bi}}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:Bi})}Jn(e){return!e||xa(e)?(A.critical("Unique user id has not been set in posthog.identify"),!1):e===Dr?(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(Ae(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(ur)||this.register_once({$had_persisted_distinct_id:!0,$device_id:r},""),e!==r&&e!==this.get_property(qi)&&(this.unregister(qi),this.register({distinct_id:e}));var s,o=(this.persistence.get_property(ft)||ei)===ei,a=e!==r,l=!a&&o;if(a&&o)this.persistence.set_property(ft,Pn),this.setPersonPropertiesForFlags({$set:n||{},$set_once:i||{}},!1),this.capture(Go,{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Sn=ra(e,n,i),(s=this.featureFlags)==null||s.setAnonymousDistinctId(r);else if(l){this.persistence.set_property(ft,Pn);var u=n||{},c=i||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=ra(e,n,i)}else(n||i)&&this.setPersonProperties(n,i);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Bn)):l&&(n||i)&&this.reloadFeatureFlags()}}setPersonProperties(e,n){if((e||n)&&this.Gn("posthog.setPersonProperties")){var i=ra(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=>Q(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(hu,o)}i&&this.setGroupPropertiesForFlags({[e]:i}),s&&!i&&this.reloadFeatureFlags()}else A.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),(i=this.featureFlags)==null||i.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(e){var n;e===void 0&&(e=!0),(n=this.featureFlags)==null||n.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,n){var i;n===void 0&&(n=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((i=this.featureFlags)==null||i.setGroupPropertiesForFlags(e,n))}resetGroupPropertiesForFlags(e){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,n){var i,r,s,o,a,l,u,c,d,f;if(n===void 0&&(n=!1),A.info("reset"),!this.__loaded)return A.uninitializedWarning("posthog.reset");var p,h=this.get_property(ur),g=this.get_property(zo),m=this.get_property(jn),v=this.is_capturing();if(this.consent.reset(),n||!v||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(i=this.persistence)==null||i.clear(),(r=this.sessionPersistence)==null||r.clear(),this.yn.clear(),this.Qn(),C(m)||(p=this.persistence)==null||p.register({[jn]: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(ft,ei),(f=this.sessionManager)==null||f.resetSessionId(),this.Sn=null,this.config.cookieless_mode===Xt)this.register_once({distinct_id:Dr,$device_id:null},"");else{var b=this.config.get_device_id(Yt());this.register_once({distinct_id:b,$device_id:e?b:h},""),e||C(g)||this.register({[zo]: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 ce((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(Bf)?(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(qi,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(me(e)){var i,r,s,o,a,l,u,c,d,f,p,h;ge(this.config,Wu(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);wt(m)&&(this.config.debug=m),wt(this.config.debug)&&(this.config.debug?(oe.DEBUG=!0,ue.N()&&ue.F("ph_debug",!0),A.info("set_config",{config:e,oldConfig:n,newConfig:k({},this.config)})):(oe.DEBUG=!1,ue.N()&&ue.q("ph_debug"))),(r=this.featureFlags)==null||r.updateConfig==null||r.updateConfig(this.config,this.Qi()),(s=this.exceptionObserver)==null||s.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(h=this.externalIntegrations)==null||h.startIfEnabledOrStop()}}_overrideSDKInfo(e,n){oe.LIB_NAME=e,oe.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:tt.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:oi;return n!==oi&&(n=oi+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ft))===Pn||((n=this.sessionPersistence)==null?void 0:n.get_property(ft))===Pn}Zn(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===qa&&!this._isIdentified()&&rn(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[qi])&&((n=this.persistence)==null||(n=n.props)==null||!n[Ss]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(A.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(Ss,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==On)}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!==Xt){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 Bu(this),this.pageViewManager=new Pu(this),this.persistence&&(this.sessionPropsManager=new Ou(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=tt.__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==On&&((c=this.surveys)==null||c.loadIfEnabled()),(C(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e?.captureEventName)!==null&&d!==void 0?d:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else A.warn(Uu)}opt_out_capturing(){var e,n,i;this.config.cookieless_mode!==Xt?(this.config.cookieless_mode===On&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===On&&(this.register({distinct_id:Dr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):A.warn(Uu)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Xt||(this.config.cookieless_mode===On?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return qe?Fh(qe,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(si,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(xs,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),we(F,xs,this.kn)))}debug(e){e===!1?(E?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(E?.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&&!q(n[i]),l=r in n&&!q(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(q(this.config.before_send))return e;var i=Object.keys((n=e.properties)!==null&&n!==void 0?n:{}).filter(Ug),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),q(s)){var a="Event '"+e.event+"' was rejected in beforeSend function";return jg(e.event)?A.warn(a+". This can cause unexpected behavior."):A.info(a),null}s.properties&&!rn(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&&q(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=wt(e)&&!e,i=ue.N()&&ue.P("ph_debug")==="true";return!n&&(!!i||e)}}tt.__defaultExtensionClasses={},tt.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]]=Am(t.prototype[e[n]])})(tt,["identify"]);class qu{constructor(e){this.disabled=e===!1;var n=me(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 aa="$copy_autocapture",la=ve("[AutoCapture]");function ca(t,e){return e.length>t?e.slice(0,t)+"...":e}function Mv(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!bn(e));return e}function $v(t,e){var n,i,r=e.e,s=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!bn(t))return{props:{}};for(var c=[t],d=new Set([t]),f=t;f.parentNode&&!rt(f,"body")&&eh>c.length;)if(Qf(f.parentNode)){var p=f.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),f=p}else{if(!bn(f.parentNode)||d.has(f.parentNode))break;d.add(f.parentNode),c.push(f.parentNode),f=f.parentNode}var h,g,m=[],v={},b=!1,w=!1;if(ae(c,(S=>{var P=Ga(S);if(rt(S,"a")){var R=S.getAttribute("href");b=!!(P&&R&&nr(R))&&(u?wn(R):R)}j(Cs(S),"ph-no-capture")&&(w=!0),m.push((function($,O,J,G,M){M===void 0&&(M=!1);var K=$.tagName.toLowerCase(),ie={tag_name:K};Vl.indexOf(K)>-1&&!J&&(ie.$el_text=K.toLowerCase()==="a"||K.toLowerCase()==="button"?ca(1024,Iu($)):ca(1024,dr($)));var B=Cs($);B.length>0&&(ie.classes=B.filter((function(ee){return ee!==""}))),ae($.attributes,(function(ee){var Pe;if((!sh($)||["name","id","class","aria-label"].indexOf(ee.name)!==-1)&&(G==null||!G.includes(ee.name))&&!O&&nr(ee.value)&&(!Q(Pe=ee.name)||Pe.substring(0,10)!=="_ngcontent"&&Pe.substring(0,7)!=="_nghost")){var ke=ee.value;ee.name==="class"&&(ke=zl(ke).join(" ")),ie["attr__"+ee.name]=ca(1024,ee.name==="href"&&M?wn(ke):ke)}}));for(var X=1,fe=1,se=$;se=Mv(se);)X++,se.tagName===$.tagName&&fe++;return ie.nth_child=X,ie.nth_of_type=fe,ie})(S,s,o,a,u));var L=(function($){if(!Ga($))return{};var O={};return ae($.attributes,(function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var G=J.name.replace("data-ph-capture-attribute-",""),M=J.value;G&&M&&nr(M)&&(O[G]=M)}})),O})(S);ge(v,L)})),w)return{props:{},explicitNoCapture:w};if(o||(m[0].$el_text=rt(t,"a")||rt(t,"button")?Iu(t):dr(t)),b){var _,x;m[0].attr__href=b;var I=(_=Ps(b))==null?void 0:_.host,T=E==null||(x=E.location)==null?void 0:x.host;I&&T&&I!==T&&(h=b)}return{props:ge({$event_type:r.type,$ce_version:1},l?{}:{$elements:m},{$elements_chain:(g=m,(function(S){return S.map((P=>{var R,L,$="";if(P.tag_name&&($+=P.tag_name),P.attr_class)for(var O of(P.attr_class.sort(),P.attr_class))$+="."+O.replace(/"/g,"");var J=k({},P.text?{text:P.text}:{},{"nth-child":(R=P.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(L=P.nth_of_type)!==null&&L!==void 0?L:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),G={};return ns(J).sort(((M,K)=>M[0].localeCompare(K[0]))).forEach((M=>{var K=M[1];return G[ku(M[0].toString())]=ku(K.toString())})),($+=":")+ns(G).map((M=>M[0]+'="'+M[1]+'"')).join("")})).join(";")})((function(S){return S.map((P=>{var R,L,$={text:(R=P.$el_text)==null?void 0:R.slice(0,400),tag_name:P.tag_name,href:(L=P.attr__href)==null?void 0:L.slice(0,2048),attr_class:Km(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return ns(P).filter((O=>O[0].indexOf("attr__")===0)).forEach((O=>$.attributes[O[0]]=O[1])),$}))})(g)))},(n=m[0])!=null&&n.$el_text?{$el_text:(i=m[0])==null?void 0:i.$el_text}:{},h&&r.type==="click"?{$external_click_url:h}:{},v)}}var Di=ve("[ExceptionAutocapture]"),zu=()=>{},Lv=ve("[TracingHeaders]"),Rn=ve("[Web Vitals]"),Vu=9e5,Gu="disabled",Ku="lazy_loading",ji="awaiting_config",Vr="missing_config";ve("[SessionRecording]"),ve("[SessionRecording]");var tl="[SessionRecording]",zt=ve(tl),Nv=ve("[Heatmaps]");function ua(t){return me(t)&&"clientX"in t&&"clientY"in t&&Ae(t.clientX)&&Ae(t.clientY)}var Gr=ve("[Product Tours]"),da=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Ul))},Ov=["$set_once","$set"],It=ve("[SiteApps]"),Yu="Error while initializing PostHog app with config id ";function ii(t,e,n){if(q(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 Bv{constructor(e){this.ns=new Jl,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"||!ii(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=>ii(a.href,n.href,n.href_matching||"exact")));var s,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&ii((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=>ii(u.text,n.text,n.text_matching||"exact")||ii(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;!q(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=>ii(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||Mh(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 Dv{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&&Mh(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===$i.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 Bv(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,$i.Activation),this.ks=this.Ps(e,$i.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,$i.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,$i.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&&(rn(i)?this.Es():this.Ts(i))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var n=this.Qs()[e];return Ae(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=>Ae(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 jv extends Dv{constructor(e){super(e)}Js(){return Da}Ys(){return Qr}Ms(){return es}Ts(e){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[es]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(es)}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 Ae(r)&&r>0}ra(){return en.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 te}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({[Qr]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Qr)}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 $h(s)&&!((o=s.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||s.schedule==="always"})(i);return r?e===en.SHOWN?"consume":"ignore":e===en.SHOWN?"persist":e===en.DISMISSED||e===en.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Kr="SDK is not enabled or survey functionality is not yet loaded",Ju="Disabled. Not loading surveys.",Uv=E!=null&&E.location?As(E.location.hash,"__posthog")||As(location.hash,"state"):null,Zu="_postHogToolbarParams",Xu=ve("[Toolbar]"),Qu=ve("[FeatureFlags]");class Hv{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||(Qu.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)||Qu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var ed=ve("[FeatureFlags]"),Tn=ve("[FeatureFlags]",{debugEnabled:!0}),fa=`" failed. Feature flags didn't load in time.`,td="connection_error",nd=t=>{for(var e={},n=0;t.length>n;n++)e[t[n]]=!0;return e},id=t=>{var e={};for(var n of ns(t||{})){var i=n[1];i&&(e[n[0]]=i)}return e},kt=ve("[Error tracking]"),rd="Refusing to render web experiment since the viewer is a likely bot",Wv={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>Ts(e,t),not_regex:(t,e)=>!Ts(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class Oe{get Ne(){return this._instance.config}constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{Oe.aa("retrieved web experiments from the server"),n.oa=new Map,r.forEach((s=>{if(s.feature_flag_key){var o;n.oa&&(Oe.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);Q(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];Oe.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())Oe.aa(rd);else if(!this.Ne.disable_web_experiments){if(q(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Oe.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=Oe.getWindowLocation();if(e!=null&&e.search){var n=_i(e?.search,"__experiment_id"),i=_i(e?.search,"__experiment_variant");n&&i&&(Oe.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&&(Oe.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!q(e.conditions)&&Oe.da(e,n)&&Oe.va(e)}static da(e,n){var i;if(q(e.conditions)||q((i=e.conditions)==null?void 0:i.url))return!0;var r=Oe.getWindowLocation();if(r){var s,o,a,l=Jf(n,r.href);return(s=e.conditions)==null||!s.url||Wv[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return E?.location}static va(e){var n;if(q(e.conditions)||q((n=e.conditions)==null?void 0:n.utm))return!0;var i=dh();if(i.utm_source){var r,s,o,a,l,u,c,d,f=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==i.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==i.utm_source,h=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==i.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==i.utm_term;return f&&h&&g&&p}return!1}static aa(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;n>r;r++)i[r-1]=arguments[r];A.info("[WebExperiments] "+e,i)}la(e,n,i){this._is_bot()?Oe.aa(rd):n!=="control"?i.forEach((r=>{if(r.selector){var s;Oe.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)}))}})):Oe.aa("Control variants leave the page unmodified.")}_is_bot(){return qe&&this._instance?Fh(qe,this.Ne.custom_blocked_useragents):void 0}}var dt=ve("[Conversations]"),Mn="Conversations not available yet.",sd="console",Dh="__posthogHandledLogsRequestError",ha=(t,e)=>{var n=t instanceof Error?t:new Error(e);return n[Dh]=!0,n},od=t=>!!t&&typeof t=="object"&&t[Dh]===!0,eo={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=ed,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 Hv(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 E&&we(E,"online",this.Ca),this.Ra=t.registerDynamicEventProperties((()=>this.Aa()?this.fa:this.pa)),this.Fa(),this.initialize()}destroy(){E?.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=[],E?.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[Vi,Gi,Xr,Pt]){var n=this.Oa(e);C(n)||(t[e]=n)}this.fa=t;var i=k({},t),r=this.Oa($n);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(tr);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($n))!==null&&i!==void 0?i:{},o=n!=null&&n.merge&&(r=this.Oa(Gi))!==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:Xc(f),variant:Qc(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(Oa),e=this.Oa(Pt),n=this.Oa(Ln);if(!n&&!e)return t||{};var i=ge({},t||{}),r=[...new Set([...Object.keys(n||{}),...Object.keys(e||{})])];for(var s of r){var o,a,l=i[s],u=e?.[s],c=C(u)?(o=l?.enabled)!==null&&o!==void 0&&o:!!u,d=C(u)?l?.variant:typeof u=="string"?u:void 0,f=n?.[s],p=k({},l,{enabled:c,variant:c?d??l?.variant:void 0});c!==l?.enabled&&(p.original_enabled=l?.enabled),d!==l?.variant&&(p.original_variant=l?.variant),f&&(p.metadata=k({},l?.metadata,{payload:f,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),i[s]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:n,finalDetails:i}),this.ca=!0),i}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map((n=>{var i=t[n];return{key:n,enabled:Xc(i),variant:Qc(i),payload:Zc(e[n])}}))}getFlagVariants(){var t=this.Oa($n),e=this.Oa(Pt);if(!e)return t||{};for(var n=ge({},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(Gi),e=this.Oa(Ln);if(!e)return t||{};for(var n=ge({},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(Bn)}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(Gt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Nn),timezone:vh()};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({[ts]:[td]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:n,compression:this.Ne.compression==="base64"?He.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then((c=>{var d,f,p=(d=c.json)!==null&&d!==void 0?d:{},h=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),h||this.wa||(this.$anon_distinct_id=void 0),!n.disable_flags||this.wa){this.ka=!h;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?td:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var m=!((f=p.quotaLimited)==null||!f.includes("feature_flags"));m&&g.push("quota_limited"),this.F({[ts]:g}),m?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):n.disable_flags||this.ja(p,h,{partialResponse:s}),l()}}else l()})).catch(u)}catch(c){u(c)}}}Ma(){return ch(this.Sa,3)}Ua(t){this.Sa=uh(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+fa)}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(Xr)||void 0,u=this.Oa(tr)||void 0,c=this.Oa(Bn)||{};if(this.Ne.deduplicateCallsPerSession){var d,f=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Yi);f&&f!==p&&(c={},n=f)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))n&&this.F({[Bn]:c,[Yi]:n});else{var h,g,m,v,b,w,_,x,I,T;U(c[t])?c[t].push(a):c[t]=[a],this.F(k({[Bn]:c},n?{[Yi]:n}:{}));var S=this.getFeatureFlagDetails(t),P=[...(h=this.Oa(ts))!==null&&h!==void 0?h:[]];C(s)&&P.push("flag_missing");var R={$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(S==null||(v=S.metadata)==null?void 0:v.has_experiment)||(R.$feature_flag_has_experiment=S.metadata.has_experiment),C(S==null||(b=S.metadata)==null?void 0:b.version)||(R.$feature_flag_version=S.metadata.version);var L,$=(w=S==null||(_=S.reason)==null?void 0:_.description)!==null&&w!==void 0?w:S==null||(x=S.reason)==null?void 0:x.code;$&&(R.$feature_flag_reason=$),S!=null&&(I=S.metadata)!=null&&I.id&&(R.$feature_flag_id=S.metadata.id),C(S?.original_variant)&&C(S?.original_enabled)||(R.$feature_flag_original_response=C(S.original_variant)?S.original_enabled:S.original_variant),S!=null&&(T=S.metadata)!=null&&T.original_payload&&(R.$feature_flag_original_payload=S==null||(L=S.metadata)==null?void 0:L.original_payload),P.length&&(R.$feature_flag_error=P.join(",")),this.za(R)}else n&&this.F({[Bn]:c,[Yi]:n});if(r)return{key:t,enabled:!!s,variant:typeof s=="string"?s:void 0,payload:Zc(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+fa)}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 ce((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"?He.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+fa),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=ed);var c=((I,T)=>{var S=I.flags;return S?k({},I,{featureFlags:Object.fromEntries(Object.keys(S).map((P=>{var R;return[P,(R=S[P].variant)!==null&&R!==void 0?R:S[P].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(S).filter((P=>S[P].enabled)).filter((P=>{var R;return(R=S[P].metadata)==null?void 0:R.payload})).map((P=>{var R;return[P,(R=S[P].metadata)==null?void 0:R.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,p=c.featureFlagPayloads;if(f){var h=r.requestId,g=r.evaluatedAt;if(U(f)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var m={};if(f)for(var v=0;f.length>v;v++)m[f[v]]=!0;return{[Vi]:f,[$n]:m,[ws]:!1}}var b=f,w=p,_=d;if(l!=null&&l.partialResponse)b=k({},s,b),w=k({},o,w),_=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)})));b=k({},s,Object.fromEntries(Object.entries(b).filter((I=>x.has(I[0]))))),w=k({},o,Object.fromEntries(Object.entries(w||{}).filter((I=>x.has(I[0]))))),_=k({},a,Object.fromEntries(Object.entries(_||{}).filter((I=>x.has(I[0])))))}else b=k({},s,b),w=k({},o,w),_=k({},a,_);return k({[Vi]:Object.keys(id(b)),[$n]:b||{},[Gi]:w||{},[Oa]:_||{},[ws]:r.minimalFlagCalledEvents===!0},h?{[Xr]:h}:{},g?{[tr]: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([Pt,Ln]),this.Va(),void Tn.info("All overrides cleared");if(U(t))return this.F({[Pt]:nd(t)}),this.Va(),void Tn.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[Pt]=U(r)?nd(r):r),s&&(i[Ln]=s),Object.keys(i).length&&this.F(i),r===!1&&s===!1?this.q([Pt,Ln]):r===!1?this.q(Pt):s===!1&&this.q(Ln),this.Va(),r===!1?Tn.info("Flag overrides cleared"):r&&Tn.info("Flag overrides set",{flags:r}),void(s===!1?Tn.info("Payload overrides cleared"):s&&Tn.info("Payload overrides set",{payloads:s}))}if(t&&typeof t=="object")return this.F({[Pt]:t}),this.Va(),void Tn.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(Zr)||[]).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({[Vi]:Object.keys(id(o)),[$n]:o,[Gt]:k({},this.Oa(Gt)||{},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(Zr);!i||e?this.Qa(t,n):t(i)}Qa(t,e){var n=this;return ce((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({[Zr]: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(Gt)||{},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({[Gt]:k({},n,s,i)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=k({},this.Oa(Gt)||{});t.forEach((i=>{delete n[i]})),this.F({[Gt]:n}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(Gt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var n=this.Oa(Nn)||{},i=k({},n);for(var r of Object.keys(t))i[r]=k({},n[r],t[r]);this.F({[Nn]:i}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Nn)||{};this.F({[Nn]:k({},e,{[t]:{}})})}else this.q(Nn)}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}}},qv={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===ji||this.Ya===Vr?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=Gu,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var n=E==null||(e=E.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 zt.error("started without valid sessionManager"),new Error(tl+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===Xt)throw new Error(tl+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&we(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(jn))==null||!t.enabled),n=!this.Ne.disable_session_recording,i=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return E&&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),zt.info("starting")):(this.Ya=Gu,this.stopRecording())}}no(t){var e,n,i;this.ro&&(this.Ya!==ji&&this.Ya!==Vr&&(this.Ya=Ku),N!=null&&(e=N.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(n=N.__PosthogExtensions__)!=null&&n.initSessionRecording?this.so(t):(i=N.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.ao,(r=>{if(r)return zt.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(Hl),(e=this.Mr)==null||e.unregister(Df)}uo(t,e){if(q(t))return null;var n,i=Ae(t)?t:parseFloat(t);return typeof(n=i)!="number"||!Number.isFinite(n)||0>n||n>1?(zt.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;q(u)&&this.lo();var c=o?.minimumDurationMilliseconds;i.register({[jn]: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===ji&&(this.Ya=Vr,zt.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):zt.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(jn);return(n==null||(e=n.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(jn);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(n){return zt.warn("persisted remote config for session recording is invalid and will be ignored",n),!1}return!q(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,n,i;if(!this.eo){if((e=N.__PosthogExtensions__)==null||!e.initSessionRecording)return zt.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Gf]:!0});var r;if(this.Ja||(this.Ja=(r=N.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===Vr||this.Ya===ji?void 0:(this.Ya=ji,zt.info("persisted remote config is stale, requesting fresh config before starting"),void new yh(this._instance).load());this.Ya=Ku,(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({[Uf]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[jf]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,n;this.Ja||(n=this.Mr)==null||n.register({[t==="url"?Hf:Wf]:!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))}}},zv={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new qu(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,n=me(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(E&&F){var t=n=>{n=n||E?.event;try{this.bo(n)}catch(i){la.error("Failed to capture event",i)}};if(we(F,"submit",t,{capture:!0}),we(F,"change",t,{capture:!0}),we(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=n=>{n=n||E?.event;try{this.bo(n,aa)}catch(i){la.error("Failed to capture copy/cut event",i)}};we(F,"copy",e,{capture:!0}),we(F,"cut",e,{capture:!0})}}}else la.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;wt(n)&&(this.instance.persistence&&this.instance.persistence.register({[Fa]: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[Fa],i=this.co,r=this.instance.Qi()&&!this.fo;if(Qe(i)&&!wt(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=Yo(t);Xf(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())&&wu(i,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var r=e===aa;if(i&&(function(d,f,p,h,g,m){var v;if(!E||Gl(d)||p!=null&&p.url_allowlist&&!vu(p.url_allowlist,m)||p!=null&&p.url_ignorelist&&vu(p.url_ignorelist,m))return!1;if(p!=null&&p.dom_event_allowlist){var b=p.dom_event_allowlist;if(b&&!b.some((S=>f.type===S)))return!1}var w=rh(d,h),_=w.parentIsUsefulElement,x=w.targetElementList;if(!(function(S,P){var R=P?.element_allowlist;if(C(R))return!0;var L,$=function(J){if(R.some((G=>J.tagName.toLowerCase()===G)))return{v:!0}};for(var O of S)if(L=$(O))return L.v;return!1})(x,p)||!Va(x,p?.css_selector_allowlist)||Va(x,(v=p?.css_selector_ignorelist)!==null&&v!==void 0?v:Hm))return!1;try{var I=E.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&&(Vl.indexOf(T)>-1||d.getAttribute("contenteditable")==="true")}})(i,t,this.Ne,r,r?["copy","cut"]:void 0,this.instance)){var s=$v(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===aa){var l,u=th(E==null||(l=E.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 Ue(F?.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(E==null||(e=E.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(){E&&E.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(E&&((e=E.history[t])==null||!e.__posthog_wrapped__)){var n=this;(function(i,r,s){try{if(!(r in i))return zu;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 Ue(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];Ue(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 zu}})(E.history,t,(i=>function(r,s,o){i.call(this,r,s,o),n.So(t)}))}}So(t){try{var e,n=E==null||(e=E.location)==null?void 0:e.pathname;if(!n)return;n!==this._o&&this.isEnabled&&this._instance.capture(si,{navigation_type:t}),this._o=n}catch(i){A.error("Error capturing "+t+" pageview",i)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};we(E,"popstate",t),this.wo=()=>{E&&E.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[Ra]),this.rageclicks=new qu(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return me(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return q(this.Ne.capture_heatmaps)?q(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Nv.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({[Ra]:n}),this.Co=n,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){ua(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(){E&&F&&(this.Po=this.cr.bind(this),we(E,Is,this.Po),this.Ro=t=>this.ke(t||E?.event),we(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||E?.event),we(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new Cu(this.instance,Ym,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),we(F,xs,this.Oo),this.vo=!0)}Eo(){var t;E&&F&&(this.Po&&E.removeEventListener(Is,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(xs,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&&bn(u)&&!rt(u,"body");){if(u===l)return!1;var c=void 0;try{var d,f,p;c=(d=(f=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&f!==void 0?f:E)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(j(a,c))return!0;u=nh(u)}return!1})(Yo(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"),!mu(t.target)&&ua(t)){var i=this.$o(t,e);(n=this.rageclicks)!=null&&n.isRageClick(t.clientX,t.clientY,new Date().getTime())&&wu(Yo(t),this.instance.config.rageclick)&&this.Vt(k({},i,{type:"rageclick"})),this.Vt(i)}}Fo(t){!mu(t.target)&&ua(t)&&(clearTimeout(this.Do),this.Do=setTimeout((()=>{this.Vt(this.$o(t,"mousemove"))}),500))}Vt(t){if(E){var e=this.Ne.disable_capture_url_hashes?wn(E.location.href):E.location.href,n=this.Ne.custom_personal_data_properties,i=this.Ne.mask_personal_data_properties?[...wi,...n||[]]:[],r=fr(e,i,hr);this.R=this.R||{},this.R[r]||(this.R[r]=[]),this.R[r].push(t)}}cr(){this.R&&!rn(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:Cu,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},q(n?.name)||q(n?.value))Rn.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=Ae(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 Rn.error("Ignoring metric with value >= "+this.Ho,n)}}},this.Uo=()=>{if(!this.vo){var n,i,r,s,o=N.__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 Rn.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[La]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,n=me(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return q(n)?((e=this._instance.persistence)==null?void 0:e.props[Na])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(me(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=me(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=me(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=me(this.Wo)&&Ae(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Vu;return t>0&&6e4>=t?Vu:t}get isEnabled(){var t=_e?.protocol;if(t!=="http:"&&t!=="https:")return Rn.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=me(this.Wo)?this.Wo.web_vitals:wt(this.Wo)?this.Wo:void 0;return wt(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Rn.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var n=me(e.capturePerformance)&&!!e.capturePerformance.web_vitals,i=me(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[La]:n}),this._instance.persistence.register({[Na]: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=N.__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?Rn.error("failed to load script",r):t()}))}Bo(t){var e=t||E?.location.href;if(e){var n=this._instance.config.disable_capture_url_hashes?wn(e):e,i=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...wi,...i||[]]:[];return fr(n,r,hr)}Rn.error("Could not determine current URL")}}},Vv={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var n;if(E&&this.isEnabled&&(n=N.__PosthogExtensions__)!=null&&n.errorWrappingFunctions){var i=N.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,r=N.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=N.__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){Di.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Ta]),this.Jo=new qg(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:Di})),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 me(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?(Di.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return Di.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({[Ta]: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)?Di.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 am([new gm,new xm,new vm,new mm,new Em,new bm,new _m,new Sm],(function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;r>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var f=c[d];if(1024>=f.length){var p=fu.test(f)?f.replace(fu,"$1"):f;if(!p.match(/\S*Error: /)){for(var h of s){var g=h(p,i);if(g){u.push(g);break}}if(u.length>=50)break}}}return(function(m){if(!m.length)return[];var v=Array.from(m);return v.reverse(),v.slice(0,50).map((b=>{return k({},b,{filename:b.filename||(w=v,w[w.length-1]||{}).filename,function:b.function||yi});var w}))})(u)}})("web:javascript",dm,pm)),this._instance=t,this.Xo=(e=(n=this._instance.persistence)==null?void 0:n.get_property(Ma))!==null&&e!==void 0?e:[],this.el=_s(this.il()),this.rl=new km(this.el)}onConfigChange(){this.el=_s(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({[Ma]:this.Xo,[$a]:o})}}}get nl(){var t,e=!!this._instance.get_property($a),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(!Q(t)||t.trim().length===0)return void kt.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)=>Im.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&&kt.warn("Ignoring reserved exception step fields",{droppedKeys:r}),this.rl.add(k({[vs]:t,[ys]:new Date().toISOString()},i))}catch(s){kt.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 kt.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 kt.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 kt.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.el.enabled&&q(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 kt.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void kt.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 kt.error("Failed to read buffered exception steps. Capturing exception without steps.",n),t}}ll(t){this.el.enabled&&this.rl.add({[vs]:t,[ys]:new Date().toISOString()})}sl(t){return me(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 Q(r)&&r.length>0&&n.$exception_types.push(r),Q(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=Th[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 kt.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!q(t)&&U(t)}}},Gv=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({[Ul]:!!e.productTours}),!da(this._instance))return!this.vl&&q((n=this.Mr)==null?void 0:n.props[Ki])||Gr.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&&da(this._instance)&&this.ai((()=>this.fl()))}ai(t){var e,n;(e=N.__PosthogExtensions__)!=null&&e.generateProductTours?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(i=>{i?Gr.error("Could not load product tours script",i):t()}))}fl(){var t;!this.vl&&(t=N.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=N.__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[Ki];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(da(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||Gr.warn(o):Gr.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({[Ki]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){q(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(Ki)}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)}}},eo),Kv={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=N._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,n,i,r,s,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var f=d[0];l[f]={id:u[f],type:f,properties:d[1]}}var p=t.$set_once,h=t.$set;return{event:k({},nf(t,Ov),{properties:k({},t.properties,h?{$set:k({},(e=(n=t.properties)==null?void 0:n.$set)!==null&&e!==void 0?e:{},h)}:{},p?{$set_once:k({},(i=(r=t.properties)==null?void 0:r.$set_once)!==null&&i!==void 0?i:{},p)}:{}),elements_chain:(s=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,n=(e=t.tagName)==null?void 0:e.toLowerCase();return n==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(It.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)||(It.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,p=(m,v,b)=>{if(m!=null&&m[v]){var w=m[v];m[v]=b(w),c.push((()=>{m[v]=w}))}},h=m=>{if(f.has(m))return m;var v=d.bl(m);return v&&f.add(v),v},g=m=>m.map((v=>typeof v=="string"?v:h(v))).filter((v=>!Qe(v)));return p(u,"appendChild",(m=>function(v){var b=h(v);return b?m.call(this,b):v})),p(u,"insertBefore",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):v})),p(u,"replaceChild",(m=>function(v,b){var w=h(v);return w?m.call(this,w,b):b})),[(e=l.Element)==null?void 0:e.prototype,(n=l.Document)==null?void 0:n.prototype,(i=l.DocumentFragment)==null?void 0:i.prototype].forEach((m=>{p(m,"append",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"prepend",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))}))})),[(r=l.Element)==null?void 0:r.prototype,(s=l.CharacterData)==null?void 0:s.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach((m=>{p(m,"before",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"after",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];return v.apply(this,g(w))})),p(m,"replaceWith",(v=>function(){for(var b=arguments.length,w=new Array(b),_=0;b>_;_++)w[_]=arguments[_];var x=g(w);return w.length&&!x.length?void 0:v.apply(this,x)}))})),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",(m=>function(v,b){var w=h(b);return w?m.call(this,v,w):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&&(It.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,It.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){It.error(Yu+t.id,o),r(!1)}if(i&&e.loaded)try{n()}catch(o){It.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){It.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 It.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;N["__$$ph_site_app_"+u]=r._instance,(l=N.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(r._instance,c,(d=>{if(d)return It.error(Yu+u,d)}))};for(var a of s.siteApps)o()}else It.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},Yv={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=N.__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=N.__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=N.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(n=N.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return Lv.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()}}},Jv=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 te.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(q(e))return te.warn("Flags not loaded yet. Not loading surveys.");var n=U(e);this.Rl=n?e.length>0:e,te.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)te.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)te.info(Ju);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())te.info("Not loading surveys in cookieless mode without consent.");else{var t=N?.__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(Wl);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 te.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new jv(this._instance),te.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){te.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 te.info(Ju),t([]);var n,i=this._instance.get_property(Ba);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?te.error(a):r.error||te.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(n==null||n({surveys:[],context:l}))}this.Ol=null;var u,c=r.json.surveys||[],d=c.filter((p=>(function(h){return!(!h.start_date||h.end_date)})(p)&&($h(p)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(p))));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(s=this._instance.persistence)==null||s.register({[Ba]:c,[bs]: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(bs);return Ae(t)&&Date.now()-t>3e5}Bl(){return Ae(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};Nh(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){te.error("Error in survey callback",n)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!q(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);te.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(q(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(q(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(q(this._surveyManager))return te.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 q(this._surveyManager)?(te.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(q(this._surveyManager))te.warn("init was not called");else{var r=typeof t=="string"?this.Hl(t):t;if(r!=null&&r.id)if(Ev.includes(r.type)){var s=F?.querySelector(e);if(s)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(te.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;te.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),te.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,s,n);te.warn("Survey element not found")}else te.warn("Surveys of type "+r.type+" cannot be rendered in the app");else te.warn("Survey not found")}}displaySurvey(t,e){var n;if(q(this._surveyManager))te.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!==Ka.Popover&&e.initialResponses&&te.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 te.warn("Survey is not eligible to be displayed: ",s.reason)}e.displayType!==Ka.Inline?this._surveyManager.handlePopoverSurvey(r,e):this.renderSurvey(r,e.selector,e.properties)}else te.warn("Survey not found")}}cancelPendingSurvey(t){q(this._surveyManager)?te.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},eo),Zv={toolbar:class{constructor(t){this.instance=t}Wl(t){N.ph_toolbar_state=t}Vl(){var t;return(t=N.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),za(this.instance.config)||!E||!F)return!1;t=t??E.location,n=n??E.history;try{if(!e){try{E.localStorage.setItem("test","test"),E.localStorage.removeItem("test")}catch{return!1}e=E?.localStorage}var i,r=Uv||As(t.hash,"__posthog")||As(t.hash,"state"),s=r?pu((()=>JSON.parse(atob(decodeURIComponent(r)))))||pu((()=>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(Zu)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token||(this.loadToolbar(i),0))}catch{return!1}}Zl(t){var e=N.ph_load_toolbar||N.ph_load_editor;!q(e)&&Ue(e)?e(t,this.instance):Xu.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(Zf));if(!E||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(E.localStorage.setItem(Zu,JSON.stringify(k({},i,{source:void 0}))),this.Vl()===2)this.Zl(i);else if(this.Vl()===0){var r;this.Wl(1),(r=N.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return Xu.error("[Toolbar] Failed to load",s),void this.Wl(0);this.Wl(2),this.Zl(i)})),we(E,"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)}}},Xv=k({experiments:Oe},eo),Qv={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;q(e)||(wt(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||za(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=N?.__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(Wl);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 dt.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,dt.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else dt.error("Cannot complete initialization: remote config is null")}eu(t,e){dt.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():dt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Qe(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":za(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?q(this.Jl)||!this.Jl.token?"missing_token":N!=null&&N.__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 ce((function*(){return i._conversationsManager?i._conversationsManager.sendMessage(t,e,n):(dt.warn(Mn),null)}))()}getMessages(t,e){var n=this;return ce((function*(){return n._conversationsManager?n._conversationsManager.getMessages(t,e):(dt.warn(Mn),null)}))()}markAsRead(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(dt.warn(Mn),null)}))()}getTickets(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(dt.warn(Mn),null)}))()}requestRestoreLink(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(dt.warn(Mn),null)}))()}restoreFromToken(t){var e=this;return ce((function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(dt.warn(Mn),null)}))()}restoreFromUrlToken(){var t=this;return ce((function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(dt.warn(Mn),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()}}},ey={logs:class{constructor(t){var e,n=this;this.iu=!1,this.ru=!1,this.rt=ve("[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(od)||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),E&&we(E,"online",this.au)}uu(t,e,n,i){var r,s=(function(o,a){var l,u,c,d,f,p,h,g=(l=o?.flushIntervalMs)!==null&&l!==void 0?l:3e3,m=(u=o?.maxBufferSize)!==null&&u!==void 0?u:100,v=a!=null&&a.consoleCapture?void 0:(c=o?.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,b=C(v)?Math.max(m,2048):Math.max(m,v),w=o?.resourceAttributes;return{serviceName:(d=(f=w?.["service.name"])!==null&&f!==void 0?f:o?.serviceName)!==null&&d!==void 0?d:a?.serviceNameDefault,serviceVersion:(p=w?.["service.version"])!==null&&p!==void 0?p:o?.serviceVersion,environment:(h=w?.["deployment.environment"])!==null&&h!==void 0?h:o?.environment,resourceAttributes:w,beforeSend:o?.beforeSend,flushIntervalMs:g,maxBufferSize:m,maxQueueSize:b,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 rm(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},sd);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;!q(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){od(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=N?.__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(Wl)}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===Kt.LogsQueue?t():void 0,setPersistedProperty(i,r){var s;i===Kt.LogsQueue&&e((s=r)!==null&&s!==void 0?s:[])},Ot:i=>this.Ot(i),getLibraryId:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.LIB_VERSION}}Ot(t){return new Promise((e=>{if(ch(this.Sa,3))e({kind:"fatal",error:ha(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:ha(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:ha(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=uh(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,oe.LIB_NAME,(e=>{this.tr=e})),this.su.length>0&&this.xu(t,this.su,this.mu,sd,(e=>{this.su=e}))}xu(t,e,n,i,r){if(e.length!==0){var s=e.map((a=>a.record));r([]);var o=$f(s,Mf(n,oe.LIB_NAME,oe.LIB_VERSION),i,oe.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,q(r)||(e.sessionStartTimestamp=r),q(s)||(e.lastActivityTimestamp=s)}if(N!=null&&(t=N.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?wn(N.location.href):N.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},ty={metrics:class{constructor(t){this.rt=ve("[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 sm(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:()=>oe.LIB_NAME,getLibraryVersion:()=>oe.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)}}},ny=k({},eo,qv,zv,Vv,Gv,Kv,Jv,Yv,Zv,Xv,Qv,ey,ty);tt.__defaultExtensionClasses=k({},ny);var jh=(function(){oe.SDK_DIST_CHANNEL="npm";var t=rr[oi]=new tt;return(function(){function e(){e.done||(e.done=!0,Bh=!1,ae(rr,(function(n){n._dom_loaded()})))}F!=null&&F.addEventListener?F.readyState==="complete"?e():we(F,"DOMContentLoaded",e,{capture:!1}):E&&A.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),t})();const iy=["a[href]","button:not([disabled])","input:not([disabled]):not([type='hidden'])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(",");let nt=null,$s=null,Uh="";const nl=new Map;function Hh(t){return[...t.querySelectorAll(iy)].filter(e=>!e.hidden&&e.getAttribute("aria-hidden")!=="true"&&e.getClientRects().length>0)}function ry(t){for(const n of document.body.children)n===t||n.tagName==="SCRIPT"||(nl.set(n,{inert:n.inert,ariaHidden:n.getAttribute("aria-hidden")}),n.inert=!0,n.setAttribute("aria-hidden","true"));const e=document.activeElement;e&&e!==document.body&&!t.contains(e)&&e.blur()}function sy(){for(const[t,e]of nl)t.inert=e.inert,e.ariaHidden===null?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden",e.ariaHidden);nl.clear()}function Wh(t){return t?.dataset.modalDismissible!=="false"&&t?.getAttribute("aria-busy")!=="true"}function Ve(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n)return!1;const i=nt&&nt!==n?nt:null,r=$s;if(i&&Ge(i,{restoreFocus:!1,force:!0}),nt!==n){let a=e.trigger||document.activeElement;a&&(i?.contains(a)||n.contains(a))&&(a=r),$s=a,Uh=document.body.style.overflow,ry(n),document.body.style.overflow="hidden"}nt=n,n.classList.add("open"),n.setAttribute("aria-hidden","false");const s=n.querySelector(".modal-content");s&&(s.style.transform="scale(1) translateY(0)");const o=()=>{if(nt!==n)return;((e.initialFocus?n.querySelector(e.initialFocus):n.querySelector("[data-modal-initial-focus]"))||Hh(n)[0]||n.querySelector(".modal-content")||n).focus({preventScroll:!0})};return requestAnimationFrame(o),setTimeout(o,260),!0}function Ge(t,e={}){const n=typeof t=="string"?document.getElementById(t):t;if(!n||!e.force&&!Wh(n))return!1;if(n.classList.remove("open"),n.setAttribute("aria-hidden","true"),n!==nt)return!0;sy(),document.body.style.overflow=Uh,nt=null;const i=$s;return $s=null,e.restoreFocus!==!1&&i?.isConnected&&i.focus({preventScroll:!0}),!0}function ad(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 oy(t){if(!Wh(t))return;const e=t.dataset.modalCloseHandler;e&&typeof window[e]=="function"?window[e]():Ge(t)}document.addEventListener("keydown",t=>{if(!nt)return;if(t.key==="Escape"){t.preventDefault(),t.stopImmediatePropagation(),oy(nt);return}if(t.key!=="Tab"){t.stopPropagation();return}const e=Hh(nt);if(!e.length){t.preventDefault(),(nt.querySelector(".modal-content")||nt).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 ay(){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 Zl=Object.freeze({free:"Free",professional:"Pro",power:"Power"}),ly=Object.freeze({free:2,professional:50,power:2e3}),cy="(contact us)",uy=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 ${cy}`])}),qh="CodeFile",zh="GeneratedCode",dy={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function vn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function il(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function fy(t={},e=0){const n=il(t.artifactType||t.type||qh),i=il(t.artifactName||t.name||t.fileName||`${zh}-${e+1}`);return`${n||"artifact"}-${i||e+1}`}function Vh(t={},e=0){const n=vn(t),i=n.artifactType||n.type||qh,r=n.artifactName||n.name||zh;let s=n.fileName||r;return s.endsWith(".dart")||(s+=".dart"),{id:il(n.id)||fy({...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:Gh(n.dependencies),imports:Array.isArray(n.imports)?n.imports:[],publicApi:Array.isArray(n.publicApi)?n.publicApi:[],relationships:Kh(n.relationships),deployStatus:n.deployStatus||"pending",review:n.review||null,metadata:vn(n.metadata),codeType:n.codeType||dy[i]||"O"}}function Gh(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const n=vn(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(vn(t)).map(([e,n])=>({name:e,version:n||null,inferred:!1})):[]}function Kh(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const n=vn(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 rl(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 pr(t,e={}){const n=[],i=typeof t=="string"?rl(t):t,s=vn(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)=>Vh(d,f)),l=new Map(o.map((d,f)=>[vn(d).id,a[f]?.id]).filter(([d,f])=>d&&f)),u=d=>l.get(d)||d,c=Kh(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:Gh(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:vn(s.metadata)}}function Ei(t){return pr(t).artifacts[0]||Vh()}function an(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function Si(t){return JSON.stringify(t,null,2)}function hy(t){return Si({task:"architect",userRequest:String(t??"")})}function py(t){const e=an(t);return e&&typeof e=="object"&&typeof e.task=="string"?Si(e):Si({task:"generate_bundle",bundleSpec:e})}function gy(t){return Si({task:"review_bundle",generatedBundle:an(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 Xl(t,e=null){const n={stage:t};return e!=null&&(n.bundle=an(e)),n}function my({bundleSpec:t,artifactBundle:e,bundleReview:n,artifactId:i,userFeedback:r}){return Si({task:"regenerate_artifact",artifactId:i,bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(r)})}function Yh({bundleSpec:t,artifactBundle:e,bundleReview:n,userFeedback:i}){return Si({task:"regenerate_bundle",bundleSpec:an(t),artifactBundle:an(e),bundleReview:an(n),userFeedback:String(i??"")})}const ld={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"},vy=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function st(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yy(t){return st(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||st(t.filterSummary)||st(t.filterResults):!1}function Jh(t,e=0){if(!st(t)||e>3)return null;if(yy(t))return t;for(const n of vy){const i=t[n];if(st(i)){const r=Jh(i,e+1);if(r)return r}}return null}function Ls(t){return Array.isArray(t)?t.some(Ls):st(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(Ls):!1}function sl(t){return Array.isArray(t)?t.some(sl):st(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(sl):!1}function Zh(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function _y(t,e){if(st(t))for(const[n,i]of Object.entries(t)){if(!st(i))continue;const r=st(i.categories)?i.categories:{},s=Object.entries(r).filter(([,o])=>st(o)&&o.matched===!0).map(([o])=>o);s.length>0?s.forEach(o=>e.add(o)):i.matched===!0&&e.add(Zh(n))}}function wy(t,e){if(!t)return;const n=Array.isArray(t)?t.flatMap(i=>st(i)?Object.entries(i):[]):Object.entries(t);for(const[i,r]of n){if(!Ls(r))continue;const s=Zh(i),o=r?.raiFilterResult?.raiFilterTypeResults||(s==="rai"?r?.raiFilterTypeResults:null),a=st(o)?Object.entries(o).filter(([,l])=>Ls(l)).map(([l])=>l):[];a.length>0?a.forEach(l=>e.add(l)):e.add(s)}}function by(t){return ld[t]?ld[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function cd(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 Ey(t){const e=Jh(t);if(!e)return null;const n=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);_y(e.filterSummary,n),wy(e.filterResults,n);const i=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||n.size>0,r=e.invocationResult||null,s=sl(e.filterSummary||e.filterResults);return!i&&!s&&!["PARTIAL","FAILURE"].includes(r)?null:{kind:i?"blocked":"unavailable",invocationResult:r,matchedFilters:[...n]}}function Sy(t,e){const n=Ey(t);if(!n)return null;const i=[...new Set(n.matchedFilters.map(by))],r=n.kind==="blocked",s=new Error(r?`Safety screening blocked this pipeline step for ${cd(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 ${cd(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 xy(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function ud(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,n=[];for(const i of xy(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 Ql(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 dd(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 Iy(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=Ql(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await dd(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await dd(c)),n[o]=u,a.type==="F"){const d=ud(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>i.add(p))}}const r=new Set(ud(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 ky=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),fd={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Cy=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Py=["Struct","Record"],Ay=[{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=>pa(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=>pa(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,31 +24,31 @@ 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 Ct(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function mr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Ry(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;rTy(t).usable);function $y(t=""){const e=mr(t);return My.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Ly(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=Fy(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rhd(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function to(t=""){return Array.from(mr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Ny(t="",e=""){return ec(t,e)?.returnType||null}function pd(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 Oy(t,e){const n=to(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>pd(l)===r)||n.length>1)return null;const[o]=n,a=`${pd(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 tc(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function By(t,e,n=""){const i=ec(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Ql(r,"A");if(s===i)return null;const o=`${tc(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 Dy(t="",e=""){return ec(t,e)!==null}function jy(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Cy.has(i)?!1:!Py.some(s=>i.endsWith(s))||e.has(i))}function Uy(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Ny(t,e),r=jy(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 Hy(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(ky.has(t.artifactType)||n.push(Ct(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(Ct(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(Ct(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(Ct(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of $y(r))n.push(Ct(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Dy(r,t.artifactName)&&n.push(Ct(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(to(r)),o=Uy(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(Ct(t,"error",o));const a=By(i,r,t.artifactName);a&&n.push(Ct(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(Ct(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Oy(i,r);s&&n.push(Ct(t,"info",s))}return n}function Wy(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>to(s.code||""))),i=e.flatMap(s=>Hy(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:fd[s.artifactType]||fd.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const gd="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function md(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function qy(t=""){const e=t.indexOf(gd);return e===-1?t:t.slice(e+gd.length).replace(/^\s*\n/,"")}const zy=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Vy(t="",e=""){const n=qy(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(md).filter(Boolean)),r=n.split(` +class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Ct(t,e,n){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:n}}function gr(t){let e="",n=0;for(;n"&&(n--,n===0))return{inner:t.slice(e+1,i),end:i+1};return null}function Ry(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;rTy(t).usable);function $y(t=""){const e=gr(t);return My.filter(n=>n.detect(e)).map(({id:n,severity:i,message:r})=>({id:n,severity:i,message:r}))}function Ly(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=Fy(t,r);if(!u||(s=u.inner.replace(/\s+/g," ").trim(),r=u.end,!/\s/.test(t[r]||"")))continue;for(;rhd(o.functionName)===i);if(r)return r;const s=o=>!o.functionName.startsWith("_");return n.find(s)||n[0]}function to(t=""){return Array.from(gr(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Ny(t="",e=""){return ec(t,e)?.returnType||null}function pd(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 Oy(t,e){const n=to(e);if(n.length===0)return null;const r=String(t||"").split("/").pop().replace(/\.dart$/,"");if(n.some(l=>pd(l)===r)||n.length>1)return null;const[o]=n,a=`${pd(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 tc(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function By(t,e,n=""){const i=ec(e,n)?.functionName;if(!i)return null;const r=String(t||"").split("/").pop(),s=Ql(r,"A");if(s===i)return null;const o=`${tc(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 Dy(t="",e=""){return ec(t,e)!==null}function jy(t,e=new Set){return(t?.match(/[A-Za-z_]\w*/g)||[]).filter(i=>Cy.has(i)?!1:!Py.some(s=>i.endsWith(s))||e.has(i))}function Uy(t,{functionName:e="",declaredTypes:n=new Set}={}){const i=Ny(t,e),r=jy(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 Hy(t,e={}){const n=[],i=t.fileName||"",r=t.code||"";if(ky.has(t.artifactType)||n.push(Ct(t,"error",`Unsupported artifact type "${t.artifactType}".`)),i.endsWith(".dart")||n.push(Ct(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!r.trim())return n.push(Ct(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(Ct(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const s of $y(r))n.push(Ct(t,s.severity,s.message))}if(t.artifactType==="CustomAction"&&!Dy(r,t.artifactName)&&n.push(Ct(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const s=e.declaredTypes||new Set(to(r)),o=Uy(r,{functionName:t.artifactName,declaredTypes:s});o&&n.push(Ct(t,"error",o));const a=By(i,r,t.artifactName);a&&n.push(Ct(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(r)&&n.push(Ct(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const s=Oy(i,r);s&&n.push(Ct(t,"info",s))}return n}function Wy(t){const e=Array.isArray(t?.artifacts)?t.artifacts:[],n=new Set(e.flatMap(s=>to(s.code||""))),i=e.flatMap(s=>Hy(s,{declaredTypes:n})),r=e.map(s=>({artifactId:s.id,fileName:s.fileName,pathHint:fd[s.artifactType]||fd.CodeFile}));return{valid:i.every(s=>s.severity!=="error"),findings:i,deployHints:r}}const gd="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function md(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function qy(t=""){const e=t.indexOf(gd);return e===-1?t:t.slice(e+gd.length).replace(/^\s*\n/,"")}const zy=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function Vy(t="",e=""){const n=qy(t),i=new Set((e.match(/^\s*import .*$/gm)||[]).map(md).filter(Boolean)),r=n.split(` `).filter(s=>{const o=md(s);return o===null||!i.has(o)?!0:!zy.test(s)}).join(` `).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+r}const Gy=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations","flutter_web_plugins","integration_test","sky_engine"]);function Ky(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(p=>p.id)).map(p=>n.find(h=>h.id===p)).filter(Boolean),s=[...t?.warnings||[]];let o=[];r.forEach(p=>{const h=e_(p),g=p.fixedCode||p.code||"",m=p.codeType||Xy[p.artifactType]||it.OTHER;g.trim()||s.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:h,content:g,type:m,path:p.deployPath||Qy(h,m),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,h)=>({entry:p,index:h})).filter(({entry:p})=>p.type===it.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],h={...p.entry,artifactId:l.map(({entry:m})=>m.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:m})=>`// ${m.artifactId} ${m.content}`).join(` `)},g=new Set(l.slice(1).map(({index:m})=>m));o=o.filter((m,v)=>!g.has(v)),o[p.index]=h}const u={...vd(t?.dependencies),...r.reduce((p,h)=>({...p,...vd(h.dependencies)}),{})},c={};r.forEach(p=>{nc(p.fixedCode||p.code||"").forEach(h=>{h in u||(c[h]="")})});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=new Map){const n=[],i=[];for(const r of t)(e.has(r.path)?n:i).push(r);return{landed:n,notLanded:i}}function ol(t,e){const n=new Set(e.map(i=>i.path));return new Map(Array.from(t.entries()).filter(([,i])=>!n.has(i.path)))}function l_(t){return t?t.notLanded.length===0&&t.landed.length>0:!1}function c_(t,e,n){const i=ol(t,e),r=new Map(i);return r.set("pubspec.yaml",{content:n,type:"D",path:"pubspec.yaml"}),r}const yd={pass:0,warning:1,fail:2},u_=["manualActions"];function ct(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function tn(...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 At(t){return t==null?[]:Array.isArray(t)?t:[t]}function d_(t){const e=ct(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return _d(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?_d(Number(i[1])):null}function _d(t){return t>=0&&t<=100?t:null}function ht(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ic(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 al(...t){return t.filter(Boolean).reduce((e,n)=>yd[n]>yd[e]?n:e,"pass")}function tp(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ct(t),r=tn(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:ic(i.severity||i.status||i.level)||e,message:r,suggestion:tn(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function ll(t,e="review"){const n=ct(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>At(n[r]).map(o=>tp(o,s,e)).filter(Boolean))}function f_(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=ct(t),r=tn(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:tn(i.detail,i.instructions,i.description),location:tn(i.location,i.flutterFlowPath,i.path),timing:tn(i.timing,i.phase)||"unspecified",artifactId:n,source:tn(i.source)||"Code Review"}:null}function cl(t,e=null){const n=ct(t);return u_.flatMap(i=>At(n[i])).map((i,r)=>f_(i,r,e)).filter(Boolean)}function h_(t){let e=typeof t=="string"?rl(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ct(e);typeof n.content=="string"&&(e=rl(n.content)||e);const i=ct(e),r=ct(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function p_(t,e){const n=[e.id,e.fileName,e.artifactName].map(ht);return t.find(i=>{const r=ct(i);return[r.id,r.fileName,r.artifactName,r.name].map(ht).some(s=>s&&n.includes(s))})||null}function g_(t,e){return At(t?.metadata?.compatibility?.deployHints).find(r=>ht(r?.artifactId)===ht(e.id)||ht(r?.fileName)===ht(e.fileName))?.pathHint||""}function m_(t,e){return At(t?.relationships).filter(n=>ht(n?.from)===ht(e.id)||ht(n?.to)===ht(e.id))}function v_(t,e){return At(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ht(n.artifactId)===ht(e.id)).map(n=>tp(n,"warning","Compatibility check")).filter(Boolean)}function y_(t,e,n,i){const r=p_(e,n),s=ct(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...ll(s),...v_(t,n)],l=cl(s,n.id),u=ic(s.status||s.verdict||s.outcome||s.result),c=a.length?al(...a.map(f=>f.severity)):null,d=al(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?tn(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:g_(t,n),relationships:m_(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 w_({bundle:t,reviewResult:e}){const n=ct(t),i=At(n.artifacts),{root:r,rawText:s}=h_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ct).find(w=>Object.keys(w).length)||{},a=At(r.artifacts||r.files||r.reviews),l=i.map((w,_)=>y_(n,a,w,_)),u=ll(r),d=[...ll(o),...u],f=[...cl(o),...cl(r),...l.flatMap(w=>w.manualSteps)].filter((w,_,x)=>x.findIndex(I=>I.title===w.title&&I.artifactId===w.artifactId)===_),p=ic(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=al(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??r.score??r.overallScore??s,m=d_(g),v=tn(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:h,score:m,artifactPresentations:l,manualSteps:f}),b=l.reduce((w,_)=>(w[_.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:At(n.deployOrder),relationships:At(n.relationships),warnings:At(n.warnings),compatibility:ct(n.metadata?.compatibility)}}const b_="x-ff-api-key",wd="dr_",E_=/^[A-Za-z0-9_-]{1,120}$/;function S_(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`${wd}${t.randomUUID()}`;if(t&&typeof t.getRandomValues=="function"){const e=t.getRandomValues(new Uint8Array(16));return`${wd}${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}return null}function x_(t){return typeof t=="string"&&E_.test(t)}function I_(t,e){return`${String(t).replace(/\/deployCustomClasses$/,"")}/runStatus/${encodeURIComponent(e)}`}function k_(t){if(!t||typeof t!="object")return null;const{status:e}=t;return e!=="running"&&e!=="done"&&e!=="failed"?null:{status:e,phase:typeof t.phase=="string"?t.phase:"",message:typeof t.message=="string"?t.message:"",error:typeof t.error=="string"?t.error:null,deployed:Array.isArray(t.deployed)?t.deployed:[],dryRun:t.dryRun===!0}}const C_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function P_(t){return!t||!t.status?{definitive:null}:t.status==="done"?{definitive:"success",deployed:Array.isArray(t.deployed)?t.deployed:[]}:t.status==="failed"&&C_.has(t.phase)?{definitive:"failed",error:t.error||"The deploy failed before writing anything to FlutterFlow."}:{definitive:null}}async function A_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,timeoutMs:r=8e3}){if(!x_(e))return null;const s=i||globalThis.fetch;if(!s)return null;const o=new AbortController,a=setTimeout(()=>o.abort(),r);try{const l=await s(I_(t,e),{method:"GET",headers:{[b_]:String(n||"")},signal:o.signal});if(!l.ok)return null;const u=await l.json();return k_(u)}catch{return null}finally{clearTimeout(a)}}async function F_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,budgetMs:r=12e3,intervalMs:s=2e3}){const o=Date.now()+r;let a=0;for(;Date.now()=2)return{definitive:null};const u=o-Date.now();if(u<=0)break;await new Promise(c=>setTimeout(c,Math.min(s,u)))}return{definitive:null}}const R_=/^\uFEFF/;function Hi(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 At(t){return t==null?[]:Array.isArray(t)?t:[t]}function d_(t){const e=ct(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const n=Number(e);if(Number.isFinite(n))return _d(n);const i=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return i?_d(Number(i[1])):null}function _d(t){return t>=0&&t<=100?t:null}function ht(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ic(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 al(...t){return t.filter(Boolean).reduce((e,n)=>yd[n]>yd[e]?n:e,"pass")}function tp(t,e="warning",n="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:n};const i=ct(t),r=tn(i.message,i.title,i.issue,i.description,i.summary);return r?{severity:ic(i.severity||i.status||i.level)||e,message:r,suggestion:tn(i.suggestion,i.fix,i.recommendation,i.action),source:i.source||n}:null}function ll(t,e="review"){const n=ct(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([r,s])=>At(n[r]).map(o=>tp(o,s,e)).filter(Boolean))}function f_(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=ct(t),r=tn(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:tn(i.detail,i.instructions,i.description),location:tn(i.location,i.flutterFlowPath,i.path),timing:tn(i.timing,i.phase)||"unspecified",artifactId:n,source:tn(i.source)||"Code Review"}:null}function cl(t,e=null){const n=ct(t);return u_.flatMap(i=>At(n[i])).map((i,r)=>f_(i,r,e)).filter(Boolean)}function h_(t){let e=typeof t=="string"?rl(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const n=ct(e);typeof n.content=="string"&&(e=rl(n.content)||e);const i=ct(e),r=ct(i.reviewResult||i.codeReview||i.result);return{rawText:"",root:Object.keys(r).length?r:i}}function p_(t,e){const n=[e.id,e.fileName,e.artifactName].map(ht);return t.find(i=>{const r=ct(i);return[r.id,r.fileName,r.artifactName,r.name].map(ht).some(s=>s&&n.includes(s))})||null}function g_(t,e){return At(t?.metadata?.compatibility?.deployHints).find(r=>ht(r?.artifactId)===ht(e.id)||ht(r?.fileName)===ht(e.fileName))?.pathHint||""}function m_(t,e){return At(t?.relationships).filter(n=>ht(n?.from)===ht(e.id)||ht(n?.to)===ht(e.id))}function v_(t,e){return At(t?.metadata?.compatibility?.findings).filter(n=>!n?.artifactId||ht(n.artifactId)===ht(e.id)).map(n=>tp(n,"warning","Compatibility check")).filter(Boolean)}function y_(t,e,n,i){const r=p_(e,n),s=ct(r?.review||r||n.review),o=Object.keys(s).length>0,a=[...ll(s),...v_(t,n)],l=cl(s,n.id),u=ic(s.status||s.verdict||s.outcome||s.result),c=a.length?al(...a.map(f=>f.severity)):null,d=al(u,c,o?null:"warning");return{...n,index:i,status:d,statusReason:o?tn(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:g_(t,n),relationships:m_(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 w_({bundle:t,reviewResult:e}){const n=ct(t),i=At(n.artifacts),{root:r,rawText:s}=h_(e),o=[r.bundleReview,r.overallReview,r.overall,r.bundleSummary,r.summaryReview,r.review].map(ct).find(w=>Object.keys(w).length)||{},a=At(r.artifacts||r.files||r.reviews),l=i.map((w,_)=>y_(n,a,w,_)),u=ll(r),d=[...ll(o),...u],f=[...cl(o),...cl(r),...l.flatMap(w=>w.manualSteps)].filter((w,_,x)=>x.findIndex(I=>I.title===w.title&&I.artifactId===w.artifactId)===_),p=ic(o.status||o.verdict||o.overallStatus||r.status||r.verdict||r.overallStatus||r.outcome),h=al(p,...d.map(w=>w.severity),...l.map(w=>w.status)),g=o.score??r.score??r.overallScore??s,m=d_(g),v=tn(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:h,score:m,artifactPresentations:l,manualSteps:f}),b=l.reduce((w,_)=>(w[_.status]+=1,w),{pass:0,warning:0,fail:0});return{title:n.title||"Generated artifact bundle",description:n.description||"",status:h,score:m,summary:v,findings:d,manualSteps:f,artifacts:l,counts:b,reviewCoverage:{reviewed:l.filter(w=>w.reviewComplete).length,total:l.length},deployOrder:At(n.deployOrder),relationships:At(n.relationships),warnings:At(n.warnings),compatibility:ct(n.metadata?.compatibility)}}const b_="x-ff-api-key",wd="dr_",E_=/^[A-Za-z0-9_-]{1,120}$/;function S_(){const t=globalThis.crypto;if(t&&typeof t.randomUUID=="function")return`${wd}${t.randomUUID()}`;if(t&&typeof t.getRandomValues=="function"){const e=t.getRandomValues(new Uint8Array(16));return`${wd}${Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}`}return null}function x_(t){return typeof t=="string"&&E_.test(t)}function I_(t,e){return`${String(t).replace(/\/deployCustomClasses$/,"")}/runStatus/${encodeURIComponent(e)}`}function k_(t){if(!t||typeof t!="object")return null;const{status:e}=t;return e!=="running"&&e!=="done"&&e!=="failed"?null:{status:e,phase:typeof t.phase=="string"?t.phase:"",message:typeof t.message=="string"?t.message:"",error:typeof t.error=="string"?t.error:null,deployed:Array.isArray(t.deployed)?t.deployed:[],dryRun:t.dryRun===!0}}const C_=new Set(["connected","workspace_init","workspace_ready","verifying"]);function P_(t){return!t||!t.status?{definitive:null}:t.status==="done"?{definitive:"success",deployed:Array.isArray(t.deployed)?t.deployed:[]}:t.status==="failed"&&C_.has(t.phase)?{definitive:"failed",error:t.error||"The deploy failed before writing anything to FlutterFlow."}:{definitive:null}}async function A_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,timeoutMs:r=8e3}){if(!x_(e))return null;const s=i||globalThis.fetch;if(!s)return null;const o=new AbortController,a=setTimeout(()=>o.abort(),r);try{const l=await s(I_(t,e),{method:"GET",headers:{[b_]:String(n||"")},signal:o.signal});if(!l.ok)return null;const u=await l.json();return k_(u)}catch{return null}finally{clearTimeout(a)}}async function F_({provisionEndpoint:t,runId:e,apiKey:n,fetchImpl:i,budgetMs:r=12e3,intervalMs:s=2e3}){const o=Date.now()+r;let a=0;for(;Date.now()=2)return{definitive:null};const u=o-Date.now();if(u<=0)break;await new Promise(c=>setTimeout(c,Math.min(s,u)))}return{definitive:null}}const R_=/^\uFEFF/;function Ui(t){let e=0,n=t.length;for(;ee&&!t[n-1].trim();)n--;return t.slice(e,n).join(` `)}function T_(t){const e=String(t??"").replace(R_,"");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 Hi(n);{const c=ul(e);if(!c.error&&o.every(f=>Ed(f,c.commentAndStringRanges)))return Hi(n)}if(r===1){const c=Hi(n.slice(0,s)),d=Hi(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 Ui(n);{const c=ul(e);if(!c.error&&o.every(f=>Ed(f,c.commentAndStringRanges)))return Ui(n)}if(r===1){const c=Ui(n.slice(0,s)),d=Ui(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}=ul(h),m=p.length+1+f;if(Ed(m,g)){l.push(d);continue}a.push(Ui(l)),l=null}const u=a.filter(c=>c.length>0);return u.length===0?"":u.join(` `)}function M_(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 np(t){const e=M_(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 ip(t){return`${tc(t)}.dart`}function $_(t){return Ql(t,"W")}const bd={"(":")","[":"]","{":"}"},L_={")":"(","]":"[","}":"{"},N_=/[A-Za-z0-9_]/;function ul(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]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!N_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(bd[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(L_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&bd[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function O_(t){return ul(String(t??"")).error}function Ed(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 B_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],D_="MAGIC_LINK_SENT",j_="PLUS_ALIAS_REJECTED",U_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",no={allowlistedDomains:B_,successCode:D_,validationCode:j_,messageTemplate:U_},H_=new Set(no.allowlistedDomains),W_=no.successCode,q_=no.validationCode;function io(t){return typeof t=="string"?t.trim():""}function z_(t){const e=io(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 H_.has(r)?i.includes("+"):!1}function V_(t,e){return no.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function rp(t){if(!z_(t))return null;const e=io(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return V_(e,i)}function sc(t){return!t||typeof t!="object"||Array.isArray(t)||t.success===!1||t.error?!1:t.code?t.code===W_:t.success===!0||typeof t.message=="string"}function sp(t,e){return t?.code===q_?t.message||rp(e)||"Please enter your primary email address.":sc(t)?`Check your email — we sent a link to ${io(e)}`:t?.message||"Something went wrong. Please try again."}const G_="ccc_auth_session",K_="ccc_subscription",Y_=Object.freeze(["hasSeenWalkthrough"]);function J_(t){const e=[];for(const n of Y_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function Z_(){return[G_,K_]}function X_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of Z_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function Q_(t){const e=t?.message||t?.error;return typeof e=="string"&&e.trim()?e.trim():"The server could not send the link."}function e0({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());if(!sc(o))throw new Error(Q_(o));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 t0=/^dependencies\s*:\s*(?:#.*)?$/,n0=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function Ir(t){const e=t.match(n0);return e?e[1]??e[2]??e[3]:null}function kr(t){const e=t.trim();return e===""||e.startsWith("#")}function En(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function oc(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;s0?t[r-1]:"",h=r>1?t[r-2]:"",g=(p==="r"||p==="R")&&!N_.test(h);e.push({kind:"string",quote:c,triple:f,raw:g,startIndex:r,openedLine:i}),r+=f?3:1;continue}if(bd[c]){e.push({kind:"code",opener:c,openedLine:i}),r++;continue}if(L_[c]){if(d.interpolation&&c==="}"){e.pop(),r++;continue}if(d.opener&&bd[d.opener]===c){e.pop(),r++;continue}return d.opener?(a(),{error:o??`line ${i}: "${c}" closes nothing - "${d.opener}" opened on line ${d.openedLine} is still open`,commentAndStringRanges:n}):(a(),{error:o??`line ${i}: unexpected "${c}" with no matching opener`,commentAndStringRanges:n})}s(c,t[r+1]),r++}a();let l=e.length-1;for(;l>0&&e[l].kind==="line-comment";)l--;let u=o;if(!u){const c=e[l];if(!(c.kind==="code"&&!c.opener&&!c.interpolation))if(c.kind==="string")u=`unclosed ${c.triple?"triple-quoted ":""}string starting on line ${c.openedLine} was never closed`;else if(c.kind==="block-comment")u=`unterminated /* comment starting on line ${c.openedLine}`;else if(c.interpolation){const d=e.findLast(p=>p.opener);u=`unclosed "\${" expression${d?` opened on line ${d.openedLine}`:""} was never closed`}else u=`"${c.opener}" opened on line ${c.openedLine} is never closed`}return{error:u,commentAndStringRanges:n}}function O_(t){return ul(String(t??"")).error}function Ed(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 B_=["gmail.com","googlemail.com","outlook.com","hotmail.com","live.com","msn.com"],D_="MAGIC_LINK_SENT",j_="PLUS_ALIAS_REJECTED",U_="Please enter your primary email address. Plus aliases (such as {email}) are not allowed for {domain} accounts.",no={allowlistedDomains:B_,successCode:D_,validationCode:j_,messageTemplate:U_},H_=new Set(no.allowlistedDomains),W_=no.successCode,q_=no.validationCode;function io(t){return typeof t=="string"?t.trim():""}function z_(t){const e=io(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 H_.has(r)?i.includes("+"):!1}function V_(t,e){return no.messageTemplate.replaceAll("{email}",t).replaceAll("{domain}",e)}function rp(t){if(!z_(t))return null;const e=io(t),n=e.lastIndexOf("@"),i=e.slice(n+1).toLowerCase();return V_(e,i)}function sc(t){return!t||typeof t!="object"||Array.isArray(t)||t.success===!1||t.error?!1:t.code?t.code===W_:t.success===!0||typeof t.message=="string"}function sp(t,e){return t?.code===q_?t.message||rp(e)||"Please enter your primary email address.":sc(t)?`Check your email — we sent a link to ${io(e)}`:t?.message||"Something went wrong. Please try again."}const G_="ccc_auth_session",K_="ccc_subscription",Y_=Object.freeze(["hasSeenWalkthrough"]);function J_(t){const e=[];for(const n of Y_)t.getItem(n)!==null&&(t.removeItem(n),e.push(n));return e}function Z_(){return[G_,K_]}function X_({storage:t,onIdentityChanged:e,onPlanChanged:n}){for(const i of Z_())t.removeItem(i);typeof e=="function"&&e(),typeof n=="function"&&n()}function Q_(t){const e=t?.message||t?.error;return typeof e=="string"&&e.trim()?e.trim():"The server could not send the link."}function e0({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());if(!sc(o))throw new Error(Q_(o));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 t0=/^dependencies\s*:\s*(?:#.*)?$/,n0=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function xr(t){const e=t.match(n0);return e?e[1]??e[2]??e[3]:null}function Ir(t){const e=t.trim();return e===""||e.startsWith("#")}function En(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function oc(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;sc&&/\s/.test(s[d-1]);)d-=1}return t[r]=s.slice(0,c)+lc(n)+s.slice(d),!0}return!1}function Sd(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?lc(i):">=0.0.0"}`]}function o0(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=ac(e),i=new Map;if(!n)return i;for(let r=n.headerIndex+1;rc&&/\s/.test(s[d-1]);)d-=1}return t[r]=s.slice(0,c)+lc(n)+s.slice(d),!0}return!1}function Sd(t,e,n){if(n&&typeof n=="object"&&n.sdk)return[`${t}${e}:`,`${t} sdk: ${n.sdk}`];const i=String(n||"").trim();return[`${t}${e}: ${i?lc(i):">=0.0.0"}`]}function o0(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(dp(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=ac(r);if(l){const u=o.flatMap(([c,d])=>Sd(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(...Sd(" ",u,c))});return{yaml:r.join(` `),added:o.map(([u])=>u),alreadyPresent:a}}function a0(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=ro(n),o=[],a=[];for(const[l,u]of i){const c=s.get(l),d=c&&!c.isScalar&&c.sourceKey===null&&c.version!==null;if(!c||!c.isScalar&&!d||!String(u||"").trim()){a.push(l);continue}if(d){s0(r,c,String(u).trim())?o.push({name:l,from:c.version,to:u}):a.push(l);continue}const f=" ".repeat(En(r[c.lineIndex]));r[c.lineIndex]=`${f}${l}: ${lc(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:r.join(` @@ -56,7 +56,7 @@ ${d}`,{commentAndStringRanges:g}=ul(h),m=p.length+1+f;if(Ed(m,g)){l.push(d);cont `))||n.push("pubspec.yaml missing dependencies section"),dp(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 l0=">=3.0.0 <4.0.0";function dl(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 c0(t=""){const e=ep(t).filter(n=>!n.startsWith("dart:")&&!n.startsWith("package:"));return{selfContained:e.length===0,unresolvableImports:e}}function xd(t,e,n){const i=[];for(const[r,s]of t){if(s.isScalar){e[r]=dl(s.constraint);continue}if(s.sourceKey==="sdk"){n.add(r);continue}if(s.sourceKey===null&&s.version){e[r]=dl(s.version);continue}i.push(r)}return i}function u0(t){const e=new Set,n=new Set,i={},r={},s=xd(ro(t),i,e),o=xd(i0(t,"dependency_overrides"),r,n),a=[...s,...o],l=new Set([...Object.keys(i),...e]),{sdk:u}=fp(t);return{sdkConstraint:dl(u)||l0,dependencies:i,dependencyOverrides:r,sdkPackages:[...e].sort(),sdkOverrides:[...n].sort(),availablePackages:l,unrepresentable:a,unrepresentableOverrides:o}}function d0(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 f0(t,e){const{sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o,availablePackages:a,unrepresentable:l,unrepresentableOverrides:u}=u0(e),c={sdkConstraint:n,dependencies:i,dependencyOverrides:r,sdkPackages:s,sdkOverrides:o},d=[],f=[],p=[];for(const h of t){const{className:g,content:m}=h,v=nc(m),b=ep(m).some(x=>x.startsWith("package:"));if(l.length>0&&b){const x=v.filter(T=>l.includes(T));let I;if(x.length>0)I=`${g} was not compiled before deploying: it imports or exports ${x.join(", ")}, which your project declares from a source that cannot be reproduced outside it, so package resolution could not be matched exactly.`;else{const T=l.filter(P=>!u.includes(P)),S=[T.length>0?`your project's pubspec.yaml declares ${T.join(", ")} from a source that cannot be reproduced outside it`:null,u.length>0?`your project's dependency_overrides redirects ${u.join(", ")} to a source that cannot be reproduced outside it`:null].filter(Boolean).join(", and ");I=`${g} was not compiled before deploying: ${S}, and an entry like that can change what every package depending on it resolves to - including packages this class reaches transitively - so package resolution could not be matched exactly.`}f.push({className:g,reason:I});continue}const{unresolvableImports:w}=c0(m),_=v.filter(x=>!a.has(x));if(w.length>0||_.length>0){f.push({className:g,reason:d0(g,w,_)});continue}d.push({fileName:`${tc(g)}.dart`,content:m})}return{manifest:c,sources:d,skipped:f,approximate:p}}function Id(t,e){const n=`${t}${e}`.split(` `),i=n.pop()??"",r=[];for(const s of n){const o=pp(s);o&&r.push(o)}return{events:r,buffer:i}}function h0(t){const e=pp(t);return e?[e]:[]}function pp(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 Ne=Object.freeze({COMMITTED:"committed",PARTIAL:"partial",FAILED:"failed",UNCONFIRMED:"unconfirmed"}),gp=84e4,mp=1e4;function vp(t){return t?.unconfirmed===!0||t?.outcome===Ne.UNCONFIRMED?Ne.UNCONFIRMED:t?.partial===!0||t?.outcome===Ne.PARTIAL?Ne.PARTIAL:t?.success===!0?Ne.COMMITTED:Ne.FAILED}class We extends Error{constructor(e){super(e),this.name="UnconfirmedDeployError",this.outcome=Ne.UNCONFIRMED}}function kd({httpStatus:t}={}){return new We(`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 p0(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}if(u.event==="result"){r=u;return}u.event===void 0&&typeof u.success=="boolean"&&(r=u)};let l=null;try{if(t.body?.getReader){const u=t.body.getReader(),c=new TextDecoder;for(;;){const{done:d,value:f}=await u.read();if(d)break;const p=Id(o,c.decode(f,{stream:!0}));o=p.buffer,p.events.forEach(a)}}else{const u=Id("",await t.text());o=u.buffer,u.events.forEach(a)}}catch(u){l=u}return h0(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 g0=new Set(["connected","workspace_init","workspace_ready","verifying"]);function yp(t){return t?.preWrite===!0||Array.isArray(t?.analyzerErrors)&&t.analyzerErrors.length>0?!0:typeof t?.runnerPhase=="string"?g0.has(t.runnerPhase):typeof t?.httpStatus=="number"?t.httpStatus>=400&&t.httpStatus<500:!1}function Cd(t){if(t?.finalResultReceived){const e=vp(t);return e===Ne.FAILED&&!yp(t)?Ne.UNCONFIRMED:e}return t?.httpRejected&&typeof t.httpStatus=="number"&&t.httpStatus>=400&&t.httpStatus<500?Ne.FAILED:Ne.UNCONFIRMED}function m0(){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,p,h,g,m,v;function b(V,z){if(!i)return null;const D=i.createShader(V);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const V=b(i.VERTEX_SHADER,o),z=b(i.FRAGMENT_SHADER,a());if(V&&z&&(l=i.createProgram(),i.attachShader(l,V),i.attachShader(l,z),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),p=i.getUniformLocation(l,"parallax"),h=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function w(V){if(!V)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(V);if(z){let D=z[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const he=D.getContext("2d");he.fillStyle="rgb(9, 8, 7)";const Ce=String(he.fillStyle);he.fillStyle=V;const Te=String(he.fillStyle);if(Te===Ce)return null;const mt=/^#([0-9a-f]{6})$/i.exec(Te);if(mt){const vt=mt[1];return[parseInt(vt.slice(0,2),16)/255,parseInt(vt.slice(2,4),16)/255,parseInt(vt.slice(4,6),16)/255]}const Wt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Te);if(Wt)return[Number(Wt[1])/255,Number(Wt[2])/255,Number(Wt[3])/255]}catch{}return null}function _(){let V="";try{const z=getComputedStyle(document.documentElement);V=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return w(V)||[.56,.68,.88]}const x=_();let I=1920,T=1080,S=960,P=540,R=960,L=540,$=.66,O=0,J=-1e9,G=!1,M=0,K=0,ie=null,B=!1,X=!1,fe=!1;const se=64,ee=15.2;let Pe=0,ke=0;const je=.0032,St=0,ye=.56,et=.26,xt=.32,Cn=.16,Le=.349;let Re=St;function Dt(){const V=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!V.width||!z||!D)return;const he=Math.min(window.devicePixelRatio||1,2),Ce=Math.max(.2,Math.min(2,V.width/z*he)),Te=Math.max(2,Math.round(z*Ce)),mt=Math.max(2,Math.round(D*Ce));(Te!==t.width||mt!==t.height)&&(t.width=Te,t.height=mt,i&&i.viewport(0,0,Te,mt)),I=z,T=D,G||(S=R=I/2,P=L=T/2,G=!0)}function Zn(V){!l||!B||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,S,P),i.uniform1f(f,$),i.uniform1f(p,O),i.uniform2f(v,Math.cos(Re),Math.sin(Re)),i.uniform1f(h,V),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Ke(V,z,D){const he=Math.max(0,Math.min(1,(D-V)/(z-V)));return he*he*(3-2*he)}function Xn(V){if(!ie||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/I;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const he=Math.min(I,T),Ce=Math.max(64,Math.min(118,he/10)),Te=Ce*2.9,mt=2*Te*Te,Wt=Math.sin(V*.11)*7,vt=Math.cos(V*.09)*7-O,$r=S+Wt,Lr=P+vt,Ro=Te*Math.sqrt(2*Math.log(1/.06)),Ri=Ro+je*Ro*Ro+Ce,Pg=Math.floor(($r-Ri)/Ce)-1,Ag=Math.ceil(($r+Ri)/Ce)+1,Fg=Math.floor((Lr-Ri)/Ce)-1,Rg=Math.ceil((Lr+Ri)/Ce)+1;for(let To=Fg;To<=Rg;To++){const Tg=(To+.5)*Ce;for(let Mo=Pg;Mo<=Ag;Mo++){const $o=(Mo+.5)*Ce-$r,Lo=Tg-Lr,No=Math.sqrt($o*$o+Lo*Lo)+1e-5;if(No>Ri)continue;const Nr=(-1+Math.sqrt(1+4*je*No))/(2*je),Vc=Math.exp(-(Nr*Nr)/mt),Gc=Ke(.06,.8,Vc)*$*.26;if(Gc<.004)continue;const gn=Ce/(1+2*je*Nr)*.26*(.32+1.1*Vc),Kc=Nr/No,Oo=$r+$o*Kc,Bo=Lr+Lo*Kc;Oo<-gn*1.6||Oo>I+gn*1.6||Bo<-gn*1.6||Bo>T+gn*1.6||(z.globalAlpha=Gc,z.save(),z.translate(Oo,Bo),z.rotate(Re),z.drawImage(ie,-gn,-gn,gn*2,gn*2),z.restore())}}z.globalAlpha=1}function jt(V){if(!X)return;const z=K?Math.min(.05,(V-K)/1e3):.016;K=V;const he=V-J>2400?.6:1;$+=(he-$)*Math.min(1,z*3.2);const Ce=Math.min(.05,z);Pe+=((R-S)*se-Pe*ee)*Ce,ke+=((L-P)*se-ke*ee)*Ce,S+=Pe*Ce,P+=ke*Ce,O=(window.scrollY||window.pageYOffset||0)*.55;const Te=V/1e3,mt=S/(I||1)-.5,Wt=P/(T||1)-.5;let vt=mt*(mt>=0?ye:et)+Wt*(Wt>=0?xt:Cn);vt>Le?vt=Le:vt<-Le&&(vt=-Le),Re=St+vt-O*6e-4,Dt(),i?Zn(Te):Xn(Te),M=requestAnimationFrame(jt)}function Ut(V){if(!X)return;const z=t.getBoundingClientRect();!z.width||!I||!T||(R=(V.clientX-z.left)/z.width*I,L=(V.clientY-z.top)/z.height*T,J=performance.now())}function ut(){X||Fo||e.matches||n.matches||!fe||document.hidden||(X=!0,K=0,M=requestAnimationFrame(jt))}function Ht(){X=!1,M&&(cancelAnimationFrame(M),M=0),K=0}function Fi(){e.matches?(Ht(),t.classList.remove("is-ready")):fe&&ut()}function Qn(){n.matches?Ht():fe&&ut()}function Wc(){document.hidden?Ht():fe&&ut()}const qc=new IntersectionObserver(V=>{fe=V[0]?.isIntersecting||!1,fe?ut():Ht()},{threshold:0});qc.observe(t),window.addEventListener("pointermove",Ut,{passive:!0,capture:!0}),window.addEventListener("resize",Dt),e.addEventListener("change",Fi),n.addEventListener("change",Qn),document.addEventListener("visibilitychange",Wc);function Cg(){const V=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(V&&window.Path2D){const he=Math.min(8.533333333333333,8.421052631578947);D.setTransform(he,0,0,he,he+(256-30*he)/2,-6.4*he),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(V),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const he=D.getImageData(0,0,256,256),Ce=he.data;for(let Te=3;Te{V.persisted?Ht():zc()}),window.addEventListener("pageshow",V=>{V.persisted&&ut()}),{dispose:zc,isRunning:()=>X}}const v0=120;function y0(t,e,n){return tn?n:t}function pe(t,e,n){return y0((t-e)/(n-e),0,1)}function _0(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function ga(t){return 1-Math.pow(1-t,3)}function Ye(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 Pd(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function re(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(pe(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=re(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),h=re(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ye}]),d=re(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ye},{t:10.6,v:0}]),p=re(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ye}]),o=re(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=re(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=pe(_,.45,2.2);a=x>0?-2.6*(1-Pd(x)):0,g=re(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=pe(_,.67,2.42);f=I>0?-2.6*(1-Pd(I)):0,s=1-.05*(Math.sin(pe(_,1.9,2.5)*Math.PI)+Math.sin(pe(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[re(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}]),re(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 w=x;const _=t-60,I=1-pe(_,12,14),T=x(pe(_,0,12)),S=x(pe(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(S[0]-T[0])*.6*I,a=(S[1]-T[1])*.6*I,p=(S[0]-T[0])*30*I,b=pe(_,0,.4)*I}else if(t<85.4){const _=t-74,x=re(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ye},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=re(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ye},{t:11.4,v:0}]),p=-l*.7,a=re(_,[{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=pe(_,0,5.6),I=pe(_,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,p=x*360*(1-I);const S=re(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:ga},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*S,d+=.16*S,l=-6*S,p+=6*S,s=1+.05*S,m=1+.9*S}else if(t<108.6){const _=t-96.4,x=pe(_,9.6,12.2);n=re(_,[{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(pe(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,h=1-.12*I,l=I*8,p=-I*8,o=.06*I,d=-.06*I,b=pe(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(pe(_,0,8)*Math.PI),I=1-pe(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(pe(_,0,6)*Math.PI),v=1+.1*Math.sin(pe(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=b,e}function w0(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=v0;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function p(M){const K=Math.min(1,Math.max(0,M.x))*c,ie=M.y*d;n.style.transform="translate3d("+K.toFixed(2)+"px,"+ie.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("+K.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,b=!1,w=!1,_=0;function x(){return w||a.matches||document.hidden||!e.offsetParent?!1:b}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){S();return}const K=g?(M-g)/1e3:0;g=M,h=(h+Math.min(K,.1))%l,_+=1,p(Wi(h))}function T(){v||w||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function S(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():S()}function R(){a.matches?(S(),p(Wi(0))):P()}function L(){f(),v&&p(Wi(h))}function $(){g=0,P()}const O=new IntersectionObserver(M=>{b=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});O.observe(e),window.addEventListener("resize",L),a.addEventListener("change",R),document.addEventListener("visibilitychange",$);function J(){w||(w=!0,S(),O.disconnect(),window.removeEventListener("resize",L),a.removeEventListener("change",R),document.removeEventListener("visibilitychange",$))}window.addEventListener("pagehide",M=>{M.persisted?S():J()}),window.addEventListener("pageshow",M=>{M.persisted&&P()});function G(M){h=(M%l+l)%l,p(Wi(h))}return f(),p(Wi(0)),P(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:G,dispose:J}}const b0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ln(t){const e=String(t||"").trim().match(b0);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function E0(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 x0(t){const e=ln(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function cc(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 ln(o)?{min:o,minInclusive:!0,max:x0(o),maxInclusive:!1}:null}if(ln(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(!ln(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Ad(t,e){const n=cc(t);if(!n||!ln(e))return!1;if(n.min!==null){const i=Ns(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=Ns(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function I0(t,e){const n=cc(t);if(!n||!ln(e))return!1;if(n.max===null)return!0;const i=Ns(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ri(t){const e=cc(t);return e?e.min:null}const k0="https://pub.dev/api/packages/",C0=8e3;function P0(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||S0(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Ad(l.sdk,n)||i&&l.flutter&&!Ad(l.flutter,i)||(!s||Ns(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function A0(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${k0}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(C0)});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=P0(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 F0(t,e={}){const n=await Promise.all(t.map(i=>A0(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function R0(t,e={},n={}){const{resolveVersions:i=F0}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=fp(t),o={dartSdkFloor:ri(s.sdk),flutterSdkFloor:ri(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=ro(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(Gy.has(d)?c:u).push(d);continue}const h=ri(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:d,constraint:p.constraint});continue}if(I0(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(ri(h)){a.additions[f]=`^${ri(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${ri(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const T0={"&":"&","<":"<",">":">",'"':""","'":"'"};function cn(t){return String(t??"").replace(/[&<>"']/g,e=>T0[e])}function W(t){return t?cn(t).replace(/\n/g,"
    "):""}function on(t){return cn(t).replace(/\r?\n/g," ")}function so(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 wp(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 M0(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 $0(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 L0(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 xi(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 Fd(t){return t=cn(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 bp(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=xi(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 cn(i)}}}function oo(t,e={}){const{highlighter:n=globalThis.hljs}=e;let i='
    ';const r=String(t??"").split(` +`)}let l=null,u,c,d,f,p,h,g,m,v;function b(V,z){if(!i)return null;const D=i.createShader(V);return i.shaderSource(D,z),i.compileShader(D),i.getShaderParameter(D,i.COMPILE_STATUS)?D:(window.console&&console.warn("fx-grid shader: "+i.getShaderInfoLog(D)),null)}if(i){const V=b(i.VERTEX_SHADER,o),z=b(i.FRAGMENT_SHADER,a());if(V&&z&&(l=i.createProgram(),i.attachShader(l,V),i.attachShader(l,z),i.linkProgram(l),i.getProgramParameter(l,i.LINK_STATUS)||(window.console&&console.warn("fx-grid link: "+i.getProgramInfoLog(l)),l=null)),l){i.useProgram(l),i.bindBuffer(i.ARRAY_BUFFER,i.createBuffer()),i.bufferData(i.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),i.STATIC_DRAW);const D=i.getAttribLocation(l,"p");i.enableVertexAttribArray(D),i.vertexAttribPointer(D,2,i.FLOAT,!1,0,0),u=i.getUniformLocation(l,"res"),c=i.getUniformLocation(l,"design"),d=i.getUniformLocation(l,"mouse"),f=i.getUniformLocation(l,"energy"),p=i.getUniformLocation(l,"parallax"),h=i.getUniformLocation(l,"t"),g=i.getUniformLocation(l,"ink"),m=i.getUniformLocation(l,"mark"),v=i.getUniformLocation(l,"rot"),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.clearColor(0,0,0,0)}else{i=null;const D=t.cloneNode(!1);if(t.parentNode.replaceChild(D,t),t=D,r=t.getContext("2d"),!r)return null}}function w(V){if(!V)return null;const z=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(V);if(z){let D=z[1];return D.length===3&&(D=D[0]+D[0]+D[1]+D[1]+D[2]+D[2]),[parseInt(D.slice(0,2),16)/255,parseInt(D.slice(2,4),16)/255,parseInt(D.slice(4,6),16)/255]}try{const D=document.createElement("canvas");D.width=1,D.height=1;const he=D.getContext("2d");he.fillStyle="rgb(9, 8, 7)";const Ce=String(he.fillStyle);he.fillStyle=V;const Te=String(he.fillStyle);if(Te===Ce)return null;const mt=/^#([0-9a-f]{6})$/i.exec(Te);if(mt){const vt=mt[1];return[parseInt(vt.slice(0,2),16)/255,parseInt(vt.slice(2,4),16)/255,parseInt(vt.slice(4,6),16)/255]}const Wt=/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i.exec(Te);if(Wt)return[Number(Wt[1])/255,Number(Wt[2])/255,Number(Wt[3])/255]}catch{}return null}function _(){let V="";try{const z=getComputedStyle(document.documentElement);V=(z.getPropertyValue("--fx-ink")||"").trim()||(z.getPropertyValue("--fg")||"").trim()}catch{}return w(V)||[.56,.68,.88]}const x=_();let I=1920,T=1080,S=960,P=540,R=960,L=540,$=.66,O=0,J=-1e9,G=!1,M=0,K=0,ie=null,B=!1,X=!1,fe=!1;const se=64,ee=15.2;let Pe=0,ke=0;const je=.0032,St=0,ye=.56,et=.26,xt=.32,Cn=.16,Le=.349;let Re=St;function Dt(){const V=t.getBoundingClientRect(),z=t.clientWidth,D=t.clientHeight;if(!V.width||!z||!D)return;const he=Math.min(window.devicePixelRatio||1,2),Ce=Math.max(.2,Math.min(2,V.width/z*he)),Te=Math.max(2,Math.round(z*Ce)),mt=Math.max(2,Math.round(D*Ce));(Te!==t.width||mt!==t.height)&&(t.width=Te,t.height=mt,i&&i.viewport(0,0,Te,mt)),I=z,T=D,G||(S=R=I/2,P=L=T/2,G=!0)}function Zn(V){!l||!B||!i||(i.uniform2f(u,t.width,t.height),i.uniform2f(c,I,T),i.uniform2f(d,S,P),i.uniform1f(f,$),i.uniform1f(p,O),i.uniform2f(v,Math.cos(Re),Math.sin(Re)),i.uniform1f(h,V),i.uniform3f(g,x[0],x[1],x[2]),i.clear(i.COLOR_BUFFER_BIT),i.drawArrays(i.TRIANGLES,0,3))}function Ke(V,z,D){const he=Math.max(0,Math.min(1,(D-V)/(z-V)));return he*he*(3-2*he)}function Xn(V){if(!ie||!r)return;const z=r;z.setTransform(1,0,0,1,0,0),z.clearRect(0,0,t.width,t.height);const D=t.width/I;z.setTransform(D,0,0,D,0,0),z.globalAlpha=1;const he=Math.min(I,T),Ce=Math.max(64,Math.min(118,he/10)),Te=Ce*2.9,mt=2*Te*Te,Wt=Math.sin(V*.11)*7,vt=Math.cos(V*.09)*7-O,$r=S+Wt,Lr=P+vt,Ro=Te*Math.sqrt(2*Math.log(1/.06)),Fi=Ro+je*Ro*Ro+Ce,Pg=Math.floor(($r-Fi)/Ce)-1,Ag=Math.ceil(($r+Fi)/Ce)+1,Fg=Math.floor((Lr-Fi)/Ce)-1,Rg=Math.ceil((Lr+Fi)/Ce)+1;for(let To=Fg;To<=Rg;To++){const Tg=(To+.5)*Ce;for(let Mo=Pg;Mo<=Ag;Mo++){const $o=(Mo+.5)*Ce-$r,Lo=Tg-Lr,No=Math.sqrt($o*$o+Lo*Lo)+1e-5;if(No>Fi)continue;const Nr=(-1+Math.sqrt(1+4*je*No))/(2*je),Vc=Math.exp(-(Nr*Nr)/mt),Gc=Ke(.06,.8,Vc)*$*.26;if(Gc<.004)continue;const gn=Ce/(1+2*je*Nr)*.26*(.32+1.1*Vc),Kc=Nr/No,Oo=$r+$o*Kc,Bo=Lr+Lo*Kc;Oo<-gn*1.6||Oo>I+gn*1.6||Bo<-gn*1.6||Bo>T+gn*1.6||(z.globalAlpha=Gc,z.save(),z.translate(Oo,Bo),z.rotate(Re),z.drawImage(ie,-gn,-gn,gn*2,gn*2),z.restore())}}z.globalAlpha=1}function jt(V){if(!X)return;const z=K?Math.min(.05,(V-K)/1e3):.016;K=V;const he=V-J>2400?.6:1;$+=(he-$)*Math.min(1,z*3.2);const Ce=Math.min(.05,z);Pe+=((R-S)*se-Pe*ee)*Ce,ke+=((L-P)*se-ke*ee)*Ce,S+=Pe*Ce,P+=ke*Ce,O=(window.scrollY||window.pageYOffset||0)*.55;const Te=V/1e3,mt=S/(I||1)-.5,Wt=P/(T||1)-.5;let vt=mt*(mt>=0?ye:et)+Wt*(Wt>=0?xt:Cn);vt>Le?vt=Le:vt<-Le&&(vt=-Le),Re=St+vt-O*6e-4,Dt(),i?Zn(Te):Xn(Te),M=requestAnimationFrame(jt)}function Ut(V){if(!X)return;const z=t.getBoundingClientRect();!z.width||!I||!T||(R=(V.clientX-z.left)/z.width*I,L=(V.clientY-z.top)/z.height*T,J=performance.now())}function ut(){X||Fo||e.matches||n.matches||!fe||document.hidden||(X=!0,K=0,M=requestAnimationFrame(jt))}function Ht(){X=!1,M&&(cancelAnimationFrame(M),M=0),K=0}function Ai(){e.matches?(Ht(),t.classList.remove("is-ready")):fe&&ut()}function Qn(){n.matches?Ht():fe&&ut()}function Wc(){document.hidden?Ht():fe&&ut()}const qc=new IntersectionObserver(V=>{fe=V[0]?.isIntersecting||!1,fe?ut():Ht()},{threshold:0});qc.observe(t),window.addEventListener("pointermove",Ut,{passive:!0,capture:!0}),window.addEventListener("resize",Dt),e.addEventListener("change",Ai),n.addEventListener("change",Qn),document.addEventListener("visibilitychange",Wc);function Cg(){const V=(s.match(/\sd="([^"]+)"/)||[])[1],z=document.createElement("canvas");z.width=256,z.height=256;const D=z.getContext("2d");if(V&&window.Path2D){const he=Math.min(8.533333333333333,8.421052631578947);D.setTransform(he,0,0,he,he+(256-30*he)/2,-6.4*he),D.fillStyle="rgb(255,255,255)",D.fill(new Path2D(V),"evenodd"),D.setTransform(1,0,0,1,0,0)}try{const he=D.getImageData(0,0,256,256),Ce=he.data;for(let Te=3;Te{V.persisted?Ht():zc()}),window.addEventListener("pageshow",V=>{V.persisted&&ut()}),{dispose:zc,isRunning:()=>X}}const v0=120;function y0(t,e,n){return tn?n:t}function pe(t,e,n){return y0((t-e)/(n-e),0,1)}function _0(t){return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2}function ga(t){return 1-Math.pow(1-t,3)}function Ye(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 Pd(t){return 1-Math.pow(2,-9*t)*Math.cos(t*15)}function re(t,e){if(t<=e[0].t)return e[0].v;for(let n=1;n8.2&&_<9.4&&(s*=1-.07*Math.sin(pe(_,8.2,9.4)*Math.PI))}else if(t<53){const _=t-42;g=re(_,[{t:0,v:1},{t:2,v:0},{t:4.2,v:0},{t:4.6,v:1},{t:6.8,v:1},{t:7.4,v:0},{t:9.4,v:0},{t:10.6,v:1}]),h=re(_,[{t:0,v:1},{t:2,v:.3},{t:4.6,v:1,e:Ye}]),d=re(_,[{t:0,v:0},{t:2,v:.3},{t:4.6,v:.16,e:Ye},{t:10.6,v:0}]),p=re(_,[{t:0,v:0},{t:2,v:-40},{t:4.6,v:0,e:Ye}]),o=re(_,[{t:0,v:0},{t:4.6,v:-.12},{t:10.6,v:0}])}else if(t<60){const _=t-53;c=re(_,[{t:0,v:1},{t:.35,v:0},{t:.45,v:0},{t:.7,v:1}]);const x=pe(_,.45,2.2);a=x>0?-2.6*(1-Pd(x)):0,g=re(_,[{t:0,v:1},{t:.57,v:0},{t:.67,v:0},{t:.92,v:1}]);const I=pe(_,.67,2.42);f=I>0?-2.6*(1-Pd(I)):0,s=1-.05*(Math.sin(pe(_,1.9,2.5)*Math.PI)+Math.sin(pe(_,2.5,3.1)*Math.PI))}else if(t<74){let x=function(P){return[re(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}]),re(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 w=x;const _=t-60,I=1-pe(_,12,14),T=x(pe(_,0,12)),S=x(pe(_-.5,0,12));n=T[0]*I,i=(T[1]+.05*Math.sin(_*7))*I,o=(S[0]-T[0])*.6*I,a=(S[1]-T[1])*.6*I,p=(S[0]-T[0])*30*I,b=pe(_,0,.4)*I}else if(t<85.4){const _=t-74,x=re(_,[{t:0,v:0},{t:4,v:1},{t:8,v:.24},{t:9.6,v:1,e:Ye},{t:11.4,v:0}]);o=x*.5,d=-x*.5,l=re(_,[{t:0,v:0},{t:4,v:6},{t:8,v:20},{t:9.6,v:38,e:Ye},{t:11.4,v:0}]),p=-l*.7,a=re(_,[{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=pe(_,0,5.6),I=pe(_,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,p=x*360*(1-I);const S=re(_,[{t:0,v:0},{t:7.6,v:0},{t:8.2,v:1,e:ga},{t:8.6,v:.55},{t:9.4,v:0}]);o=-.16*S,d+=.16*S,l=-6*S,p+=6*S,s=1+.05*S,m=1+.9*S}else if(t<108.6){const _=t-96.4,x=pe(_,9.6,12.2);n=re(_,[{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(pe(_,0,9.6)*Math.PI*3))*(1-x);const I=Math.sin(_*6.2)*(1-x);u=1+.12*I,h=1-.12*I,l=I*8,p=-I*8,o=.06*I,d=-.06*I,b=pe(_,0,.4)*(1-x)}else{const _=t-108.6,x=Math.sin(pe(_,0,8)*Math.PI),I=1-pe(_,8,11.4);s=1+.04*x*I,i=-.1*x*I,r=2*x*I,m=1+.5*Math.sin(pe(_,0,6)*Math.PI),v=1+.1*Math.sin(pe(_,0,6)*Math.PI)}return e.x=n,e.y=i,e.rot=r,e.scale=s,e.ax=o,e.ay=a,e.ar=l,e.asc=u,e.afade=c,e.bx=d,e.by=f,e.br=p,e.bsc=h,e.bfade=g,e.hfade=m,e.hsc=v,e.shd=b,e}function w0(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=v0;let u=34,c=0,d=0;function f(){u=n.offsetWidth||34,c=Math.max(0,e.offsetWidth-u-4),d=Math.max(0,(e.offsetHeight-u)/2-2),e.style.setProperty("--mark-c",u/2+"px")}function p(M){const K=Math.min(1,Math.max(0,M.x))*c,ie=M.y*d;n.style.transform="translate3d("+K.toFixed(2)+"px,"+ie.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("+K.toFixed(2)+"px) scaleX("+(.75+.4*Math.abs(M.x)).toFixed(3)+")",o.style.opacity=(M.shd*.5).toFixed(3)}let h=0,g=0,m=0,v=!1,b=!1,w=!1,_=0;function x(){return w||a.matches||document.hidden||!e.offsetParent?!1:b}function I(M){if(!v)return;if(m=requestAnimationFrame(I),!x()){S();return}const K=g?(M-g)/1e3:0;g=M,h=(h+Math.min(K,.1))%l,_+=1,p(Hi(h))}function T(){v||w||x()&&(v=!0,g=0,m=requestAnimationFrame(I))}function S(){v=!1,m&&(cancelAnimationFrame(m),m=0),g=0}function P(){x()?T():S()}function R(){a.matches?(S(),p(Hi(0))):P()}function L(){f(),v&&p(Hi(h))}function $(){g=0,P()}const O=new IntersectionObserver(M=>{b=M[0]?M[0].isIntersecting:!1,P()},{threshold:0});O.observe(e),window.addEventListener("resize",L),a.addEventListener("change",R),document.addEventListener("visibilitychange",$);function J(){w||(w=!0,S(),O.disconnect(),window.removeEventListener("resize",L),a.removeEventListener("change",R),document.removeEventListener("visibilitychange",$))}window.addEventListener("pagehide",M=>{M.persisted?S():J()}),window.addEventListener("pageshow",M=>{M.persisted&&P()});function G(M){h=(M%l+l)%l,p(Hi(h))}return f(),p(Hi(0)),P(),{isRunning:()=>v,currentTime:()=>h,frameCount:()=>_,seek:G,dispose:J}}const b0=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ln(t){const e=String(t||"").trim().match(b0);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function E0(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 x0(t){const e=ln(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function cc(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 ln(o)?{min:o,minInclusive:!0,max:x0(o),maxInclusive:!1}:null}if(ln(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(!ln(a))return null;r=!0,o===">="||o===">"?(n.min=a,n.minInclusive=o===">="):(n.max=a,n.maxInclusive=o==="<=")}return r?n:null}function Ad(t,e){const n=cc(t);if(!n||!ln(e))return!1;if(n.min!==null){const i=Ns(e,n.min);if(i<0||i===0&&!n.minInclusive)return!1}if(n.max!==null){const i=Ns(e,n.max);if(i>0||i===0&&!n.maxInclusive)return!1}return!0}function I0(t,e){const n=cc(t);if(!n||!ln(e))return!1;if(n.max===null)return!0;const i=Ns(n.max,e);return i>0?!0:i===0&&n.maxInclusive}function ri(t){const e=cc(t);return e?e.min:null}const k0="https://pub.dev/api/packages/",C0=8e3;function P0(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||S0(a))continue;const l=o.pubspec?.environment||{};n&&l.sdk&&!Ad(l.sdk,n)||i&&l.flutter&&!Ad(l.flutter,i)||(!s||Ns(a,s)>0)&&(s=a)}return s?{version:s,constraint:`^${s}`}:null}async function A0(t,e={}){const{dartSdkFloor:n=null,flutterSdkFloor:i=null,fetchImpl:r=fetch}=e;let s;try{const a=await r(`${k0}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(C0)});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=P0(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 F0(t,e={}){const n=await Promise.all(t.map(i=>A0(i,e)));return new Map(n.map(({name:i,...r})=>[i,r]))}async function R0(t,e={},n={}){const{resolveVersions:i=F0}=n,r=Object.entries(e).filter(([d])=>d&&d!=="flutter"),s=fp(t),o={dartSdkFloor:ri(s.sdk),flutterSdkFloor:ri(s.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(r.length===0)return a;const l=ro(t),u=[],c=[];for(const[d,f]of r){const p=l.get(d);if(!p){(Gy.has(d)?c:u).push(d);continue}const h=ri(f);if(!h){a.kept.push({name:d,constraint:p.constraint});continue}const g=p.isScalar?p.constraint:p.sourceKey===null?p.version:null;if(g===null){a.warnings.push(`"${d}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${h}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:d,constraint:p.constraint});continue}if(I0(g,h)){a.kept.push({name:d,constraint:g});continue}a.overrides[d]=`^${h}`,a.warnings.push(`"${d}" was pinned to ${g} in your project, which cannot resolve the ${h} the generated code needs. Raising it to ^${h} — this changes a dependency the rest of your app also uses.`)}for(const d of c)a.additions[d]={sdk:"flutter"};if(u.length>0){const d=await i(u,o);for(const f of u){const p=d.get(f);if(p?.constraint){a.additions[f]=p.constraint;continue}const h=e[f]||"";if(ri(h)){a.additions[f]=`^${ri(h)}`,a.warnings.push(`Could not confirm "${f}" version on pub.dev (${p?.error||"lookup failed"}). Using ^${ri(h)} from the AI's recommendation — verify this is current.`);continue}a.additions[f]=">=0.0.0",a.warnings.push(`Could not determine a version for "${f}" (${p?.error||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const T0={"&":"&","<":"<",">":">",'"':""","'":"'"};function cn(t){return String(t??"").replace(/[&<>"']/g,e=>T0[e])}function W(t){return t?cn(t).replace(/\n/g,"
    "):""}function on(t){return cn(t).replace(/\r?\n/g," ")}function so(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 wp(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 M0(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 $0(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 L0(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 xi(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 Fd(t){return t=cn(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 bp(t,e="dart",n=globalThis.hljs){if(!t)return"";const i=xi(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 cn(i)}}}function oo(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=L0(o),u=bp(o.trim(),l,n);i+=`
    ${u}
    `,o="",s=!1}else s=!0;continue}if(s){o+=a+` @@ -81,13 +81,13 @@ in vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }`;function a(){return[
    ${i}
    - `}const ai=5200,ma=73,N0=1600,Rd=35,Td=22,va=new WeakMap;function Md(t,e){return!!(t&&t.trim())&&!e}function O0(t,e){const n=ai+(e-1)*ma,i=n+N0;if(t{X.disabled=B}),o&&(o.disabled=B),a&&(a.disabled=B),b()}async function x(){if(Md(n.value,v())){_(!0);try{await t()}finally{_(!1)}}}function I(){f&&(f=!1,g&&(clearTimeout(g),g=null),e.classList.remove("is-demo-typing","is-demo-keying"),n.placeholder="Describe the widget or action you need",b())}function T(){if(l.matches||!m.trim())return;const B=window.location.hash.replace(/^#/,"");if(B&&B!=="home")return;f=!0,n.placeholder="",n.value="",w(),b(),e.classList.add("is-demo-typing");const X=performance.now(),fe=()=>{if(!f)return;const se=O0(performance.now()-X,m.length);n.value=m.slice(0,se.chars),w(),e.classList.toggle("is-demo-keying",se.keying),se.done?I():g=setTimeout(fe,se.next)};g=setTimeout(fe,ai)}function S(){f&&(n.value="",w(),I())}function P(){l.matches&&(S(),L())}function R(){d=!1,h&&(clearInterval(h),h=null),e.classList.remove("is-demo-typing","is-demo-keying"),b()}function L(){d&&(n.value=s.find(B=>B.classList.contains("is-active"))?.dataset.prompt||n.value,w(),R())}function $(){s.forEach(B=>{B.classList.remove("is-active"),B.setAttribute("aria-pressed","false")})}function O(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function J(B){const X=B.dataset.prompt||"";if(I(),R(),s.forEach(se=>{const ee=se===B;se.classList.toggle("is-active",ee),se.setAttribute("aria-pressed",String(ee))}),l.matches||!X){n.value=X,w(),b(),O();return}n.value="",w(),d=!0,b(),e.classList.add("is-demo-typing","is-demo-keying");const fe=performance.now();h=setInterval(()=>{const se=Math.min(X.length,Math.floor((performance.now()-fe)/Td));n.value=X.slice(0,se),w(),se>=X.length?(R(),O()):b()},Td)}s.forEach(B=>{B.setAttribute("aria-pressed","false"),B.addEventListener("click",()=>J(B))}),n.addEventListener("keydown",B=>{if((f||d)&&B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u){B.preventDefault();return}S(),L(),B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u&&(B.preventDefault(),x())}),n.addEventListener("beforeinput",()=>S()),n.addEventListener("input",()=>{I(),R(),$(),w(),b()}),n.addEventListener("compositionstart",()=>{u=!0}),n.addEventListener("compositionend",()=>{u=!1,b()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),i.addEventListener("click",x),n.addEventListener("pointerdown",()=>{S(),L(),$()}),n.addEventListener("focus",()=>S());const G=va.get(e);G&&G.mql.removeEventListener("change",G.handler),l.addEventListener("change",P),va.set(e,{mql:l,handler:P});function M(){K(),l.removeEventListener("change",P),va.delete(e),document.removeEventListener("visibilitychange",ie)}function K(){S(),L()}function ie(){document.hidden&&K()}return document.addEventListener("visibilitychange",ie),w(),b(),T(),{setAttachmentsPending(B){p=!!B,b()},dispose:M,cancelTyping:K}}const vr=window.matchMedia("(prefers-reduced-motion: reduce)");let hi=null,Jt=null;const Os=new Map;function Ep(){for(const[t,e]of Os)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Os.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Gn(){if(Ep(),hi){const t=hi;hi=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Jt&&(Jt.animation.cancel(),Jt.hero.classList.remove("is-exiting"),Jt.hero.style.cssText=Jt.style,Jt=null)}function D0(t){return(hi?.ghost||t)?.getBoundingClientRect()}function j0(t){Ep(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",vr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Os.delete(e))}Os.set(e,i),e.addEventListener("animationend",i)})}function U0(t,e){if(!t||!e||vr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Jt={hero:t,animation:i,style:n},i.onfinish=()=>{Jt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Jt=null)}}function Sp(t,e,n,{results:i=!1}={}){if(Gn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,j0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(vr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};hi=h,p.onfinish=()=>{hi===h&&(Gn(),s())}}window.addEventListener("resize",Gn);window.addEventListener("pagehide",Gn);document.addEventListener("visibilitychange",()=>{document.hidden&&Gn()});vr.addEventListener("change",()=>{vr.matches&&Gn()});const $d="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",H0="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",W0="https://us.i.posthog.com";jh.init(H0,{api_host:W0,person_profiles:"identified_only"});function Dn(t,e={}){try{jh.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const Et="https://4tgke4.buildship.run",xp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Bs="ccc_auth_session",fl="ccc_signin_return",q0=1800*1e3,Ld=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let de=Kn({isResolved:!0}),hl=Promise.resolve();const z0=`${Et}/service/runpipeline`,V0="bs_user_id",G0="bs_identity_token",K0=`${Et}/authUserCheck`;let yt={userId:null,token:null,status:null,resolved:!1};const Ds=ly,js="ccc_subscription",Nd=3,Y0=new Set(["active","trialing","paid"]),Us="google/gemini-3.7-flash",ss=["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"],J0={"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 nn(t){return J0[t]||t}const Z0=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 Ip(t){return Z0.has(t)}const pl=4,ya=8*1024*1024,X0="https://4tgke4.buildship.run/service/runpipeline-image";let De=[];const Sn=[],Q0=3e4;let uc=null;function ew(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function tw(t,e){const n=new FormData;return n.append("file",t),(await fetch(X0,{method:"POST",body:n,signal:e})).json()}function nw(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 iw(t,e,n){const i=await ew(t,n);i&&De.includes(e)&&(e.dataUrl=i,yn());let r="";if(i)try{r=nw(await tw(t,n))}catch{r=""}return De.includes(e)?!i||!r?(De.splice(De.indexOf(e),1),yn(),"failed"):(e.url=r,yn(),"added"):"dropped"}function kp(t){const e=Sn.indexOf(t);e>=0&&Sn.splice(e,1),Pp()}function Cp(t){t.controller.abort(),kp(t);const e=De.indexOf(t.slot);e>=0&&(De.splice(e,1),yn())}function Pp(){uc?.setAttachmentsPending(Sn.length>0)}async function rw(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>ya);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(ya/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ya);if(!i.length)return;const r=pl-De.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${pl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};De.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Q0);return d.job=iw(u,c,d.controller.signal),Sn.push(d),d.job.finally(()=>{clearTimeout(f),kp(d)}),d.job});yn(),Pp();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 sw(t){if(y.isRunning){Ee("Wait for the current generation to finish before removing images.","info");return}const e=De[t],n=Sn.find(i=>i.slot===e);if(n){Cp(n);return}De.splice(t,1),yn()}function yn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",De.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=De.length>=pl?"Image limit reached":"Add images"))}function dc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ip(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(Cp),De=[],yn())}const Wn="ccc_usage",Ap="google/gemini-3.7-flash",Fp="google/gemini-3.7-flash",Yr="google/gemini-3.7-flash",Zi={professional:11,power:49},gl={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"},os={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 as={...os};async function ow(){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(os),...Object.values(ml),...Object.values(gl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:os[a]&&(s[a]=os[a]));as=s}catch{}finally{clearTimeout(e)}}const ml={"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 fc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ml[s])return ml[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=gl[e];if(n)return n;const i=e.split("_")[0],r=gl[i];return r||"USD"}function Xi(t,e){const n=as[e]??as.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*as.USD)}}const _t="ccc_api_key_",Tt="ccc_session_api_key_",Nt="ccc_encryption_key",yr="ccc_encryption_key_scope",aw="ccc_keystore",Hs="keys",_r="ccc_encryption_key_version";let vl=null,Ws=null,wr=!1,qs=!1,Od=!1;class zs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Bd(){if(Od)return;Od=!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 Rp(){return localStorage.getItem(_r)||""}function yl(){return crypto.randomUUID?.()||Mp(crypto.getRandomValues(new Uint8Array(16)))}function lw(){const t=Rp();if(t)return t;const e=yl();return localStorage.setItem(_r,e),e}function Ii(){vl=null,Ws=null,wr=!1,qs=!1}window.addEventListener("storage",t=>{t.key===_r&&Ii()});function cw(){return new Promise((t,e)=>{const n=indexedDB.open(aw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Hs)||i.createObjectStore(Hs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function hc(t,e){const n=await cw();return new Promise((i,r)=>{const s=n.transaction(Hs,t);let o;try{o=e(s.objectStore(Hs))}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 uw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function dw(){const t=await hc("readonly",e=>e.get(Nt));return uw(t)?t:null}async function Tp(t){await hc("readwrite",e=>e.put(t,Nt))}async function fw(){Ii();try{await hc("readwrite",t=>t.delete(Nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function hw(){const t=sessionStorage.getItem(Nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Tp(e),sessionStorage.removeItem(Nt),sessionStorage.removeItem(yr),localStorage.removeItem(_t+"salt"),e}async function Dd(t){const e=sessionStorage.getItem(Nt);if(e)return qs=sessionStorage.getItem(yr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new zs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Nt,JSON.stringify(i)),sessionStorage.setItem(yr,"session"),qs=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function pw(t){if(sessionStorage.getItem(yr)==="session"&&sessionStorage.getItem(Nt))return Bd(),wr=!0,Dd(t);try{const e=await dw();if(e)return e;const n=await hw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Tp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Bd(),wr=!0,Dd(t)}}async function pc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=lw();Ws!==n&&Ii();const i=vl||pw(e);vl=i,Ws=n;try{return await i}catch(r){throw Ii(),r}}async function gw(t){const e=await pc(),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:Mp(o),keyVersion:n,sessionFallback:wr}}async function mw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await pc({allowSessionFallbackCreation:!1});if(wr&&!n&&!qs)throw new zs;const r=vw(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 zs)throw i;return console.error("Decryption failed:",i),null}}function Mp(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ie="",Mt="",or=null,Ud=0,ot="not-configured",gt=0,_l=0,wl=0,ao=0,Zt=0,un=0,Ze=null,$t=null,br=null;function _w(){return _l+=1,_l}function ww(){return wl+=1,wl}function Er(t,e,n){Ze=t?{projectId:t,key:e,generation:n}:null}function bl(t,e=Ie){if(!t)return!1;const n=Ze;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function gc(t,e,n){if(!Mt||Ze&&Ze.projectId!==Mt)return;(t||[]).some(r=>(r.id||r.projectId)===Mt)?Er(Mt,e,n):Ze&&Er("",null,null)}function $p({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===Ie||r===Ie}async function mc(){sessionStorage.getItem(Nt)&&await pc(),Ie=await Me("flutterflow"),Mt=await Me("flutterflow_project_id"),kw(),pn(),Ie?wc():(ot="not-configured",bt())}let Sr=!1;function Lp(){const t=document.getElementById("api-keys-modal");Ve(t),_c(),Ie&&uo(Ie)}function vc(){Sr=!1,Lp()}function bw(){Sr=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Lp()}let Hd=!1;function Wd(){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 qd(){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=nn(t.value),r=Ip(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.`),dc()}function Np(){if(Sr=!1,Wd(),qd(),!Hd){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")),Wd(),qd()}),Hd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function Ew(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Op(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=Sr;if(Sr=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&yc(),Ve(i))}}let dn=1;function Bp(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function lo(){const t=Bp();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,lo())}function Sw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,lo(),Ve(t))}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Dp(){if(H.isVerified&&Ot()&&de.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,lo(),Ve(e))}}async function _c(){const t=document.getElementById("flutterflow-api-key-input");Ie?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Iw()}function Iw(){zd("flutterflow","flutterflow-key-status"),zd("flutterflow_project_id","flutterflow-project-status")}function zd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ft(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function kw(){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"?Ft("flutterflow")&&Ft("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ft("flutterflow")||Ft("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)"):Ft(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)")}),pn()}async function Cw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==Ie,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await jd("flutterflow",n),n!==l&&!r&&ls()}const s=n||Ie;if(r){if(!co(r)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}bl(r,s)?await jd("flutterflow_project_id",r):(i?ls():Ze=null,e.value="",s&&!($t&&$t.key===s&&$t.generation===gt)&&uo(s))}else i&&ls();await mc(),n&&await wc(),_c();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Op()},1e3)}async function Pw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(_r,yl()),Ii(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),sessionStorage.removeItem(Nt),sessionStorage.removeItem(yr),localStorage.removeItem(_t+"salt"),await fw(),localStorage.setItem(_r,yl()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),Ze=null,$t=null,br=null,await mc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),_c()}function co(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Mt||"—"),!e)return;let r,s;if(!Ft("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 wc(){const t=ww(),e=++ao,n=gt,i=Ie,r=await Me("flutterflow"),s=()=>$p({seq:t,currentSeq:wl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Ft("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&gc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function ls(){Mt="",Ze=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow_project_id")}function Aw(){gt+=1,$t=null,br=null,ls();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ft("flutterflow")?(ot="validating",uo(Ie)):ot="not-configured",bt()}function Fw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Rw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Fw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Tw(async n=>{const i=n.target.value.trim();i&&await uo(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&$t?Er(n,$t.key,$t.generation):Er("",null,null)})}function Tw(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function uo(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=_w(),r=++ao,s=gt,o=Ie,a=()=>$p({seq:i,currentSeq:_l,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};$t=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===Ie&&(Ft("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;$t={key:t,generation:s};const f=t===Ie,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,gc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Mt&&(e.value=Mt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===Ie&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Mw(t){const e=document.getElementById(t),i=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",i.innerHTML=` + `}const ai=5200,ma=73,N0=1600,Rd=35,Td=22,va=new WeakMap;function Md(t,e){return!!(t&&t.trim())&&!e}function O0(t,e){const n=ai+(e-1)*ma,i=n+N0;if(t{X.disabled=B}),o&&(o.disabled=B),a&&(a.disabled=B),b()}async function x(){if(Md(n.value,v())){_(!0);try{await t()}finally{_(!1)}}}function I(){f&&(f=!1,g&&(clearTimeout(g),g=null),e.classList.remove("is-demo-typing","is-demo-keying"),n.placeholder="Describe the widget or action you need",b())}function T(){if(l.matches||!m.trim())return;const B=window.location.hash.replace(/^#/,"");if(B&&B!=="home")return;f=!0,n.placeholder="",n.value="",w(),b(),e.classList.add("is-demo-typing");const X=performance.now(),fe=()=>{if(!f)return;const se=O0(performance.now()-X,m.length);n.value=m.slice(0,se.chars),w(),e.classList.toggle("is-demo-keying",se.keying),se.done?I():g=setTimeout(fe,se.next)};g=setTimeout(fe,ai)}function S(){f&&(n.value="",w(),I())}function P(){l.matches&&(S(),L())}function R(){d=!1,h&&(clearInterval(h),h=null),e.classList.remove("is-demo-typing","is-demo-keying"),b()}function L(){d&&(n.value=s.find(B=>B.classList.contains("is-active"))?.dataset.prompt||n.value,w(),R())}function $(){s.forEach(B=>{B.classList.remove("is-active"),B.setAttribute("aria-pressed","false")})}function O(){try{n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length)}catch{}}function J(B){const X=B.dataset.prompt||"";if(I(),R(),s.forEach(se=>{const ee=se===B;se.classList.toggle("is-active",ee),se.setAttribute("aria-pressed",String(ee))}),l.matches||!X){n.value=X,w(),b(),O();return}n.value="",w(),d=!0,b(),e.classList.add("is-demo-typing","is-demo-keying");const fe=performance.now();h=setInterval(()=>{const se=Math.min(X.length,Math.floor((performance.now()-fe)/Td));n.value=X.slice(0,se),w(),se>=X.length?(R(),O()):b()},Td)}s.forEach(B=>{B.setAttribute("aria-pressed","false"),B.addEventListener("click",()=>J(B))}),n.addEventListener("keydown",B=>{if((f||d)&&B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u){B.preventDefault();return}S(),L(),B.key==="Enter"&&!B.shiftKey&&!B.isComposing&&!u&&(B.preventDefault(),x())}),n.addEventListener("beforeinput",()=>S()),n.addEventListener("input",()=>{I(),R(),$(),w(),b()}),n.addEventListener("compositionstart",()=>{u=!0}),n.addEventListener("compositionend",()=>{u=!1,b()}),n.addEventListener("scroll",()=>{r&&r.parentNode&&(r.parentNode.scrollTop=n.scrollTop)}),i.addEventListener("click",x),n.addEventListener("pointerdown",()=>{S(),L(),$()}),n.addEventListener("focus",()=>S());const G=va.get(e);G&&G.mql.removeEventListener("change",G.handler),l.addEventListener("change",P),va.set(e,{mql:l,handler:P});function M(){K(),l.removeEventListener("change",P),va.delete(e),document.removeEventListener("visibilitychange",ie)}function K(){S(),L()}function ie(){document.hidden&&K()}return document.addEventListener("visibilitychange",ie),w(),b(),T(),{setAttachmentsPending(B){p=!!B,b()},dispose:M,cancelTyping:K}}const mr=window.matchMedia("(prefers-reduced-motion: reduce)");let hi=null,Jt=null;const Os=new Map;function Ep(){for(const[t,e]of Os)t.removeEventListener("animationend",e),t.classList.remove("panel-in"),t.style.animationDelay="";Os.clear(),document.querySelectorAll(".code-line.is-in").forEach(t=>t.classList.remove("is-in"))}function Gn(){if(Ep(),hi){const t=hi;hi=null,t.animation?.cancel(),t.ghost.remove(),t.panel.style.visibility="",delete t.panel.dataset.morphing,t.panel.inert=!1}Jt&&(Jt.animation.cancel(),Jt.hero.classList.remove("is-exiting"),Jt.hero.style.cssText=Jt.style,Jt=null)}function D0(t){return(hi?.ghost||t)?.getBoundingClientRect()}function j0(t){Ep(),t.filter(Boolean).forEach((e,n)=>{if(e.classList.remove("panel-in"),e.style.animationDelay="",mr.matches||document.hidden)return;e.offsetWidth,e.style.animationDelay=`${n*80}ms`,e.classList.add("panel-in");function i(r){r.target===e&&(e.classList.remove("panel-in"),e.style.animationDelay="",e.removeEventListener("animationend",i),Os.delete(e))}Os.set(e,i),e.addEventListener("animationend",i)})}function U0(t,e){if(!t||!e||mr.matches||document.hidden||!t.animate)return;const n=t.style.cssText;t.classList.add("is-exiting"),innerWidth<=920&&(t.style.cssText=`position:absolute;left:0;top:64px;width:${e.width}px;height:${e.height}px;transform:none;`);const i=t.animate([{opacity:1},{opacity:0}],{duration:460,easing:"cubic-bezier(0.4,0,0.2,1)",fill:"both"});Jt={hero:t,animation:i,style:n},i.onfinish=()=>{Jt?.animation===i&&(t.classList.remove("is-exiting"),t.style.cssText=n,i.cancel(),Jt=null)}}function Sp(t,e,n,{results:i=!1}={}){if(Gn(),!e)return;const r=e.getBoundingClientRect(),s=()=>{e.style.visibility="",delete e.dataset.morphing,e.inert=!1,j0(n),(document.activeElement===document.body||document.getElementById("hero")?.contains(document.activeElement))&&e.querySelector(i?"#results-summary-tab":"#pipeline-edit-prompt")?.focus({preventScroll:!0})};if(mr.matches||document.hidden||!e.animate||!t?.width||!r.width||i&&innerWidth<=920){s();return}e.style.visibility="hidden",e.dataset.morphing="true",e.inert=!0;const o=document.createElement("div");o.className="composer-morph",o.setAttribute("aria-hidden","true");const a=innerWidth>920?Math.min(1,innerWidth/1920):1;o.style.cssText=`left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border-width:${2*a}px;border-radius:${20*a}px;`,document.body.appendChild(o);const l=t.left+t.width/2-r.left-r.width/2,u=t.top+t.height/2-r.top-r.height/2,c=t.width/r.width,d=t.height/r.height,f=`translate(${l}px,${u}px) scale(${c},${d})`,p=o.animate([{transform:f,opacity:0,offset:0,easing:"cubic-bezier(.2,0,0,1)"},{transform:f,opacity:1,offset:.14,easing:"cubic-bezier(.4,0,.2,1)"},{transform:`translate(${l}px,${u}px) scale(${c*.93},${d*.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:1120,fill:"both"}),h={panel:e,ghost:o,animation:p};hi=h,p.onfinish=()=>{hi===h&&(Gn(),s())}}window.addEventListener("resize",Gn);window.addEventListener("pagehide",Gn);document.addEventListener("visibilitychange",()=>{document.hidden&&Gn()});mr.addEventListener("change",()=>{mr.matches&&Gn()});const $d="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",H0="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",W0="https://us.i.posthog.com";jh.init(H0,{api_host:W0,person_profiles:"identified_only"});function Dn(t,e={}){try{jh.capture(t,e)}catch(n){console.error("PostHog tracking failed",n)}}const Et="https://4tgke4.buildship.run",xp={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},Bs="ccc_auth_session",fl="ccc_signin_return",q0=1800*1e3,Ld=new WeakSet;let H={email:null,sessionToken:null,isVerified:!1};function Kn(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let de=Kn({isResolved:!0}),hl=Promise.resolve();const z0=`${Et}/service/runpipeline`,V0="bs_user_id",G0="bs_identity_token",K0=`${Et}/authUserCheck`;let yt={userId:null,token:null,status:null,resolved:!1};const Ds=ly,js="ccc_subscription",Nd=3,Y0=new Set(["active","trialing","paid"]),Us="google/gemini-3.7-flash",ss=["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"],J0={"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 nn(t){return J0[t]||t}const Z0=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 Ip(t){return Z0.has(t)}const pl=4,ya=8*1024*1024,X0="https://4tgke4.buildship.run/service/runpipeline-image";let De=[];const Sn=[],Q0=3e4;let uc=null;function ew(t,e){return new Promise(n=>{const i=new FileReader,r=o=>{e?.removeEventListener("abort",s),n(o)},s=()=>{i.abort(),r(null)};if(i.onload=()=>r(i.result),i.onerror=()=>r(null),e){if(e.aborted){n(null);return}e.addEventListener("abort",s,{once:!0})}i.readAsDataURL(t)})}async function tw(t,e){const n=new FormData;return n.append("file",t),(await fetch(X0,{method:"POST",body:n,signal:e})).json()}function nw(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 iw(t,e,n){const i=await ew(t,n);i&&De.includes(e)&&(e.dataUrl=i,yn());let r="";if(i)try{r=nw(await tw(t,n))}catch{r=""}return De.includes(e)?!i||!r?(De.splice(De.indexOf(e),1),yn(),"failed"):(e.url=r,yn(),"added"):"dropped"}function kp(t){const e=Sn.indexOf(t);e>=0&&Sn.splice(e,1),Pp()}function Cp(t){t.controller.abort(),kp(t);const e=De.indexOf(t.slot);e>=0&&(De.splice(e,1),yn())}function Pp(){uc?.setAttachmentsPending(Sn.length>0)}async function rw(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>ya);n.length&&Ee(`Skipped ${n.length} image(s) over the ${(ya/1024/1024).toFixed(0)} MB limit.`,"warning");const i=e.filter(u=>u.size<=ya);if(!i.length)return;const r=pl-De.length,s=i.slice(0,r);if(i.length>r&&Ee(`You can attach up to ${pl} images.`,"info"),!s.length)return;const o=s.map(u=>{const c={dataUrl:null,name:u.name,url:null};De.push(c);const d={slot:c,controller:new AbortController},f=setTimeout(()=>d.controller.abort(),Q0);return d.job=iw(u,c,d.controller.signal),Sn.push(d),d.job.finally(()=>{clearTimeout(f),kp(d)}),d.job});yn(),Pp();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 sw(t){if(y.isRunning){Ee("Wait for the current generation to finish before removing images.","info");return}const e=De[t],n=Sn.find(i=>i.slot===e);if(n){Cp(n);return}De.splice(t,1),yn()}function yn(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",De.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=De.length>=pl?"Image limit reached":"Add images"))}function dc(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),n=Ip(e?.value);t.classList.toggle("hidden",!n),!n&&De.length&&!y.isRunning&&(Sn.slice().forEach(Cp),De=[],yn())}const Wn="ccc_usage",Ap="google/gemini-3.7-flash",Fp="google/gemini-3.7-flash",Yr="google/gemini-3.7-flash",Ji={professional:11,power:49},gl={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"},os={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 as={...os};async function ow(){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(os),...Object.values(ml),...Object.values(gl)]);for(const a of o)a!=="AUD"&&(typeof r[a]=="number"&&r[a]>0?s[a]=r[a]:os[a]&&(s[a]=os[a]));as=s}catch{}finally{clearTimeout(e)}}const ml={"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 fc(){try{const s=Intl.DateTimeFormat().resolvedOptions().timeZone;if(s&&ml[s])return ml[s]}catch{}const e=(navigator.language||"en-US").replace("-","_"),n=gl[e];if(n)return n;const i=e.split("_")[0],r=gl[i];return r||"USD"}function Zi(t,e){const n=as[e]??as.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*as.USD)}}const _t="ccc_api_key_",Tt="ccc_session_api_key_",Nt="ccc_encryption_key",vr="ccc_encryption_key_scope",aw="ccc_keystore",Hs="keys",yr="ccc_encryption_key_version";let vl=null,Ws=null,_r=!1,qs=!1,Od=!1;class zs extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function Bd(){if(Od)return;Od=!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 Rp(){return localStorage.getItem(yr)||""}function yl(){return crypto.randomUUID?.()||Mp(crypto.getRandomValues(new Uint8Array(16)))}function lw(){const t=Rp();if(t)return t;const e=yl();return localStorage.setItem(yr,e),e}function Ii(){vl=null,Ws=null,_r=!1,qs=!1}window.addEventListener("storage",t=>{t.key===yr&&Ii()});function cw(){return new Promise((t,e)=>{const n=indexedDB.open(aw,1);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(Hs)||i.createObjectStore(Hs)},n.onsuccess=()=>t(n.result),n.onerror=()=>e(n.error)})}async function hc(t,e){const n=await cw();return new Promise((i,r)=>{const s=n.transaction(Hs,t);let o;try{o=e(s.objectStore(Hs))}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 uw(t){return t instanceof CryptoKey&&t.algorithm?.name==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function dw(){const t=await hc("readonly",e=>e.get(Nt));return uw(t)?t:null}async function Tp(t){await hc("readwrite",e=>e.put(t,Nt))}async function fw(){Ii();try{await hc("readwrite",t=>t.delete(Nt))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function hw(){const t=sessionStorage.getItem(Nt);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Tp(e),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),e}async function Dd(t){const e=sessionStorage.getItem(Nt);if(e)return qs=sessionStorage.getItem(vr)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new zs;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await crypto.subtle.exportKey("jwk",n);return sessionStorage.setItem(Nt,JSON.stringify(i)),sessionStorage.setItem(vr,"session"),qs=!1,crypto.subtle.importKey("jwk",i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function pw(t){if(sessionStorage.getItem(vr)==="session"&&sessionStorage.getItem(Nt))return Bd(),_r=!0,Dd(t);try{const e=await dw();if(e)return e;const n=await hw();if(n)return n;const i=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Tp(i),i}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),Bd(),_r=!0,Dd(t)}}async function pc(t={}){const{allowSessionFallbackCreation:e=!0}=t,n=lw();Ws!==n&&Ii();const i=vl||pw(e);vl=i,Ws=n;try{return await i}catch(r){throw Ii(),r}}async function gw(t){const e=await pc(),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:Mp(o),keyVersion:n,sessionFallback:_r}}async function mw(t,e={}){const{isSessionCredential:n=!1}=e;try{const i=await pc({allowSessionFallbackCreation:!1});if(_r&&!n&&!qs)throw new zs;const r=vw(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 zs)throw i;return console.error("Decryption failed:",i),null}}function Mp(t){const e=new Uint8Array(t);let n="";for(let i=0;i0}let Ie="",Mt="",sr=null,Ud=0,ot="not-configured",gt=0,_l=0,wl=0,ao=0,Zt=0,un=0,Ze=null,$t=null,wr=null;function _w(){return _l+=1,_l}function ww(){return wl+=1,wl}function br(t,e,n){Ze=t?{projectId:t,key:e,generation:n}:null}function bl(t,e=Ie){if(!t)return!1;const n=Ze;return n?n.projectId===t&&n.key===e&&n.generation===gt:!1}function gc(t,e,n){if(!Mt||Ze&&Ze.projectId!==Mt)return;(t||[]).some(r=>(r.id||r.projectId)===Mt)?br(Mt,e,n):Ze&&br("",null,null)}function $p({seq:t,currentSeq:e,generation:n,storedKeyAtStart:i,requestKey:r}){return t!==e||n!==gt?!1:i===Ie||r===Ie}async function mc(){sessionStorage.getItem(Nt)&&await pc(),Ie=await Me("flutterflow"),Mt=await Me("flutterflow_project_id"),kw(),pn(),Ie?wc():(ot="not-configured",bt())}let Er=!1;function Lp(){const t=document.getElementById("api-keys-modal");Ve(t),_c(),Ie&&uo(Ie)}function vc(){Er=!1,Lp()}function bw(){Er=!0;const t=document.getElementById("walkthrough-modal");t&&Ge(t),Lp()}let Hd=!1;function Wd(){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 qd(){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=nn(t.value),r=Ip(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.`),dc()}function Np(){if(Er=!1,Wd(),qd(),!Hd){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")),Wd(),qd()}),Hd=!0}const t=document.querySelector('.composer [aria-label="Generation settings"]');Ve("composer-settings-modal",{trigger:t})}function Ew(t){t&&t.target!==t.currentTarget||Ge("composer-settings-modal")}function Op(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&Ge(e);const n=Er;if(Er=!1,n){const i=document.getElementById("walkthrough-modal");i&&(ot==="connected"&&yc(),Ve(i))}}let dn=1;function Bp(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function lo(){const t=Bp();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===dn?(e.classList.add("wt-current"),r&&(r.textContent=i)):i0&&dn<=t&&(dn++,lo())}function Sw(){const t=document.getElementById("walkthrough-modal");t&&(dn=1,lo(),Ve(t))}function xw(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&Ge(e);const n=document.getElementById("walkthrough-dont-show");n&&n.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Dp(){if(H.isVerified&&Ot()&&de.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(dn=1,lo(),Ve(e))}}async function _c(){const t=document.getElementById("flutterflow-api-key-input");Ie?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Iw()}function Iw(){zd("flutterflow","flutterflow-key-status"),zd("flutterflow_project_id","flutterflow-project-status")}function zd(t,e){const n=document.getElementById(e);if(!n)return;const i=n.querySelector(".key-status-dot"),r=n.querySelector("span");Ft(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 pn(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff");e&&e.classList.toggle("hidden",!t)}function kw(){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"?Ft("flutterflow")&&Ft("flutterflow_project_id")?(i.className="key-status-dot configured",i.title="FlutterFlow (Fully configured)"):Ft("flutterflow")||Ft("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)"):Ft(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)")}),pn()}async function Cw(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select"),n=t.value.trim(),i=!!n&&n!==Ie,r=e?.value.trim()||"";if(n){const l=await Me("flutterflow").catch(()=>"");await jd("flutterflow",n),n!==l&&!r&&ls()}const s=n||Ie;if(r){if(!co(r)){Ee("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}bl(r,s)?await jd("flutterflow_project_id",r):(i?ls():Ze=null,e.value="",s&&!($t&&$t.key===s&&$t.generation===gt)&&uo(s))}else i&&ls();await mc(),n&&await wc(),_c();const o=document.querySelector("#api-keys-modal .bg-blue-500"),a=o.textContent;o.textContent="Saved!",o.classList.remove("bg-blue-500","hover:bg-blue-600"),o.classList.add("bg-green-500"),setTimeout(()=>{o.textContent=a,o.classList.remove("bg-green-500"),o.classList.add("bg-blue-500","hover:bg-blue-600"),Op()},1e3)}async function Pw(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(yr,yl()),Ii(),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),sessionStorage.removeItem(Nt),sessionStorage.removeItem(vr),localStorage.removeItem(_t+"salt"),await fw(),localStorage.setItem(yr,yl()),localStorage.removeItem(_t+"flutterflow"),localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow"),sessionStorage.removeItem(Tt+"flutterflow_project_id"),Ze=null,$t=null,wr=null,await mc();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),_c()}function co(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function bt(){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=ze();n.textContent=o.includes("staging")?"Staging":"Production"}if(i&&(i.textContent=Mt||"—"),!e)return;let r,s;if(!Ft("flutterflow"))r="Not connected — add your FlutterFlow API key",s="";else switch(ot){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 wc(){const t=ww(),e=++ao,n=gt,i=Ie,r=await Me("flutterflow"),s=()=>$p({seq:t,currentSeq:wl,generation:n,storedKeyAtStart:i,requestKey:r});if(!s()||e<=Zt)return null;const o=()=>{un=Math.max(un,e)};if(!r||!Ft("flutterflow"))return Zt=e,o(),ot="not-configured",bt(),null;ot="validating",bt();try{const l=await new In(r,"","main",ze()).listProjects();return!s()||e<=Zt?null:(Zt=e,o(),ot=l&&l.length>0?"connected":"no-projects",e>=un&&gc(l,r,n),bt(),l)}catch(a){if(!s()||e<=Zt)return null;Zt=e,o();const l=String(a&&a.message||"");return ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(l)?"unauthorized":"network-error",bt(),null}}function ls(){Mt="",Ze=null,localStorage.removeItem(_t+"flutterflow_project_id"),sessionStorage.removeItem(Tt+"flutterflow_project_id")}function Aw(){gt+=1,$t=null,wr=null,ls();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML='',t.value=""),Ft("flutterflow")?(ot="validating",uo(Ie)):ot="not-configured",bt()}function Fw(t,e){const n=document.getElementById(t);n&&(n.value?e?n.style.borderColor="#22c55e":n.style.borderColor="#ef4444":n.style.borderColor="")}function Rw(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",n=>{const i=n.target.value.trim().length>0;Fw("flutterflow-api-key-input",i)}),t.addEventListener("blur",Tw(async n=>{const i=n.target.value.trim();i&&await uo(i)},500)));const e=document.getElementById("flutterflow-projects-select");e&&e.addEventListener("change",()=>{const n=e.value.trim();n&&$t?br(n,$t.key,$t.generation):br("",null,null)})}function Tw(t,e){let n;return function(...r){const s=()=>{clearTimeout(n),t(...r)};clearTimeout(n),n=setTimeout(s,e)}}async function uo(t){const e=document.getElementById("flutterflow-projects-select"),n=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}const i=_w(),r=++ao,s=gt,o=Ie,a=()=>$p({seq:i,currentSeq:_l,generation:s,storedKeyAtStart:o,requestKey:t}),l=()=>r>Zt,u=()=>{Zt=Math.max(Zt,r)};$t=null,e.innerHTML='',n&&n.classList.add("hidden"),l()&&t===Ie&&(Ft("flutterflow")||t)&&(ot="validating"),bt();try{const d=await new In(t,"","main",ze()).listProjects();if(!a())return;$t={key:t,generation:s};const f=t===Ie,p=l()&&f;if(p&&u(),r>un&&f&&(un=r,gc(d,t,s)),!d||d.length===0){p&&(ot="no-projects",bt()),e.innerHTML='';return}p&&(ot="connected",bt()),e.innerHTML='',d.forEach(h=>{const g=document.createElement("option");g.value=h.id||h.projectId||"",g.textContent=h.name||h.projectName||`Project ${h.id}`,e.appendChild(g)}),Mt&&(e.value=Mt)}catch(c){if(!a())return;console.error("Failed to fetch projects:",c);const d=String(c&&c.message||"");l()&&t===Ie&&(u(),ot=/(401|403)|denied|unauthorized|scoped|list permission/i.test(d)?"unauthorized":"network-error",bt()),e.innerHTML='',n&&(n.textContent=`Failed to load projects: ${c.message}`,n.classList.remove("hidden"))}}function Mw(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 $w(){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 Lw(){y.bundleSpec=gr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function fo(){const t=Ei(y.bundleSpec);y.artifactBundle=gr(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=Wy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Ei(y.artifactBundle).id}function ho(){const t=gr(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=gr({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 jp(){const t=bc();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function bc(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Ei(t)}function Ec(){return bc().code||y.step2Result||""}async function Nw(){try{await mc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const cs={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Ow(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 In{constructor(e,n,i="main",r=cs.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=[cs.production,cs.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(El(f?d.clone():d,mp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 kd({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(Ow(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 El(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 Sc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Bw(t,e=mp){const n=t.clone();let i;try{i=JSON.parse(await El(t,e))}catch{let o="";try{o=await El(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 po(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 Z={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Up=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Hp=/extends\s+State<\w+>/;function Dw(t,e=""){if(t==="pubspec.yaml")return Z.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return Z.OTHER;if(t==="custom_functions.dart")return Z.FUNCTION;if(e){const n=Up.test(e),i=Hp.test(e);if(n||i)return Z.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return Z.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return Z.FUNCTION}return Z.CODE_FILE}function Wp(t,e){switch(e){case Z.ACTION:return`lib/custom_code/actions/${t}`;case Z.WIDGET:return`lib/custom_code/widgets/${t}`;case Z.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case Z.CODE_FILE:return`lib/custom_code/${t}`;case Z.DEPENDENCIES:return"pubspec.yaml";case Z.OTHER:return`lib/custom_code/${t}`;default:return t}}async function go(t,e=new Map){return Iy(t,e)}const Sl=new Map,pi=new Map,gi=new Map;function Pr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){Sl.delete(Pr(t))}function Qi(t,e,n){const i=Pr(t),r=pi.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?pi.delete(i):pi.set(i,r)}function jw(t,e){Qi(t,e,{uncertain:1})}function Uw(t){const e=Pr(t);gi.set(e,(gi.get(e)??0)+1)}function Vd(t){const e=Pr(t),n=(gi.get(e)??0)-1;n<=0?gi.delete(e):gi.set(e,n)}function Sc(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 mo(t,e,n=gp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Bw(s)})();return Sc(r,n,(s,o)=>{i.stop=!0,Yn(t),Uw(t),r.then(()=>Vd(t),()=>Vd(t)),o(new We("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 Hw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=a_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function xc(t,e,n,i,r="",s=gp){const o=o_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=S_();let l=!1;const u=f0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch($d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 p0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await Sc(g,s,(m,v)=>{p=!1,v(new We("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(Cd(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Cd(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Yn(t),jw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Qi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&yp(w)&&Qi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await F_({provisionEndpoint:$d,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Qi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:ol(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await Hw(t,o,m);throw l_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Yn(t),Qi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:ol(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Ic(t,e={}){const n=Pr(t);let i=Sl.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=hp(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=pi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&pi.delete(n)}!pi.has(n)&&!gi.has(n)&&Sl.set(n,i)}const r=await R0(i.pubspecYaml,e),s=a0(i.pubspecYaml,r.overrides),o=o0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Ww(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 $w(){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 Lw(){y.bundleSpec=pr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function fo(){const t=Ei(y.bundleSpec);y.artifactBundle=pr(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=Wy(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(n=>n.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=Ei(y.artifactBundle).id}function ho(){const t=pr(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=pr({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 jp(){const t=bc();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function bc(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t?.artifacts)?t.artifacts:[]).find(n=>n.id===y.selectedArtifactId)||Ei(t)}function Ec(){return bc().code||y.step2Result||""}async function Nw(){try{await mc()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const cs={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};function Ow(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 In{constructor(e,n,i="main",r=cs.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=[cs.production,cs.staging],s=Math.max(0,r.indexOf(this._endpoint));let o=!1,a=null;for(let l=0;lsetTimeout(h,1e3*(l+1)));continue}if(d.ok)return console.log(`Push to ${c} succeeded!`),d;a=d.status;const f=d.status<500&&!o;if(El(f?d.clone():d,mp).then(p=>console.log(`Push to ${c} returned ${d.status}: ${p}`),()=>console.log(`Push to ${c} returned ${d.status} (unreadable response body)`)),d.status>=500&&(o=!0),d.status===500){console.warn(`Endpoint ${c} returned 500, trying next...`),await new Promise(p=>setTimeout(p,1e3*(l+1)));continue}if(d.status>=500)throw new We(`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 We(`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 kd({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(Ow(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 El(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 Sc(i,e,(r,s)=>{try{n?.cancel()?.catch?.(()=>{})}catch{}s(new Error("The response body stalled before it finished."))})}async function Bw(t,e=mp){const n=t.clone();let i;try{i=JSON.parse(await El(t,e))}catch{let o="";try{o=await El(n,e)}catch{}if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:o||`HTTP ${t.status}`,errorMap:new Map};throw new We(`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 po(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 Z={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Up=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Hp=/extends\s+State<\w+>/;function Dw(t,e=""){if(t==="pubspec.yaml")return Z.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return Z.OTHER;if(t==="custom_functions.dart")return Z.FUNCTION;if(e){const n=Up.test(e),i=Hp.test(e);if(n||i)return Z.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return Z.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return Z.FUNCTION}return Z.CODE_FILE}function Wp(t,e){switch(e){case Z.ACTION:return`lib/custom_code/actions/${t}`;case Z.WIDGET:return`lib/custom_code/widgets/${t}`;case Z.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case Z.CODE_FILE:return`lib/custom_code/${t}`;case Z.DEPENDENCIES:return"pubspec.yaml";case Z.OTHER:return`lib/custom_code/${t}`;default:return t}}async function go(t,e=new Map){return Iy(t,e)}const Sl=new Map,pi=new Map,gi=new Map;function Cr(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Yn(t){Sl.delete(Cr(t))}function Xi(t,e,n){const i=Cr(t),r=pi.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?pi.delete(i):pi.set(i,r)}function jw(t,e){Xi(t,e,{uncertain:1})}function Uw(t){const e=Cr(t);gi.set(e,(gi.get(e)??0)+1)}function Vd(t){const e=Cr(t),n=(gi.get(e)??0)-1;n<=0?gi.delete(e):gi.set(e,n)}function Sc(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 mo(t,e,n=gp){const i={stop:!1},r=(async()=>{const s=await t.pushCode(e,i);return Bw(s)})();return Sc(r,n,(s,o)=>{i.stop=!0,Yn(t),Uw(t),r.then(()=>Vd(t),()=>Vd(t)),o(new We("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 Hw(t,e,n){let i;try{i=await Promise.race([t.fetchProjectSource(),new Promise((u,c)=>setTimeout(()=>c(new Error("read timed out")),2e4))])}catch{return n}const{landed:r,notLanded:s}=a_(e,i.files),o=u=>u.map(c=>c.className).join(", ");let a;s.length===0?a=`Checked FlutterFlow just now: all ${r.length} custom class(es) are in the project (${o(r)}). The final step, pushing your pubspec.yaml dependencies, did not run. Finish deploy to push the dependencies without re-writing the classes, or deploy again - classes already there are skipped, not duplicated.`:r.length===0?a=`Checked FlutterFlow just now: none of the ${s.length} custom class(es) are in the project yet (${o(s)}). The server may still be writing them. Wait a minute, then deploy again - the project is re-read first, so nothing is duplicated.`:a=`Checked FlutterFlow just now: ${r.length} of ${e.length} custom class(es) are in the project (${o(r)}); not there yet: ${o(s)}. Wait a minute, then deploy again - classes already there are skipped, and the rest are written.`;const l=new We(n?.causeDetail?`${n.causeDetail} ${a}`:a);return l.reconcilePartition={landed:r,notLanded:s},l}async function xc(t,e,n,i,r="",s=gp){const o=o_(e,n);if(o.length===0)return{remoteFiles:n,syncFileMap:e,unverified:[],approximate:[]};const a=S_();let l=!1;const u=f0(o,r),c={...u.manifest,sources:u.sources},d=u.skipped.map(m=>m.reason);d.forEach(m=>console.warn(`[custom class deploy] ${m}`));const f=u.approximate;f.forEach(m=>console.warn(`[custom class deploy] ${m}`)),console.log(`Provisioning ${o.length} new FlutterFlow custom code file(s) before sync.`),$e.set("provision");let p=!0,h,g;try{if(g=(async()=>{let m;try{m=await fetch($d,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:i,runId:a,customClasses:o,verification:c,stream:!0})})}catch{throw new We("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 p0(m,{onPhase:v=>{p&&$e.setSubstatus(v)},onLog:v=>{p&&console.log(`[custom class deploy] ${v}`)}})})(),h=await Sc(g,s,(m,v)=>{p=!1,v(new We("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(Cd(h)===Ne.FAILED)throw new Error(h.error||`FlutterFlow custom class provisioning failed (HTTP ${h.httpStatus}).`);const m=h.httpRejected&&typeof h.httpStatus=="number"?`The FlutterFlow deploy runner returned HTTP ${h.httpStatus} without reporting a result.`:"The connection to the FlutterFlow deploy runner dropped before it reported a result.",v=new We(`${m} The deploy may still be finishing on the server; open your FlutterFlow project to reconcile before retrying.`);throw v.causeDetail=m,v}if(!h.success){const m=h.details?` ${h.details}`:"",v=`${h.error||"FlutterFlow custom class provisioning failed."}${m}`;if(Cd(h)===Ne.UNCONFIRMED){const b=new We(`${v} The failure arrived after the deploy began — custom classes may already be written. Open your FlutterFlow project to reconcile before retrying.`);throw b.causeDetail=v,b}throw new Error(v)}}catch(m){if(m instanceof We){Yn(t),jw(t,o),g?.then(w=>{l||(w?.finalResultReceived&&w.success?Xi(t,o,{uncertain:-1,verified:1}):w?.finalResultReceived&&yp(w)&&Xi(t,o,{uncertain:-1}))},()=>{});let v={definitive:null};try{v=await F_({provisionEndpoint:$d,runId:a,apiKey:t.apiKey})}catch{v={definitive:null}}if(v.definitive==="success")return l=!0,Xi(t,o,{uncertain:-1,verified:1}),{remoteFiles:n,syncFileMap:ol(e,o),unverified:d,approximate:f,provisionSucceeded:!0};if(v.definitive==="failed")throw l=!0,new Error(v.error||"The deploy failed before writing anything.");const b=await Hw(t,o,m);throw l_(b.reconcilePartition)&&(b.finishDeploy={apiKey:t.apiKey,projectId:t.projectId,endpoint:t.baseUrl,branchName:t.branchName,fileMap:e,serializedYaml:r,landed:b.reconcilePartition.landed}),b}throw m}return Yn(t),Xi(t,o,{verified:1}),h.verificationSkipped&&(console.warn(`[custom class deploy] ${h.verificationSkipped}`),d.push(h.verificationSkipped)),{remoteFiles:n,syncFileMap:ol(e,o),unverified:d,approximate:f,provisionSucceeded:!0}}async function Ic(t,e={}){const n=Cr(t);let i=Sl.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=hp(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=pi.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.explainedByVerified=!0):f.explainedByVerified||(f.uncertain-=1),f.uncertain<=0&&f.verified<=0&&c.delete(d))}for(const[f,p]of[...c])p.verified=0,p.uncertain<=0&&c.delete(f);c.size===0&&l.delete(u)}l.size===0&&pi.delete(n)}!pi.has(n)&&!gi.has(n)&&Sl.set(n,i)}const r=await R0(i.pubspecYaml,e),s=a0(i.pubspecYaml,r.overrides),o=o0(s.yaml,r.additions);return r.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>{const l=r.additions[a],u=l?.sdk?`sdk: ${l.sdk}`:l||"any";return`${a}: ${u}`}).join(", "),r.sdk.dartSdkFloor?`(resolved for Dart ${r.sdk.dartSdkFloor})`:""),r.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:s.overridden,warnings:r.warnings,remoteFiles:i.files}}function Ww(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===Z.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=O_(t.content);if(s&&e.push(`FlutterFlow cannot format this code - ${s}. Fix or regenerate before committing.`),t.codeType===Z.WIDGET){const o=np(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=`${ip(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 qp(t,e={}){const{artifactType:n="CustomWidget",artifactName:i="GeneratedCode",fileName:r}=e,s=T_(t);let o=r||i;if(n==="CustomFunction")o="custom_functions.dart";else if(n==="CustomWidget"){const u=np(s)[0],c=u?ip(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=Z.CODE_FILE;switch(n){case"CustomAction":a=Z.ACTION;break;case"CustomWidget":a=Z.WIDGET;break;case"CustomFunction":a=Z.FUNCTION;break;case"CustomClass":case"CodeFile":a=Z.CODE_FILE;break}let l="";return a===Z.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; @@ -114,15 +114,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:Vy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function qw(t){const e={};for(const n of nc(t))e[n]="";return e}function zw(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 Vw(t,e,n,i=new Set,r=""){const s=[],o=Up.test(e),a=Hp.test(e);return n===Z.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function vo(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=>to(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=Vw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=hp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function kc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(bl(n,e))return n;const i=++ao,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==Ie||i<=un||(un=i,!s)?"":Ze&&Ze.projectId!==n&&bl(Ze.projectId,e)?Ze.projectId:((!Ze||Ze.projectId===n)&&Er(n,e,r),n)}async function Gw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=Z.WIDGET),i==="CustomAction"&&(i=Z.ACTION),i==="CustomFunction"&&(i=Z.FUNCTION),i==="CustomClass"&&(i=Z.CODE_FILE),i==="CodeFile"&&(i=Z.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await kc(o);if((o!==Ie||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!co(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||Dw(e,t),f=Wp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=vo(c);if(!p.valid)throw new Error(`Validation failed: +`),{content:Vy(s,l),fileName:o,codeType:a,artifactType:n,artifactName:i}}function qw(t){const e={};for(const n of nc(t))e[n]="";return e}function zw(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 Vw(t,e,n,i=new Set,r=""){const s=[],o=Up.test(e),a=Hp.test(e);return n===Z.WIDGET&&!o&&!a&&s.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:s.length===0,errors:s}}function vo(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=>to(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=Vw(r,s.content,s.type,i,s.artifactName);o.valid||e.push(...o.errors.map(a=>`${r}: ${a}`))}if(r==="pubspec.yaml"){const o=hp(s.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:n}}const ne={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},Y={currentState:ne.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=ne.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(ne).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===ne.PREPARING&&(this.startTime=Date.now()),(t===ne.SUCCESS||t===ne.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(ne.ERROR)},setSuccess(t){this.result=t,this.setState(ne.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===ne.PREPARING||this.currentState===ne.VALIDATING||this.currentState===ne.PUSHING}};async function kc(t){const e=t!==void 0?t:await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n)return"";if(bl(n,e))return n;const i=++ao,r=gt;let s=!1;try{s=(await new In(e,"","main",ze()).listProjects()||[]).some(l=>(l.id||l.projectId)===n)}catch(o){const a=String(o&&o.message||"");if(!/denied \(403\)|without list permission/i.test(a))return"";s=!0}return r!==gt||e!==Ie||i<=un||(un=i,!s)?"":Ze&&Ze.projectId!==n&&bl(Ze.projectId,e)?Ze.projectId:((!Ze||Ze.projectId===n)&&br(n,e,r),n)}async function Gw(t,e,n={}){let{codeType:i="W"}=n;const{pubspecDeps:r={},artifactName:s=e}=n;i==="CustomWidget"&&(i=Z.WIDGET),i==="CustomAction"&&(i=Z.ACTION),i==="CustomFunction"&&(i=Z.FUNCTION),i==="CustomClass"&&(i=Z.CODE_FILE),i==="CodeFile"&&(i=Z.CODE_FILE),Y.reset(),Y.setState(ne.PREPARING);try{const o=await Me("flutterflow"),a=ze();let l=await kc(o);if((o!==Ie||a!==ze())&&(l=""),!o)throw new Error("FlutterFlow API Key not configured. Please set your API key in the API Keys settings.");if(!l)throw new Error("No confirmed FlutterFlow project target. Choose a project from the loaded list in API Keys settings.");if(!co(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new In(o,l,"main",a);Y.setState(ne.VALIDATING);const c=new Map,d=i||Dw(e,t),f=Wp(e,d);c.set(e,{artifactName:s,content:t,type:d,path:f}),Y.setProgress(0,c.size);const p=vo(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const h=await Ic(u,r),g=h.yaml,m=await xc(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await go(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await yo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Yn(u),$e.set("push");const x=await mo(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||po(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function yo(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 Kw(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=qp(t,{artifactType:n,artifactName:i,fileName:r}),u=qw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=or||await kc(c);if((c!==Ie||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!co(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Wp(l.fileName,l.codeType),functionName:l.codeType===Z.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=vo(h);if(!g.valid)throw new Error(`File validation failed: +`)}`);const h=await Ic(u,r),g=h.yaml,m=await xc(u,c,h.remoteFiles,`Provision ${s} custom class`,g),v=await go(m.syncFileMap,m.remoteFiles),b=new Map(m.syncFileMap);b.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),$e.set("package");const w=await yo(b),_={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:v.fileMapContents,functions_map:v.functionsMapContents};Y.setState(ne.PUSHING),Y.setProgress(1,c.size),Yn(u),$e.set("push");const x=await mo(u,_);if(x.success)Y.setSuccess({fileCount:c.size,projectId:l,warnings:x.errorMap&&x.errorMap.size>0?Array.from(x.errorMap.entries()):[]});else{const I=x.errorMessage||po(x.responseCode),T=new Error(I);throw T.remoteRefusal=!0,T}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${l}`,addedDependencies:h.added,unverified:m.unverified,approximate:m.approximate,warnings:x.errorMap?Array.from(x.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),Y.setError(o),o instanceof We?{success:!1,unconfirmed:!0,error:o.message,state:Y.currentState}:{success:!1,error:o.message,remoteRefusal:o.remoteRefusal===!0,state:Y.currentState}}}async function yo(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 Kw(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:ze(),artifactType:n,artifactName:i,fileName:r};try{Y.setState(ne.PREPARING);const l=qp(t,{artifactType:n,artifactName:i,fileName:r}),u=qw(l.content);console.log("Detected dependencies:",u),Y.setState(ne.VALIDATING);const c=await Me("flutterflow"),d=ze(),f=await Me("flutterflow_project_id");let p=sr||await kc(c);if((c!==Ie||d!==ze())&&(p=""),!c)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!p)throw new Error(f?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!co(p))throw new Error("Invalid FlutterFlow Project ID format.");a.projectId=p;const h=new Map;h.set(l.fileName,{artifactName:i,content:l.content,type:l.codeType,path:Wp(l.fileName,l.codeType),functionName:l.codeType===Z.FUNCTION?i:void 0}),Y.setProgress(0,h.size);const g=vo(h);if(!g.valid)throw new Error(`File validation failed: ${g.errors.join(` `)}`);g.warnings.length>0&&console.warn("Validation warnings:",g.warnings),Y.setState(ne.PUSHING);const m=new In(c,p,"main",d),v=await Ic(m,u),b=v.yaml,w=await xc(m,h,v.remoteFiles,`Provision ${i} custom class`,b);o=w.provisionSucceeded===!0;const _=await go(w.syncFileMap,w.remoteFiles),x=new Map(w.syncFileMap);x.set("pubspec.yaml",{content:b,type:Z.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const I=await yo(x),T={project_id:p,zipped_custom_code:I,uid:`web_${Date.now()}`,branch_name:m.branchName,serialized_yaml:b,file_map:_.fileMapContents,functions_map:_.functionsMapContents};Y.setProgress(1,h.size),Yn(m),$e.set("push");const S=await mo(m,T);if(S.success){const P={...zw(l,s),projectId:p};return Y.setSuccess({...P,fileCount:h.size,warnings:S.errorMap?Array.from(S.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${l.fileName} to FlutterFlow`,metadata:P,targetIdentity:a,addedDependencies:v.added,unverified:w.unverified,approximate:w.approximate,warnings:S.errorMap?Array.from(S.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}else{const P=S.errorMessage||po(S.responseCode),R=new Error(P);throw R.errorMap=S.errorMap,R.remoteRefusal=!0,R}}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 We?{success:!1,unconfirmed:!0,error:l.message,errorMap:u,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...l.finishDeploy?{finishDeploy:fg(l.finishDeploy,a,Y)}:{}}: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,remoteRefusal:l.remoteRefusal===!0,targetIdentity:a,state:Y.currentState,elapsedTime:Y.getElapsedTime()}}}async function Yw(t,e={}){const{pipelineResult:n}=e;let i=!1;const r={projectId:null,endpoint:ze(),artifactType:"Bundle",artifactName:t?.title,fileName:t?.fileEntries?`${t.fileEntries.length} artifacts`:"bundle"};try{if(Y.setState(ne.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===Z.FUNCTION?I.artifactName:void 0}]));Y.setProgress(0,s.size);const o=vo(s);if(!o.valid)throw new Error(`File validation failed: ${o.errors.join(` -`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=or||await kc(a);if((a!==Ie||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!co(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Ic(d,t.dependencies),p=f.yaml,h=await xc(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await go(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:Z.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await yo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Yn(d),$e.set("push");const w=await mo(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||po(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:fg(s.finishDeploy,r,Y)}:{}}: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 Jw(t,e=[]){const n=Xl("architect");try{return await Ks("architect",Ap,hy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function _o(t,e,n=[],i){const r=py(t),s=Xl("generator",y.bundleSpec);try{return await Ks("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Yr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),nE(e,Yr,i);try{return await Ks("generator",Yr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Yr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function wo(t,e=null){const n={...Xl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ks("review",Fp,gy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Vs(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=` +`)}`);Y.setState(ne.VALIDATING);const a=await Me("flutterflow"),l=ze(),u=await Me("flutterflow_project_id");let c=sr||await kc(a);if((a!==Ie||l!==ze())&&(c=""),!a)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!c)throw new Error(u?"The FlutterFlow project target is not confirmed for your current API key. Reopen the deploy dialog and choose a project from the loaded list.":"FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!co(c))throw new Error("Invalid FlutterFlow Project ID format.");r.projectId=c,Y.setState(ne.PUSHING);const d=new In(a,c,"main",l),f=await Ic(d,t.dependencies),p=f.yaml,h=await xc(d,s,f.remoteFiles,`Provision ${t.title} custom classes`,p);i=h.provisionSucceeded===!0;const g=await go(h.syncFileMap,h.remoteFiles),m=new Map(h.syncFileMap);m.set("pubspec.yaml",{content:p,type:Z.DEPENDENCIES,path:"pubspec.yaml"}),$e.set("package");const v=await yo(m),b={project_id:c,zipped_custom_code:v,uid:`web_${Date.now()}`,branch_name:d.branchName,serialized_yaml:p,file_map:g.fileMapContents,functions_map:g.functionsMapContents};Y.setProgress(1,s.size),Yn(d),$e.set("push");const w=await mo(d,b);if(w.success){const I={...n,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((T,S)=>T+S.content.length,0),projectId:c};return Y.setSuccess({...I,fileCount:s.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:I,targetIdentity:r,addedDependencies:f.added,unverified:h.unverified,approximate:h.approximate,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:Y.getElapsedTime()}}const _=w.errorMessage||po(w.responseCode),x=new Error(_);throw x.errorMap=w.errorMap,x.remoteRefusal=!0,x}catch(s){console.error("Bundle commit execution failed:",s),Y.setError(s);const o=s.errorMap||new Map;return s instanceof We?{success:!1,unconfirmed:!0,error:s.message,errorMap:o,targetIdentity:r,state:Y.currentState,elapsedTime:Y.getElapsedTime(),...s.finishDeploy?{finishDeploy:fg(s.finishDeploy,r,Y)}:{}}: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 Jw(t,e=[]){const n=Xl("architect");try{return await Ks("architect",Ap,hy(t),n,e)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Prompt Architect failed: ${i.message}`)}}async function _o(t,e,n=[],i){const r=py(t),s=Xl("generator",y.bundleSpec);try{return await Ks("generator",e,r,s,n)}catch(o){if(o.isModelArmor||o.isUsageLimit||o.isPipelineCancel)throw o;if(e!==Yr){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,o.message),nE(e,Yr,i);try{return await Ks("generator",Yr,r,s,n)}catch(a){throw a.isModelArmor||a.isUsageLimit||a.isPipelineCancel?a:new Error(`Code Generator failed: primary (${e}): ${o.message} | fallback (${Yr}): ${a.message}`)}}throw new Error(`Code Generator failed: ${o.message}`)}}async function wo(t,e=null){const n={...Xl("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ks("review",Fp,gy(t),n)}catch(i){throw i.isModelArmor||i.isUsageLimit||i.isPipelineCancel?i:new Error(`Code Review failed: ${i.message}`)}}function Vs(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=` @@ -130,12 +130,12 @@ ${o.errors.join(` `):i.innerHTML=` - `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Vs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Vs(t,"completed"))}function Zw(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 Xw(t){at(parseInt(t.replace("step","")))}function at(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"),Jn();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 Qw(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 xl(t){const e=Il(t);console.log(`Step 1 (Prompt Architect): ${nn(Ap)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(Fp)}`)}function zp(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function eb(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=Ei(y.artifactBundle)?.id||null)}const Vp="results-replacement-error";function tb(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Vp);if(!r)return;const s=wp(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=`${xo[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=()=>ki(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Cc(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Cc(){const t=document.getElementById(Vp);t&&(t.hidden=!0)}function Gp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),eb(e),Ai(),Bt(!0),Mr(),y.resultsViewMode=e.resultsViewMode||"summary",Tr(),kn(),tb(t,{stage:n,runId:i,retry:r}),pn())}async function Kp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Io();Pc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=zp();n.forEach(r=>{r.disabled=!0,r.innerHTML=` + `)}function Fe(t,e){const n=document.getElementById(`step${t}-loading`),i=document.getElementById(`step${t}-result`);e?(n.classList.remove("hidden"),i.classList.add("hidden"),Vs(t,"active")):(n.classList.add("hidden"),i.classList.remove("hidden"),Vs(t,"completed"))}function Zw(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 Xw(t){at(parseInt(t.replace("step","")))}function at(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"),Jn();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 Qw(t){const e=document.getElementById(t);if(!e)return;const n=e.dataset.raw||e.textContent;navigator.clipboard.writeText(n).then(()=>{Dn("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 xl(t){const e=Il(t);console.log(`Step 1 (Prompt Architect): ${nn(Ap)}`),console.log(e!==t?`Step 2 (Code Generator): ${nn(t)} → ${nn(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${nn(t)}`),console.log(`Step 3 (Code Review): ${nn(Fp)}`)}function zp(){return{step1Result:y.step1Result,step2Result:y.step2Result,step3Result:y.step3Result,artifactBundle:y.artifactBundle,bundleReview:y.bundleReview,selectedArtifactId:y.selectedArtifactId,resultsViewMode:y.resultsViewMode}}function eb(t){if(!t)return;Object.assign(y,t),new Set((y.artifactBundle?.artifacts||[]).map(n=>n.id)).has(y.selectedArtifactId)||(y.selectedArtifactId=Ei(y.artifactBundle)?.id||null)}const Vp="results-replacement-error";function tb(t,{stage:e=2,runId:n,retry:i}){if(!le(n))return;const r=document.getElementById(Vp);if(!r)return;const s=wp(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=`${xo[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=()=>Ar(),c=u)),l&&(l.hidden=s.canUpgrade,s.canUpgrade||(l.onclick=()=>{Cc(),typeof i=="function"&&i()},l.textContent="Retry",c=l)),(c||r).focus({preventScroll:!0})}function Cc(){const t=document.getElementById(Vp);t&&(t.hidden=!0)}function Gp(t,{previous:e,stage:n,runId:i,retry:r}){le(i)&&(t.isUsageLimit&&_n(),eb(e),Pi(),Bt(!0),Mr(),y.resultsViewMode=e.resultsViewMode||"summary",Tr(),kn(),tb(t,{stage:n,runId:i,retry:r}),pn())}async function Kp(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0;const e=Io();Pc("standardRegenerate",y.step2Result,y.step1Result);const n=document.querySelectorAll(".btn-refine-action"),i=zp();n.forEach(r=>{r.disabled=!0,r.innerHTML=` - Refining...`});try{Cc();const r=bc(),s=r.id,o=my({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."});Po({runId:e}),Lt(2,e),at(2),Fe(2,!0);const a=await _o(o,t,[],e);if(!le(e))return;y.step2Result=a,fo(),fn(2,e);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,e),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,ho(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=Ei(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ai();const f=oo(y.step3Result);Mr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=so(r,{architect:2,generator:2,review:3});Gp(r,{previous:i,stage:s,runId:e,retry:Kp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function Pc(t,e,n){const i=`${Et}/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 nb(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Yp(){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=Io();Pc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{Cc();const r=bc(),s=r.id,o=my({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."});Po({runId:e}),Lt(2,e),at(2),Fe(2,!0);const a=await _o(o,t,[],e);if(!le(e))return;y.step2Result=a,fo(),fn(2,e);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,e),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(e))return;y.step3Result=c,ho(),fn(3,e),y.artifactBundle?.artifacts?.some(p=>p.id===s)?y.selectedArtifactId=s:y.selectedArtifactId=Ei(y.artifactBundle)?.id||null;const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=oo(y.step3Result);Mr(u,f)}catch(r){if(console.error("Refinement failed:",r),!le(e))return;const s=so(r,{architect:2,generator:2,review:3});Gp(r,{previous:i,stage:s,runId:e,retry:Kp})}finally{n.forEach(r=>{r.disabled=!1,r.textContent="Refine & Regenerate"}),le(e)&&(y.isRunning=!1,pn())}}async function Pc(t,e,n){const i=`${Et}/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 nb(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Yp(){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=Io();Pc("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);const s=zp();try{Cc();const o=Yh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});xg(),Po({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await _o(o,n,[],i);if(!le(i))return;y.step2Result=a,fo(),fn(2,i);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,ho(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ai();const f=oo(y.step3Result);Mr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=so(o,{architect:2,generator:2,review:3});Gp(o,{previous:s,stage:a,runId:i,retry:Yp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function xr(){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=De.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Io();try{if(await hl,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await kb(t)||!le(i)||(await wb(),!le(i)))return;const r=Il(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),$w(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Js(!0),xl(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Po({prompt:t,runId:i}),oE(a,l),at(1),Lt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await Jw(t,u);if(!le(i))return;y.step1Result=c,Lw(),fn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=xi(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Lt(2,i),Fe(2,!0);const p=await _o(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,fo(),fn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=xi(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const m=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,ho(),fn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Ai();const b=oo(y.step3Result);Mr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=so(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():Dn("Pipeline Failed",{error:r.message,effectiveModel:Il(document.getElementById("code-generator-model").value)}),at(s),Fe(s,!1),wg(r,{stage:s,runId:i}),Vs(s,"error")}finally{le(i)&&(y.isRunning=!1,Js(!1),pn())}}function ib(){const t=document.getElementById("code-generator-model").value,e=[Us,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? + Fixing…`);const s=zp();try{Cc();const o=Yh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});xg(),Po({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await _o(o,n,[],i);if(!le(i))return;y.step2Result=a,fo(),fn(2,i);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,ho(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=oo(y.step3Result);Mr(u,f),t&&(t.value="")}catch(o){if(console.error("Fix from errors failed:",o),!le(i))return;const a=so(o,{architect:2,generator:2,review:3});Gp(o,{previous:s,stage:a,runId:i,retry:Yp})}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}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=De.slice();if(!t.trim()){Ee("Please describe your FlutterFlow widget first.","warning");return}y.isRunning=!0;const i=Io();try{if(await hl,!le(i)||(Sn.length&&await Promise.allSettled(Sn.map(w=>w.job)),!le(i))||!await kb(t)||!le(i)||(await wb(),!le(i)))return;const r=Il(e);Dn("Pipeline Started",{selectedModel:e,effectiveModel:r,inputLength:t.length}),$w(),y.submittedPrompt=t,y.submittedImages=n.filter(w=>w.url),Js(!0),xl(r),Jn();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");const o=document.getElementById("paywall-exhausted");o&&o.classList.add("hidden");const a=document.getElementById("composer")?.getBoundingClientRect(),l=document.getElementById("hero")?.getBoundingClientRect();Po({prompt:t,runId:i}),oE(a,l),at(1),Lt(1,i),Fe(1,!0);const u=y.submittedImages.map(w=>({url:w.url})),c=await Jw(t,u);if(!le(i))return;y.step1Result=c,Lw(),fn(1,i),Dn("Prompt Architect Completed");const d=document.getElementById("step1-output"),f=xi(y.step1Result);d.textContent=f,d.dataset.raw=f,Fe(1,!1),at(2),Lt(2,i),Fe(2,!0);const p=await _o(y.step1Result,r,u,i);if(!le(i))return;y.step2Result=p,fo(),fn(2,i),Dn("Code Generator Completed");const h=document.getElementById("step2-output"),g=xi(y.step2Result);h.textContent=g,h.dataset.raw=g,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const m=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=m,ho(),fn(3,i),Dn("Code Review Completed");const v=document.getElementById("step3-output");v.textContent=y.step3Result,Fe(3,!1),Pi();const b=oo(y.step3Result);Mr(g,b)}catch(r){if(r.isPipelineCancel||console.error("Pipeline failed:",r),!le(i))return;const s=so(r,{architect:1,generator:2,review:3});r.isUsageLimit?_n():Dn("Pipeline Failed",{error:r.message,effectiveModel:Il(document.getElementById("code-generator-model").value)}),at(s),Fe(s,!1),wg(r,{stage:s,runId:i}),Vs(s,"error")}finally{le(i)&&(y.isRunning=!1,Js(!1),pn())}}function ib(){const t=document.getElementById("code-generator-model").value,e=[Us,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(i=>i!==t),n=prompt(`Retry with different model? Current: ${t} @@ -143,7 +143,7 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);n==="1"?(document.getElementById("code-generator-model").value=e[0],xr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],xr())}async function rb(){const t=Ec();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),vc();return}if(y.artifactBundle?.artifacts?.length>1){await sb();return}const{artifactType:i,artifactName:r,fileName:s}=jp(),o=qp(t,{artifactType:i,artifactName:r,fileName:s}),a=Ww(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Rc(o,a,null,null)}async function sb(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),vc();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=vo(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],Sr()):n==="2"&&(document.getElementById("code-generator-model").value=e[1],Sr())}async function rb(){const t=Ec();if(!t){Ee("No code to commit. Please run the pipeline first.","warning");return}const e=await Me("flutterflow"),n=await Me("flutterflow_project_id");if(!e||!n){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),vc();return}if(y.artifactBundle?.artifacts?.length>1){await sb();return}const{artifactType:i,artifactName:r,fileName:s}=jp(),o=qp(t,{artifactType:i,artifactName:r,fileName:s}),a=Ww(o);if(!a.canProceed){Ee(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Rc(o,a,null,null)}async function sb(){const t=await Me("flutterflow"),e=await Me("flutterflow_project_id");if(!t||!e){Ee("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),vc();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=vo(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};Rc(o,s,n.dependencies,n)}function ob(t){let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let n=`
    @@ -167,10 +167,10 @@ ${a.content}`).join(` Error: ${g} `}else s+=`${t} -`;const o=Yh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Po({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await _o(o,n,[],i);if(!le(i))return;y.step2Result=a,fo(),fn(2,i);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,ho(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ai();const f=oo(y.step3Result);Mr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=so(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),wg(s,{stage:o,runId:i,retry:()=>Jp(t,e)}),Vs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function ab(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 Zp(t){try{const e=await fetch(`${Et}/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 lb(t){try{const n=await(await fetch(`${Et}/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 cb(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Gd(t,e){const n=Qp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,de=Kn({isLoading:!0}),localStorage.setItem(Bs,JSON.stringify({email:t,sessionToken:e})),i&&rg()}function Xp(){H.email=null,H.sessionToken=null,H.isVerified=!1,de=Kn({isResolved:!0}),localStorage.removeItem(Bs),localStorage.removeItem(js)}function Qp(){try{const t=localStorage.getItem(Bs);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Bs),{email:null,sessionToken:null}}}async function ub(){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 lb(e);Gd(n,i),eg();const r=Kd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){Kd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),bo(),ui(i,"error")}}else{const{email:n,sessionToken:i}=Qp();if(n&&i){const r=await cb(i);r?Gd(r.email,r.sessionToken):Xp()}}Ac()}function db(){try{localStorage.setItem(fl,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function Kd(){try{const t=localStorage.getItem(fl);if(localStorage.removeItem(fl),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>q0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function bo(){const t=document.getElementById("signin-modal");if(!t)return;db(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ui(""),Ve(t)}function eg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function ui(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 fb(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=io(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"),ui("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=rp(n);r&&ui(r,"error");try{const s=await Zp(n),o=sc(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ui(sp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ui("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function hb(){H.email=null,H.sessionToken=null,H.isVerified=!1,de=Kn({isResolved:!0}),X_({storage:window.localStorage,onIdentityChanged:Ac,onPlanChanged:So})}const pb=e0({sendLink:Zp,getEmail:()=>H.email||"",onState:gb});function gb(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=sp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function mb(){await pb()}function vb(){const t=J_(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 yb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function _b(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Ac(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Fb(),So()}async function tg(){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(K0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(V0,r.user_id),yt.token&&sessionStorage.setItem(G0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),_n()}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 _a=null;function wb(t=5e3){return yt.resolved?Promise.resolve():(_a||(_a=tg().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([_a,new Promise(e=>setTimeout(e,t))]))}function ng(){const t=xn();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Ar(){const t=ng();return t.month!==xn()?{count:0,month:xn()}:t}function bb(){const e={count:Ar().count+1,month:xn()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Pi(){return!!de.isLoading}function Ot(){return!!de.isResolved}function Eb(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(Ds,e)?e:null}function Sb(t){return t&&Object.entries(xp).find(([,e])=>e===t)?.[0]||null}function Jr(...t){return t.find(e=>e!=null&&e!=="")}function xb(...t){return t.find(e=>e&&typeof e=="object")||{}}function Ib(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=xb(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=Jr(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=Jr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=Eb(Jr(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=Y0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Sb(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Jr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Eo(){return Ds[de.tier]??Ds.free}async function kb(t){if(H.isVerified&&(!Ot()||Pi())&&(await ig({force:!0}),So()),H.isVerified&&!Ot())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:e}=Ar(),n=Eo();if(e>=n)return Cb(e,n,{openModal:!0,prompt:t}),!1;const i=Math.floor(n*.8);if(e>=i){const r=n-e;Ee(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Yd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Cb(t,e,n={}){Bt(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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"),ki();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=de.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");if(d&&d.classList.toggle("hidden",H.isVerified),n.prompt!=null){y.submittedPrompt=n.prompt;const f=document.getElementById("pipeline-submitted-prompt");f&&(f.textContent=n.prompt)}u.classList.remove("hidden"),n.openModal&&ki()}function Il(t){return de.tier==="free"&&ss.includes(t)?Us:t}function Pb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=de.tier,r=!(H.isVerified&&!Ot())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=ss.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&ss.includes(e.value)&&(e.value=Us),e.disabled=!1,Ld.has(e)||(e.addEventListener("change",()=>{Ot()&&de.tier==="free"&&ss.includes(e.value)&&(e.value=Us,ki()),xl(e.value),dc()}),Ld.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(),xl(e.value)}function Fc(){const t=H.isVerified&&!!H.email,e=t&&Pi(),n=!t||Ot(),i=Ar(),r=n?i.count:0,s=n?Eo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Zl,u=n?de.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ng(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Ds.free} generations used`}}Ab()}function Ab(){if(!(H.isVerified&&!!H.email))return;const e=Pi(),n=Ot(),i=Ar(),r=n?i.count:0,s=n?Eo():0,o=Math.max(0,s-r),a=n?de.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Xi(Zi[a]??0,fc());h.textContent=`${S} / 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 S=Date.parse(de.periodEnd||""),P=n&&a!=="free"&&!!de.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Fc(),H.isVerified&&(Pi()||!Ot())){Yd();return}const{count:t}=Ar();tString(s.error).toLowerCase().includes(a))){Xp(),Ac();return}de=Kn({isResolved:!1,error:s.error});return}de=Ib(s),localStorage.setItem(js,JSON.stringify({version:Nd,data:de,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),de={...de,isLoading:!1,isResolved:!1,error:r.message}}}function rg(){localStorage.removeItem(js)}async function Rb(t){if(!H.isVerified||!H.sessionToken){og(),bo();return}if(!xp[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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:fc()})})).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 Tb(t){if(!H.isVerified||!H.sessionToken){bo();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Gs=new Set;function sg(){Gs.forEach(t=>t.abort()),Gs.clear()}async function Ks(t,e,n,i={},r=[]){const o=new AbortController;Gs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(z0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Wn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=Sy(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),_n())}else bb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Gs.delete(o)}}let kl=!1;function Mb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),rg(),kl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function $b(){if(!kl)return;kl=!1;const t=de.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 So(){const t=H.isVerified&&!!H.email,e=de.tier,n=t&&Pi(),i=!t||Ot(),r=document.getElementById("subscription-tier-badge");if(r){const a=Zl,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"),Lb(i?e:null),Pb(),dc(),_n(),Ig()}function Lb(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 Nb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=uy[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 Cl(){const t=fc(),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=Xi(Zi.professional,t)),n&&(n.textContent=Xi(Zi.power,t)),i&&(i.textContent=Xi(Zi.professional,t)),r&&(r.textContent=Xi(Zi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function ki(){Cl();const t=document.getElementById("pricing-modal");t&&Ve(t),ow().then(()=>Cl())}function og(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(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()=>{ay(),Zb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Ob(),window.__heroField=m0(),window.__pipelineLogo=w0(),yE(),uc=B0({onSubmit:xr}),hl=(async()=>{try{await ub(),Mb(),await ig()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await hl,$b(),So(),Cl(),Nb(),await Nw(),Rw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Dp(),tg();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(yc(),lo())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(pg(),$e.phaseId||Mc(),Zd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(Zd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,$c()},1e3))}),Hc()});function Ob(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Bb(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Dp()}let ar=null;async function Pl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ud,n=++ao,i=()=>e===Ud,r=gt;br=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==Ie)return Pl();if(n>un&&(un=n,gc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),br={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==Ie)return Pl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function Db(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=br;return!n||n.key!==Ie||n.generation!==gt?null:e}function Rc(t,e,n,i=null){ar={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,Pl();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function ag(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),ar=null}function jb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 lg(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function cg(t){$c(),ob(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,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(rc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function ug(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 dg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Al=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Tc(t,{heading:e,title:n,guidance:i})}let Al=null;function fg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function Ub(){const t=Al;if(!t||Lc)return;Al=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);hg(),Nc(!0),Mc();try{$e.set("package");const n=c_(t.fileMap,t.landed,t.serializedYaml),i=await go(n,new Map),r=await yo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),$e.set("push");const o=await mo(e,s);if(o.success){Ys({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||po(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ys({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function hg(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function Hb(){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 Jd={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}},Wb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function pg(){Un&&clearTimeout(Un),Un=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){pg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(ad(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Jd[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=Jd[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=Wb.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(qb(e)),gg(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&&(ad(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function qb(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 Mc(t){$e.start(t)}function $c(){$e.stop()}function gg(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 Zd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,gg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function zb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===Z.CODE_FILE):t.codeInfo?.codeType===Z.CODE_FILE}let Lc=!1;function Nc(t){Lc=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 Ys(t){$c(),Nc(!1);const e=vp(t);e===Ne.COMMITTED?lg(t):e===Ne.PARTIAL?ug(t):e===Ne.UNCONFIRMED?dg(t):cg(t)}async function Vb(){if(!ar){console.error("No pending commit data");return}if(Lc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=ar;if(ar=null,or=Db(),ag(),Nc(!0),Mc({withProvisioning:zb(t)}),t.bundlePlan){const o=await Yw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});or=null,Ys(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=jp(),s=await Kw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});or=null,Ys(s)}window.runThinkingPipeline=xr;window.toggleStep=Xw;window.toggleSection=Zw;window.selectWorkflowStep=at;window.copyCode=Qw;window.retryWithDifferentModel=ib;window.openApiKeysModal=vc;window.closeApiKeysModal=Op;window.openComposerSettings=Np;window.closeComposerSettings=Ew;window.walkthroughConnectAccount=bw;window.closeWalkthroughModal=xw;window.openWalkthroughModal=Sw;window.advanceWalkthrough=yc;window.commitToFlutterFlow=Gw;function Gb(){y.isRunning||Bt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Kb(){Np();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Gb;window.openModelSelector=Kb;window.handlePromptImageSelect=rw;window.removePromptImage=sw;window.saveApiKeys=Cw;window.validateFlutterFlowConnection=wc;window.clearAllApiKeys=Pw;window.toggleKeyVisibility=Mw;window.handleWelcomeVideoEnd=Bb;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=rb;window.updateFlutterFlowCredentialStatus=ab;window.openCommitConfirmModal=Rc;window.closeCommitConfirmModal=ag;window.closeCommitSuccessModal=jb;window.closeCommitTerminalModal=hg;window.finishProvisionedDeploy=Ub;window.showCommitPartialModal=ug;window.showCommitUnconfirmedModal=dg;window.showCommitSuccessModal=lg;window.showCommitFailureModal=cg;window.toggleCodePreview=Hb;window.confirmCommitToFlutterFlow=Vb;window.runRefinement=Kp;window.regenerateFromPastedErrors=Yp;window.clearErrorInput=nb;window.setFlutterFlowEndpoint=yw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=bo;window.closeSignInModal=eg;window.handleMagicLinkRequest=fb;window.handleSignOut=hb;window.handleSendNewLink=mb;window.handleClearCache=vb;window.handleDeleteAccount=yb;window.closeDeleteUnavailableModal=_b;window.startCheckout=Rb;window.openCustomerPortal=Tb;window.openPricingModal=ki;window.closePricingModal=og;let us=null,mg=null,hn={1:"pending",2:"pending",3:"pending"},qn=1,Fl=null,Oc=null;const xo={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Yb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Jb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Io(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function vg(){y.runId+=1}function Bc(t){return document.getElementById(`pdot-${t}`)}const yg=window.matchMedia("(max-width: 920px)");function Xd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=yg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Zb(){Xd(),yg.addEventListener("change",Xd)}function Xb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Js(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 ko(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){hn[t]=e;const n=Bc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=xo[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 Qb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Fr(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${eE()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function eE(){const t=33.333333333333336,e=hn[qn];if(e==="active"&&Fl!==null){const n=(Date.now()-Fl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:Qb()/3*100}function Co(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?Jb[t]:Yb[t]),i&&(i.textContent=Xb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${xo[t]}${a}`}}function tE(t){hn[t]==="pending"||hn[t]==="skipped"||(Oc=t,[1,2,3].forEach(e=>{const n=Bc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Co(t))}function Dc(){Oc=null,[1,2,3].forEach(t=>{const e=Bc(t);e&&e.removeAttribute("aria-pressed")})}function _g(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function nE(t,e,n){le(n)&&_g(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function jc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function iE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Gn()}function rE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function sE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=sE;function oE(t,e){Sp(t,document.getElementById("main-stage-container"),rE()),U0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function Po(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Rr(),kn(),Bt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),ko("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}mg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Dc(),jc(),_g(""),[1,2,3].forEach(a=>zn(a,"pending")),Lt(1,n),aE()}function Lt(t,e){le(e)&&(qn=t,Fl=Date.now(),Dc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),Co(t),Fr())}function fn(t,e){le(e)&&(zn(t,"done"),Oc===null&&Co(t,{done:!0}),Fr())}function wg(t,{stage:e=1,runId:n,retry:i=bg}={}){if(!le(n))return;Ao(),Rr(),kn(),ko("failed"),Bt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Dc(),Co(e),Fr();const o=wp(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=`${xo[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>ki()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Rl}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Rl}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Rl(){vg(),sg(),y.isRunning=!1,Js(!1),pn(),ko("settled"),kn(),Ao(),Rr(),jc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Bt(!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 bg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),jc(),xr()}function aE(){Ao(),us=setInterval(()=>{const t=(Date.now()-mg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Fr()},250)}function Ao(){us&&(clearInterval(us),us=null)}let lr=null;function Rr(){lr&&(clearTimeout(lr),lr=null)}function Ai(){Ao(),Rr(),ko("settled"),Fr();const t=document.getElementById("pipeline-progress-fill");lr=setTimeout(()=>{lr=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ci(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Eg(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function lE(){return w_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function cE(t){return` +`;const o=Yh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});Po({runId:i}),Lt(2,i),at(2),Fe(2,!0);const a=await _o(o,n,[],i);if(!le(i))return;y.step2Result=a,fo(),fn(2,i);const l=document.getElementById("step2-output"),u=xi(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Lt(3,i),Fe(3,!0);const c=await wo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,ho(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Pi();const f=oo(y.step3Result);Mr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=so(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),wg(s,{stage:o,runId:i,retry:()=>Jp(t,e)}),Vs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function ab(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 Zp(t){try{const e=await fetch(`${Et}/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 lb(t){try{const n=await(await fetch(`${Et}/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 cb(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Gd(t,e){const n=Qp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,de=Kn({isLoading:!0}),localStorage.setItem(Bs,JSON.stringify({email:t,sessionToken:e})),i&&rg()}function Xp(){H.email=null,H.sessionToken=null,H.isVerified=!1,de=Kn({isResolved:!0}),localStorage.removeItem(Bs),localStorage.removeItem(js)}function Qp(){try{const t=localStorage.getItem(Bs);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(Bs),{email:null,sessionToken:null}}}async function ub(){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 lb(e);Gd(n,i),eg();const r=Kd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){Kd();const i=n.message||"Sign-in link invalid or expired.";Ee(i,"error"),bo(),ui(i,"error")}}else{const{email:n,sessionToken:i}=Qp();if(n&&i){const r=await cb(i);r?Gd(r.email,r.sessionToken):Xp()}}Ac()}function db(){try{localStorage.setItem(fl,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function Kd(){try{const t=localStorage.getItem(fl);if(localStorage.removeItem(fl),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>q0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function bo(){const t=document.getElementById("signin-modal");if(!t)return;db(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),ui(""),Ve(t)}function eg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function ui(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 fb(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=io(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"),ui("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=rp(n);r&&ui(r,"error");try{const s=await Zp(n),o=sc(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),ui(sp(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),ui("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function hb(){H.email=null,H.sessionToken=null,H.isVerified=!1,de=Kn({isResolved:!0}),X_({storage:window.localStorage,onIdentityChanged:Ac,onPlanChanged:So})}const pb=e0({sendLink:Zp,getEmail:()=>H.email||"",onState:gb});function gb(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=sp(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function mb(){await pb()}function vb(){const t=J_(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 yb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function _b(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function Ac(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Fb(),So()}async function tg(){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(K0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(V0,r.user_id),yt.token&&sessionStorage.setItem(G0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Wn,JSON.stringify({count:a,month:s})),_n()}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 _a=null;function wb(t=5e3){return yt.resolved?Promise.resolve():(_a||(_a=tg().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([_a,new Promise(e=>setTimeout(e,t))]))}function ng(){const t=xn();try{const e=localStorage.getItem(Wn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Wn,month:t,err:e}),localStorage.removeItem(Wn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Pr(){const t=ng();return t.month!==xn()?{count:0,month:xn()}:t}function bb(){const e={count:Pr().count+1,month:xn()};return localStorage.setItem(Wn,JSON.stringify(e)),e}function Ci(){return!!de.isLoading}function Ot(){return!!de.isResolved}function Eb(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(Ds,e)?e:null}function Sb(t){return t&&Object.entries(xp).find(([,e])=>e===t)?.[0]||null}function Jr(...t){return t.find(e=>e!=null&&e!=="")}function xb(...t){return t.find(e=>e&&typeof e=="object")||{}}function Ib(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=xb(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=Jr(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=Jr(e.status,e.subscriptionStatus,e.subscription_status,n.status,"none"),o=Eb(Jr(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=Y0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Sb(r)||(a||l?"professional":"free");return Kn({tier:u,status:s,periodEnd:Jr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function Eo(){return Ds[de.tier]??Ds.free}async function kb(t){if(H.isVerified&&(!Ot()||Ci())&&(await ig({force:!0}),So()),H.isVerified&&!Ot())return Ee("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:e}=Pr(),n=Eo();if(e>=n)return Cb(e,n,{prompt:t}),!1;const i=Math.floor(n*.8);if(e>=i){const r=n-e;Ee(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Yd(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Cb(t,e,n={}){Bt(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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"),Ar();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=de.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");if(d&&d.classList.toggle("hidden",H.isVerified),n.prompt!=null){y.submittedPrompt=n.prompt;const f=document.getElementById("pipeline-submitted-prompt");f&&(f.textContent=n.prompt)}u.classList.remove("hidden")}function Il(t){return de.tier==="free"&&ss.includes(t)?Us:t}function Pb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=de.tier,r=!(H.isVerified&&!Ot())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=ss.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&ss.includes(e.value)&&(e.value=Us),e.disabled=!1,Ld.has(e)||(e.addEventListener("change",()=>{Ot()&&de.tier==="free"&&ss.includes(e.value)&&(e.value=Us,Ar()),xl(e.value),dc()}),Ld.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(),xl(e.value)}function Fc(){const t=H.isVerified&&!!H.email,e=t&&Ci(),n=!t||Ot(),i=Pr(),r=n?i.count:0,s=n?Eo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Zl,u=n?de.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=ng(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Ds.free} generations used`}}Ab()}function Ab(){if(!(H.isVerified&&!!H.email))return;const e=Ci(),n=Ot(),i=Pr(),r=n?i.count:0,s=n?Eo():0,o=Math.max(0,s-r),a=n?de.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Zi(Ji[a]??0,fc());h.textContent=`${S} / 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 S=Date.parse(de.periodEnd||""),P=n&&a!=="free"&&!!de.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Fc(),H.isVerified&&(Ci()||!Ot())){Yd();return}const{count:t}=Pr();tString(s.error).toLowerCase().includes(a))){Xp(),Ac();return}de=Kn({isResolved:!1,error:s.error});return}de=Ib(s),localStorage.setItem(js,JSON.stringify({version:Nd,data:de,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),de={...de,isLoading:!1,isResolved:!1,error:r.message}}}function rg(){localStorage.removeItem(js)}async function Rb(t){if(!H.isVerified||!H.sessionToken){og(),bo();return}if(!xp[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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:fc()})})).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 Tb(t){if(!H.isVerified||!H.sessionToken){bo();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Ee("Could not open billing portal. Please try again.","error")}}const Gs=new Set;function sg(){Gs.forEach(t=>t.abort()),Gs.clear()}async function Ks(t,e,n,i={},r=[]){const o=new AbortController;Gs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(z0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Wn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=Sy(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Wn,JSON.stringify({count:d.usage_count,month:h})),_n())}else bb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),Gs.delete(o)}}let kl=!1;function Mb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),rg(),kl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Ee("Checkout cancelled.","info")),e}function $b(){if(!kl)return;kl=!1;const t=de.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 So(){const t=H.isVerified&&!!H.email,e=de.tier,n=t&&Ci(),i=!t||Ot(),r=document.getElementById("subscription-tier-badge");if(r){const a=Zl,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"),Lb(i?e:null),Pb(),dc(),_n(),Ig()}function Lb(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 Nb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=uy[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 Cl(){const t=fc(),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=Zi(Ji.professional,t)),n&&(n.textContent=Zi(Ji.power,t)),i&&(i.textContent=Zi(Ji.professional,t)),r&&(r.textContent=Zi(Ji.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function Ar(){Cl();const t=document.getElementById("pricing-modal");t&&Ve(t),ow().then(()=>Cl())}function og(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(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()=>{ay(),Zb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Ob(),window.__heroField=m0(),window.__pipelineLogo=w0(),yE(),uc=B0({onSubmit:Sr}),hl=(async()=>{try{await ub(),Mb(),await ig()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await hl,$b(),So(),Cl(),Nb(),await Nw(),Rw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Dp(),tg();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(yc(),lo())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(pg(),$e.phaseId||Mc(),Zd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(Zd(i),Un&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,$c()},1e3))}),Hc()});function Ob(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Bb(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jn),document.addEventListener("keydown",Jn))}function Jn(){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",Jn),document.removeEventListener("keydown",Jn),Dp()}let or=null;async function Pl(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Ud,n=++ao,i=()=>e===Ud,r=gt;wr=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==Ie)return Pl();if(n>un&&(un=n,gc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),wr={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==Ie)return Pl();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function Db(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=wr;return!n||n.key!==Ie||n.generation!==gt?null:e}function Rc(t,e,n,i=null){or={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,Pl();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function ag(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),or=null}function jb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 lg(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function cg(t){$c(),ob(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,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(rc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function ug(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 dg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(Al=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Tc(t,{heading:e,title:n,guidance:i})}let Al=null;function fg(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function Ub(){const t=Al;if(!t||Lc)return;Al=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);hg(),Nc(!0),Mc();try{$e.set("package");const n=c_(t.fileMap,t.landed,t.serializedYaml),i=await go(n,new Map),r=await yo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Yn(e),$e.set("push");const o=await mo(e,s);if(o.success){Ys({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||po(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Ys({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function hg(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function Hb(){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 Jd={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}},Wb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let Un=null;function pg(){Un&&clearTimeout(Un),Un=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){pg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(ad(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!Jd[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=Jd[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=Wb.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(qb(e)),gg(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&&(ad(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function qb(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 Mc(t){$e.start(t)}function $c(){$e.stop()}function gg(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 Zd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,gg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function zb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===Z.CODE_FILE):t.codeInfo?.codeType===Z.CODE_FILE}let Lc=!1;function Nc(t){Lc=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 Ys(t){$c(),Nc(!1);const e=vp(t);e===Ne.COMMITTED?lg(t):e===Ne.PARTIAL?ug(t):e===Ne.UNCONFIRMED?dg(t):cg(t)}async function Vb(){if(!or){console.error("No pending commit data");return}if(Lc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=or;if(or=null,sr=Db(),ag(),Nc(!0),Mc({withProvisioning:zb(t)}),t.bundlePlan){const o=await Yw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ys(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=jp(),s=await Kw(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});sr=null,Ys(s)}window.runThinkingPipeline=Sr;window.toggleStep=Xw;window.toggleSection=Zw;window.selectWorkflowStep=at;window.copyCode=Qw;window.retryWithDifferentModel=ib;window.openApiKeysModal=vc;window.closeApiKeysModal=Op;window.openComposerSettings=Np;window.closeComposerSettings=Ew;window.walkthroughConnectAccount=bw;window.closeWalkthroughModal=xw;window.openWalkthroughModal=Sw;window.advanceWalkthrough=yc;window.commitToFlutterFlow=Gw;function Gb(){y.isRunning||Bt(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Kb(){Np();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Gb;window.openModelSelector=Kb;window.handlePromptImageSelect=rw;window.removePromptImage=sw;window.saveApiKeys=Cw;window.validateFlutterFlowConnection=wc;window.clearAllApiKeys=Pw;window.toggleKeyVisibility=Mw;window.handleWelcomeVideoEnd=Bb;window.dismissWelcomeVideo=Jn;window.initiateCommitToFlutterFlow=rb;window.updateFlutterFlowCredentialStatus=ab;window.openCommitConfirmModal=Rc;window.closeCommitConfirmModal=ag;window.closeCommitSuccessModal=jb;window.closeCommitTerminalModal=hg;window.finishProvisionedDeploy=Ub;window.showCommitPartialModal=ug;window.showCommitUnconfirmedModal=dg;window.showCommitSuccessModal=lg;window.showCommitFailureModal=cg;window.toggleCodePreview=Hb;window.confirmCommitToFlutterFlow=Vb;window.runRefinement=Kp;window.regenerateFromPastedErrors=Yp;window.clearErrorInput=nb;window.setFlutterFlowEndpoint=yw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=bo;window.closeSignInModal=eg;window.handleMagicLinkRequest=fb;window.handleSignOut=hb;window.handleSendNewLink=mb;window.handleClearCache=vb;window.handleDeleteAccount=yb;window.closeDeleteUnavailableModal=_b;window.startCheckout=Rb;window.openCustomerPortal=Tb;window.openPricingModal=Ar;window.closePricingModal=og;let us=null,mg=null,hn={1:"pending",2:"pending",3:"pending"},qn=1,Fl=null,Oc=null;const xo={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},Yb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},Jb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function Io(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function vg(){y.runId+=1}function Bc(t){return document.getElementById(`pdot-${t}`)}const yg=window.matchMedia("(max-width: 920px)");function Xd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=yg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Zb(){Xd(),yg.addEventListener("change",Xd)}function Xb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Js(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 ko(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function zn(t,e){hn[t]=e;const n=Bc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=xo[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 Qb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Fr(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[qn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${eE()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${qn} of 3`)}function eE(){const t=33.333333333333336,e=hn[qn];if(e==="active"&&Fl!==null){const n=(Date.now()-Fl)/1e3;return(qn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?qn/3*100:Qb()/3*100}function Co(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?Jb[t]:Yb[t]),i&&(i.textContent=Xb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${xo[t]}${a}`}}function tE(t){hn[t]==="pending"||hn[t]==="skipped"||(Oc=t,[1,2,3].forEach(e=>{const n=Bc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Co(t))}function Dc(){Oc=null,[1,2,3].forEach(t=>{const e=Bc(t);e&&e.removeAttribute("aria-pressed")})}function _g(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function nE(t,e,n){le(n)&&_g(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function jc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function iE(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Gn()}function rE(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function sE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=sE;function oE(t,e){Sp(t,document.getElementById("main-stage-container"),rE()),U0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function Po(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Rr(),kn(),Bt(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),ko("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}mg=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Dc(),jc(),_g(""),[1,2,3].forEach(a=>zn(a,"pending")),Lt(1,n),aE()}function Lt(t,e){le(e)&&(qn=t,Fl=Date.now(),Dc(),[1,2,3].forEach(n=>{n===t?zn(n,"active"):nt&&zn(n,"pending")}),Co(t),Fr())}function fn(t,e){le(e)&&(zn(t,"done"),Oc===null&&Co(t,{done:!0}),Fr())}function wg(t,{stage:e=1,runId:n,retry:i=bg}={}){if(!le(n))return;Ao(),Rr(),kn(),ko("failed"),Bt(!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"),zn(e,"failed"),[1,2,3].forEach(h=>{h>e&&zn(h,"pending")}),qn=e,Dc(),Co(e),Fr();const o=wp(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=`${xo[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>Ar()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Rl}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Rl}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Rl(){vg(),sg(),y.isRunning=!1,Js(!1),pn(),ko("settled"),kn(),Ao(),Rr(),jc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Bt(!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 bg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),jc(),Sr()}function aE(){Ao(),us=setInterval(()=>{const t=(Date.now()-mg)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Fr()},250)}function Ao(){us&&(clearInterval(us),us=null)}let ar=null;function Rr(){ar&&(clearTimeout(ar),ar=null)}function Pi(){Ao(),Rr(),ko("settled"),Fr();const t=document.getElementById("pipeline-progress-fill");ar=setTimeout(()=>{ar=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function ki(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function Eg(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function lE(){return w_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function cE(t){return`
    - ${Ci(t.severity)} + ${ki(t.severity)}
    ${W(t.message)}
    ${t.suggestion?`
    ${W(t.suggestion)}
    `:""} @@ -188,7 +188,7 @@ Error: ${g}
      ${t.findings.map(u=>`
    • - ${Ci(u.severity)} + ${ki(u.severity)} ${W(u.message)} ${u.suggestion?`${W(u.suggestion)}`:""} @@ -198,7 +198,7 @@ Error: ${g}
    `:"",a=t.warnings.length?`
    -

    ${Ci("warning")} Bundle

    +

    ${ki("warning")} Bundle

      ${t.warnings.map(u=>`
    • ${W(u)}
    • `).join("")}
    @@ -251,14 +251,14 @@ Error: ${g}
    - `}function fE(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(cE).join(""):`
    ${Ci(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>` + `}function fE(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(cE).join(""):`
    ${ki(n.icon)} ${W(n.message)}
    `,r=e.dependencies?.length?e.dependencies.map(l=>`
  • ${W(l.name)}${l.version?` ${W(l.version)}`:""}${l.reason?`

    ${W(l.reason)}

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

    ${W(l.description)}

    `:""}
  • `).join(""):'
  • No relationships for this file
  • ';return`
    - ${Ci(e.status)} ${W(Eg(e.status))} + ${ki(e.status)} ${W(Eg(e.status))}

    ${W(e.artifactName)}

    ${e.description?`

    ${W(e.description)}

    `:""}
    @@ -318,11 +318,11 @@ Error: ${g} tabindex="${o?0:-1}" title="${on(`${Eg(s.status)} · ${s.fileName||s.artifactName}`)}" > - ${Ci(s.status)} + ${ki(s.status)} ${W(s.artifactName)} ${W(s.artifactType)} `}).join(""),i.onclick=s=>{const o=s.target.closest(".artifact-tab");o?.dataset?.artifactId&&Uc(o.dataset.artifactId)},Qd()),e&&e.classList.add("visible")}function Qd(){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")Sg();else{const a=s.dataset.artifactId;a&&Uc(a)}const o=s.id==="results-summary-tab"?document.getElementById("results-summary-tab"):document.querySelector(`#artifact-tabs .artifact-tab[data-artifact-id="${s.dataset.artifactId}"]`);o&&o.focus()}))}function Tr(){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=lE(),o=Ec();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")}dE(s),hE(s),e&&(e.textContent=""),e&&(e.replaceChildren(),o.split(` -`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=bp(a),!iE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=fE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Mr(t,e){const n=document.getElementById("main-stage-container"),i=D0(n),r=document.body.classList.contains("results-fullscreen");Rr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),Bt(!0),y.selectedArtifactId||(y.selectedArtifactId=Ei(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Tr(),pn(),pE(),r||Sp(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function pE(){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 Uc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Tr()}function Sg(){y.resultsViewMode="summary",Tr()}function gE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ec(),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 mE(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 Pc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function vE(){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 xg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function yE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function Bt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function Ig(){const t=H.isVerified&&!!H.email,e=de.tier||"free",n=t&&Pi(),i=!t||Ot(),s=n?"Checking…":i?Zl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Fc();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 _E(){Ig();const t=document.getElementById("credits-modal");t&&Ve(t)}function wE(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function kg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),uc?.cancelTyping?.(),y.isRunning&&(vg(),sg(),y.isRunning=!1,Js(!1),Ai(),y.artifactBundle?Tr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")Bt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&Bt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ef=!1;function Hc(){const t=window.location.hash.replace(/^#/,"");kg(t||"home",!1,ef),ef=!0}window.addEventListener("popstate",t=>{Hc()});window.addEventListener("hashchange",()=>{Hc()});window.copyResultsCode=gE;window.selectArtifact=Uc;window.selectResultsSummary=Sg;window.submitResultsFeedback=mE;window.showErrorInputPanel=vE;window.hideErrorInputPanel=xg;window.setGenerationStageVisible=Bt;window.switchView=kg;window.selectPipelineStage=tE;window.editPipelinePrompt=Rl;window.retryPipelineRun=bg;window.openCreditsModal=_E;window.closeCreditsModal=wE; +`).forEach((a,l)=>{const u=document.createElement("span");u.className="code-line",u.innerHTML=bp(a),!iE()&&y.resultsViewMode==="file"&&(u.classList.add("is-in"),u.style.setProperty("--d",`${l*10}ms`),u.addEventListener("animationend",()=>u.classList.remove("is-in"),{once:!0})),e.appendChild(u)})),n&&(n.innerHTML=fE(s)),i&&i.classList.toggle("hidden",y.resultsViewMode!=="summary"),r&&r.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function Mr(t,e){const n=document.getElementById("main-stage-container"),i=D0(n),r=document.body.classList.contains("results-fullscreen");Rr(),document.getElementById("pipeline-progress")?.classList.remove("visible"),Bt(!0),y.selectedArtifactId||(y.selectedArtifactId=Ei(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Tr(),pn(),pE(),r||Sp(i,n,["#bundle-strip",".summary-heading",".review-summary-text",".summary-spec",".review-score-column",".results-action-bar"].map(o=>document.querySelector(o)),{results:!0})}function pE(){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 Uc(t){y.selectedArtifactId=t,y.resultsViewMode="file",Tr()}function Sg(){y.resultsViewMode="summary",Tr()}function gE(){const t=document.getElementById("btn-copy-results"),e=document.getElementById("results-copy-status"),n=Ec(),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 mE(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 Pc(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."),Dn("Generation Feedback",{feedback:o})}catch{s(!1),r("Review feedback could not be sent. Tap again to retry.")}}function vE(){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 xg(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}function yE(){const t=document.getElementById("shell-stage"),e=document.getElementById("main-stage-container"),n=e?.querySelector(".pipeline-prompt-recap"),i=window.matchMedia("(max-width: 920px)"),r=()=>t?.style.setProperty("--fit",Math.min(1,document.documentElement.clientWidth/1920)),s=()=>{if(!n)return;const o=n.contains(document.activeElement)?document.activeElement:null;i.matches?e.appendChild(n):e.prepend(n),o?.focus({preventScroll:!0})};r(),s(),window.addEventListener("resize",r),i.addEventListener("change",s)}function Bt(t){const e=document.getElementById("generation-stage");if(!e)return;const n=document.getElementById("hero");n&&(n.hidden=t,n.inert=t),t?(e.hidden=!1,e.inert=!1,e.classList.add("is-active")):(kn(),document.body.classList.remove("results-fullscreen","results-with-sidebar"),e.classList.remove("is-active"),e.inert=!0,e.hidden=!0)}function Ig(){const t=H.isVerified&&!!H.email,e=de.tier||"free",n=t&&Ci(),i=!t||Ot(),s=n?"Checking…":i?Zl[e]||"Free":"—",o=document.getElementById("topbar-plan");o&&(o.textContent=s);const a=document.getElementById("topbar-avatar");a&&(a.textContent=(H.email||"?")[0].toUpperCase()),Fc();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 _E(){Ig();const t=document.getElementById("credits-modal");t&&Ve(t)}function wE(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("credits-modal");e&&Ge(e)}function kg(t,e=!0,n=!0){if(t=["home","account","plans"].includes(t)?t:"home",document.body.dataset.shellView=t,t!=="home"&&(kn(),uc?.cancelTyping?.(),y.isRunning&&(vg(),sg(),y.isRunning=!1,Js(!1),Pi(),y.artifactBundle?Tr():(document.getElementById("results-view")?.classList.remove("visible"),document.getElementById("ready-state")?.classList.remove("hidden")))),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")Bt(!1);else{const r=document.getElementById("main-stage-container");r&&r.classList.contains("visible")&&Bt(!0)}if(e){const r=t==="home"?"":`#${t}`;window.location.hash!==r&&window.history.pushState({view:t},"",r||"#")}}let ef=!1;function Hc(){const t=window.location.hash.replace(/^#/,"");kg(t||"home",!1,ef),ef=!0}window.addEventListener("popstate",t=>{Hc()});window.addEventListener("hashchange",()=>{Hc()});window.copyResultsCode=gE;window.selectArtifact=Uc;window.selectResultsSummary=Sg;window.submitResultsFeedback=mE;window.showErrorInputPanel=vE;window.hideErrorInputPanel=xg;window.setGenerationStageVisible=Bt;window.switchView=kg;window.selectPipelineStage=tE;window.editPipelinePrompt=Rl;window.retryPipelineRun=bg;window.openCreditsModal=_E;window.closeCreditsModal=wE; diff --git a/dist/index.html b/dist/index.html index 8f9f9a8..a725d44 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3273,7 +3273,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + diff --git a/e2e/stu382-plans-paywall.spec.js b/e2e/stu382-plans-paywall.spec.js index a3e2ab0..95a46bc 100644 --- a/e2e/stu382-plans-paywall.spec.js +++ b/e2e/stu382-plans-paywall.spec.js @@ -96,8 +96,9 @@ test.describe("STU-382 plans surface and paywall states", () => { await expect(page.locator("#paywall-exhausted")).toBeHidden(); await expect(page.locator("#generation-stage")).toBeHidden(); - // Submitting the prompt is what surfaces the paywall, with the prompt in - // the recap and pricing open — and no generation request leaves. + // Submitting the prompt is what surfaces the paywall — only the screen, + // with the prompt in the recap and no pricing dialog stacked over it — and + // no generation request leaves. const prompt = "A habit tracker heatmap with streak counts"; await field.fill(prompt); await page.locator("#hero-send").click(); @@ -106,11 +107,16 @@ test.describe("STU-382 plans surface and paywall states", () => { `You've used all ${PLAN_LIMITS.free} free generations this month.`, ); await expect(page.locator("#pipeline-submitted-prompt")).toHaveText(prompt); - await expect(page.locator("#pricing-modal")).toHaveClass(/open/); + await expect(page.locator("#pricing-modal")).not.toHaveClass(/open/); - // Edit prompt goes back to the composer holding what the user wrote. + // Pricing opens when the user asks for it, from the screen's View Plans. + const viewPlans = page.locator("#paywall-exhausted").getByRole("button", { name: "View Plans" }); + await viewPlans.click(); + await expect(page.locator("#pricing-modal")).toHaveClass(/open/); await page.keyboard.press("Escape"); await expect(page.locator("#pricing-modal")).not.toHaveClass(/open/); + + // Edit prompt goes back to the composer holding what the user wrote. await page.locator("#pipeline-edit-prompt").click(); await expect(page.locator("#generation-stage")).toBeHidden(); await expect(field).toHaveValue(prompt); diff --git a/e2e/stu391-tutorial-onboarding.spec.js b/e2e/stu391-tutorial-onboarding.spec.js index 451f700..6e144e8 100644 --- a/e2e/stu391-tutorial-onboarding.spec.js +++ b/e2e/stu391-tutorial-onboarding.spec.js @@ -357,8 +357,8 @@ test.describe("STU-391 tutorial + connection onboarding", () => { // observed, not assumed: resolveIdentity writes it and calls // updateUsageDisplay in one synchronous block, so the key reappearing at the // limit means the decision has fully run. A run attempt is not passive: an - // out-of-runs run surfaces the paywall with the submitted prompt, takes the - // tour with it, and opens pricing. + // out-of-runs run surfaces the paywall screen with the submitted prompt and + // takes the tour with it; pricing waits for the screen's View Plans. test("an out-of-runs startup never surfaces the paywall; a run attempt does, with the prompt", async ({ page }) => { let releaseIdentity; const identityGate = new Promise((resolve) => { @@ -439,7 +439,7 @@ test.describe("STU-391 tutorial + connection onboarding", () => { await expect(page.locator("#generation-stage")).toBeHidden(); // A run attempt is not passive: an out-of-runs run must surface the paywall - // in place of the tour, and open pricing so the user can act on it. + // screen in place of the tour — only the screen, no pricing dialog over it. await reopenWalkthrough(page); await expect(page.locator(WALKTHROUGH)).toHaveClass(/open/); @@ -450,7 +450,7 @@ test.describe("STU-391 tutorial + connection onboarding", () => { await expect(page.locator(WALKTHROUGH)).not.toHaveClass(/open/); await expect(page.locator(WALKTHROUGH)).toHaveAttribute("aria-hidden", "true"); await expect(page.locator("#paywall-exhausted")).toBeVisible(); - await expect(page.locator("#pricing-modal")).toHaveClass(/open/); + await expect(page.locator("#pricing-modal")).not.toHaveClass(/open/); // The paywall answers the submitted prompt: it sits in the recap. await expect(page.locator("#pipeline-submitted-prompt")).toHaveText( "A circular progress gauge", From c44c5d137befc2ab57e23650e741b9b75dcf08f7 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:20:12 +0000 Subject: [PATCH 08/10] fix(paywall): require the paywall element to exist for the visible check Co-Authored-By: Stuart Gardoll --- app.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app.js b/app.js index 0143536..fe9c12e 100644 --- a/app.js +++ b/app.js @@ -6895,7 +6895,8 @@ function updateUsageDisplay() { // cannot confirm it. const subscriptionUncertain = authState.isVerified && (isSubscriptionLoading() || !isSubscriptionResolved()) if (subscriptionUncertain || getUsage().count < getRunLimit()) { - const paywallWasVisible = !document.getElementById('paywall-exhausted')?.classList.contains('hidden') + const paywallEl = document.getElementById('paywall-exhausted') + const paywallWasVisible = !!paywallEl && !paywallEl.classList.contains('hidden') hidePaywallExhausted() // A correction that lands while the paywall is up (a stale stored count // replaced by a smaller authoritative one) frees runs: with nothing else From 6315c8a290129685c7429727302effc07c64c051 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:20:14 +0000 Subject: [PATCH 09/10] build: rebuild dist Co-Authored-By: Stuart Gardoll --- dist/assets/{index-jgsziodK.js => index-FNrAL4lj.js} | 2 +- dist/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename dist/assets/{index-jgsziodK.js => index-FNrAL4lj.js} (97%) diff --git a/dist/assets/index-jgsziodK.js b/dist/assets/index-FNrAL4lj.js similarity index 97% rename from dist/assets/index-jgsziodK.js rename to dist/assets/index-FNrAL4lj.js index d2b1d7c..43080b8 100644 --- a/dist/assets/index-jgsziodK.js +++ b/dist/assets/index-FNrAL4lj.js @@ -167,7 +167,7 @@ ${a.content}`).join(` Error: ${g} `}else s+=`${t} -`;const o=Hh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});ko({runId:i}),Nt(2,i),at(2),Fe(2,!0);const a=await vo(o,n,[],i);if(!le(i))return;y.step2Result=a,co(),fn(2,i);const l=document.getElementById("step2-output"),u=Ei(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Nt(3,i),Fe(3,!0);const c=await yo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,uo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ci();const f=ro(y.step3Result);Rr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=io(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),pg(s,{stage:o,runId:i,retry:()=>Wp(t,e)}),qs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function nb(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 qp(t){try{const e=await fetch(`${Et}/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 ib(t){try{const n=await(await fetch(`${Et}/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 rb(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Hd(t,e){const n=Vp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,fe=Gn({isLoading:!0}),localStorage.setItem(Ns,JSON.stringify({email:t,sessionToken:e})),i&&Xp()}function zp(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Gn({isResolved:!0}),localStorage.removeItem(Ns),localStorage.removeItem(Bs)}function Vp(){try{const t=localStorage.getItem(Ns);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(Ns),{email:null,sessionToken:null}}}async function sb(){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 ib(e);Hd(n,i),Gp();const r=Wd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){Wd();const i=n.message||"Sign-in link invalid or expired.";Se(i,"error"),_o(),li(i,"error")}}else{const{email:n,sessionToken:i}=Vp();if(n&&i){const r=await rb(i);r?Hd(r.email,r.sessionToken):zp()}}kc()}function ob(){try{localStorage.setItem(cl,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function Wd(){try{const t=localStorage.getItem(cl);if(localStorage.removeItem(cl),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>D0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function _o(){const t=document.getElementById("signin-modal");if(!t)return;ob(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),li(""),Ve(t)}function Gp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function li(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 ab(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=to(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"),li("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=Zh(n);r&&li(r,"error");try{const s=await qp(n),o=nc(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),li(Xh(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),li("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function lb(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Gn({isResolved:!0}),G_({storage:window.localStorage,onIdentityChanged:kc,onPlanChanged:bo})}const cb=Y_({sendLink:qp,getEmail:()=>H.email||"",onState:ub});function ub(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=Xh(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function db(){await cb()}function fb(){const t=z_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Se(`${e} Your run count, identity and stored keys are kept.`,"info")}function hb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function pb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function kc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Ib(),bo()}async function Kp(){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(W0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(U0,r.user_id),yt.token&&sessionStorage.setItem(H0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Hn,JSON.stringify({count:a,month:s})),_n()}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 ma=null;function gb(t=5e3){return yt.resolved?Promise.resolve():(ma||(ma=Kp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([ma,new Promise(e=>setTimeout(e,t))]))}function Yp(){const t=xn();try{const e=localStorage.getItem(Hn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Hn,month:t,err:e}),localStorage.removeItem(Hn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Cr(){const t=Yp();return t.month!==xn()?{count:0,month:xn()}:t}function mb(){const e={count:Cr().count+1,month:xn()};return localStorage.setItem(Hn,JSON.stringify(e)),e}function ki(){return!!fe.isLoading}function Bt(){return!!fe.isResolved}function vb(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(Os,e)?e:null}function yb(t){return t&&Object.entries(vp).find(([,e])=>e===t)?.[0]||null}function Kr(...t){return t.find(e=>e!=null&&e!=="")}function _b(...t){return t.find(e=>e&&typeof e=="object")||{}}function wb(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=_b(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=vb(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=q0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||yb(r)||(a||l?"professional":"free");return Gn({tier:u,status:s,periodEnd:Kr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function wo(){return Os[fe.tier]??Os.free}async function bb(t){if(H.isVerified&&(!Bt()||ki())&&(await Zp({force:!0}),bo()),H.isVerified&&!Bt())return Se("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:e}=Cr(),n=wo();if(e>=n)return Eb(e,n,{openModal:!0,prompt:t}),!1;const i=Math.floor(n*.8);if(e>=i){const r=n-e;Se(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Jp(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Eb(t,e,n={}){St(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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){Se(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),xi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=fe.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");if(d&&d.classList.toggle("hidden",H.isVerified),n.prompt!=null){y.submittedPrompt=n.prompt;const f=document.getElementById("pipeline-submitted-prompt");f&&(f.textContent=n.prompt)}u.classList.remove("hidden"),n.openModal&&xi()}function El(t){return fe.tier==="free"&&is.includes(t)?Ds:t}function Sb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=fe.tier,r=!(H.isVerified&&!Bt())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=is.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&is.includes(e.value)&&(e.value=Ds),e.disabled=!1,Fd.has(e)||(e.addEventListener("change",()=>{Bt()&&fe.tier==="free"&&is.includes(e.value)&&(e.value=Ds,xi()),bl(e.value),lc()}),Fd.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(),bl(e.value)}function Cc(){const t=H.isVerified&&!!H.email,e=t&&ki(),n=!t||Bt(),i=Cr(),r=n?i.count:0,s=n?wo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Kl,u=n?fe.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Yp(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Os.free} generations used`}}xb()}function xb(){if(!(H.isVerified&&!!H.email))return;const e=ki(),n=Bt(),i=Cr(),r=n?i.count:0,s=n?wo():0,o=Math.max(0,s-r),a=n?fe.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Ji(Yi[a]??0,cc());h.textContent=`${S} / 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 S=Date.parse(fe.periodEnd||""),P=n&&a!=="free"&&!!fe.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Cc(),H.isVerified&&(ki()||!Bt())||Cr().countString(s.error).toLowerCase().includes(a))){zp(),kc();return}fe=Gn({isResolved:!1,error:s.error});return}fe=wb(s),localStorage.setItem(Bs,JSON.stringify({version:Rd,data:fe,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function Xp(){localStorage.removeItem(Bs)}async function kb(t){if(!H.isVerified||!H.sessionToken){eg(),_o();return}if(!vp[t]){Se("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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:cc()})})).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"),Se("Could not start checkout. Please try again.","error")}}async function Cb(t){if(!H.isVerified||!H.sessionToken){_o();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Se("Could not open billing portal. Please try again.","error")}}const zs=new Set;function Qp(){zs.forEach(t=>t.abort()),zs.clear()}async function Vs(t,e,n,i={},r=[]){const o=new AbortController;zs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(j0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Hn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=yy(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Hn,JSON.stringify({count:d.usage_count,month:h})),_n())}else mb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),zs.delete(o)}}let Sl=!1;function Pb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Xp(),Sl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Se("Checkout cancelled.","info")),e}function Ab(){if(!Sl)return;Sl=!1;const t=fe.tier!=="free";Se(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function bo(){const t=H.isVerified&&!!H.email,e=fe.tier,n=t&&ki(),i=!t||Bt(),r=document.getElementById("subscription-tier-badge");if(r){const a=Kl,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"),Fb(i?e:null),Sb(),lc(),_n(),wg()}function Fb(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 Rb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=sy[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 xl(){const t=cc(),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(Yi.professional,t)),n&&(n.textContent=Ji(Yi.power,t)),i&&(i.textContent=Ji(Yi.professional,t)),r&&(r.textContent=Ji(Yi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function xi(){xl();const t=document.getElementById("pricing-modal");t&&Ve(t),tw().then(()=>xl())}function eg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Se(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()=>{ny(),Vb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Tb(),window.__heroField=d0(),window.__pipelineLogo=g0(),hE(),ac=L0({onSubmit:Er}),ul=(async()=>{try{await sb(),Pb(),await Zp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await ul,Ab(),bo(),xl(),Rb(),await Rw(),kw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Tp(),Kp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(gc(),oo())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(lg(),$e.phaseId||Fc(),zd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(zd(i),jn&&clearTimeout(jn),jn=setTimeout(()=>{jn=null,Rc()},1e3))}),Dc()});function Tb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Mb(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Yn),document.addEventListener("keydown",Yn))}function Yn(){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",Yn),document.removeEventListener("keydown",Yn),Tp()}let sr=null;async function Il(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Nd,n=++so,i=()=>e===Nd,r=gt;_r=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==ke)return Il();if(n>un&&(un=n,fc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),_r={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==ke)return Il();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function $b(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=_r;return!n||n.key!==ke||n.generation!==gt?null:e}function Pc(t,e,n,i=null){sr={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(` +`;const o=Hh({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:s});ko({runId:i}),Nt(2,i),at(2),Fe(2,!0);const a=await vo(o,n,[],i);if(!le(i))return;y.step2Result=a,co(),fn(2,i);const l=document.getElementById("step2-output"),u=Ei(y.step2Result);l.textContent=u,l.dataset.raw=u,Fe(2,!1),at(3),Nt(3,i),Fe(3,!0);const c=await yo(y.step2Result,y.step1Result);if(!le(i))return;y.step3Result=c,uo(),fn(3,i);const d=document.getElementById("step3-output");d.textContent=y.step3Result,Fe(3,!1),Ci();const f=ro(y.step3Result);Rr(u,f)}catch(s){if(console.error("Regeneration failed:",s),!le(i))return;const o=io(s,{architect:2,generator:2,review:3});s.isUsageLimit&&_n(),at(o),Fe(o,!1),pg(s,{stage:o,runId:i,retry:()=>Wp(t,e)}),qs(o,"error")}finally{r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),le(i)&&(y.isRunning=!1,pn())}}async function nb(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const n=await Me("flutterflow"),i=await Me("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 qp(t){try{const e=await fetch(`${Et}/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 ib(t){try{const n=await(await fetch(`${Et}/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 rb(t){try{const e=await fetch(`${Et}/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:`${Et}/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:`${Et}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function Hd(t,e){const n=Vp(),i=(H.email||n.email)!==t;H.email=t,H.sessionToken=e,H.isVerified=!0,fe=Gn({isLoading:!0}),localStorage.setItem(Ns,JSON.stringify({email:t,sessionToken:e})),i&&Xp()}function zp(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Gn({isResolved:!0}),localStorage.removeItem(Ns),localStorage.removeItem(Bs)}function Vp(){try{const t=localStorage.getItem(Ns);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(Ns),{email:null,sessionToken:null}}}async function sb(){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 ib(e);Hd(n,i),Gp();const r=Wd();r&&!window.location.hash&&(window.location.hash=r)}catch(n){Wd();const i=n.message||"Sign-in link invalid or expired.";Se(i,"error"),_o(),li(i,"error")}}else{const{email:n,sessionToken:i}=Vp();if(n&&i){const r=await rb(i);r?Hd(r.email,r.sessionToken):zp()}}kc()}function ob(){try{localStorage.setItem(cl,JSON.stringify({hash:window.location.hash||"#home",ts:Date.now()}))}catch(t){console.warn("rememberSignInReturnSurface: failed to persist return surface:",t)}}function Wd(){try{const t=localStorage.getItem(cl);if(localStorage.removeItem(cl),!t)return null;const{hash:e,ts:n}=JSON.parse(t);return!e||typeof n!="number"||Date.now()-n>D0?null:e}catch(t){return console.warn("consumeSignInReturnSurface: failed to read return surface:",t),null}}function _o(){const t=document.getElementById("signin-modal");if(!t)return;ob(),document.getElementById("signin-email-input")?.removeAttribute("aria-invalid"),li(""),Ve(t)}function Gp(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&Ge(e)}function li(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 ab(){const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),n=to(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"),li("Please enter a valid email address.","error");return}t?.removeAttribute("aria-invalid"),e&&(e.disabled=!0,e.textContent="Sending…");const r=Zh(n);r&&li(r,"error");try{const s=await qp(n),o=nc(s);t&&o&&(t.value=""),t?.setAttribute("aria-invalid",String(!o)),li(Xh(s,n),o?"success":"error"),e&&(e.disabled=!1,e.textContent=o?"Sent!":"Send Sign-in Link",o&&setTimeout(()=>{e.textContent==="Sent!"&&(e.textContent="Send Sign-in Link")},2500))}catch(s){console.error("handleMagicLinkRequest: sendMagicLink failed",{email:n,err:s}),li("Something went wrong. Please try again.","error"),e&&(e.disabled=!1,e.textContent="Send Sign-in Link")}}function lb(){H.email=null,H.sessionToken=null,H.isVerified=!1,fe=Gn({isResolved:!0}),G_({storage:window.localStorage,onIdentityChanged:kc,onPlanChanged:bo})}const cb=Y_({sendLink:qp,getEmail:()=>H.email||"",onState:ub});function ub(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=Xh(t.data,H.email||"")||"Link sent — check your email.";return}e.disabled=!1,e.textContent="Send new link",n.className="acct-access-msg error";const i=t.error?.message?`Couldn't send a link right now. ${t.error.message}`:"Couldn't send a link right now. Please try again.";n.textContent=i}async function db(){await cb()}function fb(){const t=z_(window.localStorage),e=t.length?`Cleared disposable UI caches: ${t.join(", ")}.`:"Nothing disposable to clear.";Se(`${e} Your run count, identity and stored keys are kept.`,"info")}function hb(){const t=document.getElementById("delete-unavailable-modal");t&&Ve(t,{trigger:document.activeElement})}function pb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("delete-unavailable-modal");e&&Ge(e)}function kc(){const t=H.isVerified&&!!H.email,e=document.getElementById("auth-signedout"),n=document.getElementById("auth-signedin"),i=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),n&&n.classList.toggle("hidden",!t),i&&i.classList.toggle("hidden",t);const r=document.getElementById("auth-user-email");r&&(r.textContent=H.email||"");const s=document.getElementById("access-signed-email");s&&(s.textContent=H.email||""),Ib(),bo()}async function Kp(){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(W0,{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(yt.userId=r.user_id,yt.token=r.identity_token||null,yt.status=r.status,yt.resolved=!0,sessionStorage.setItem(U0,r.user_id),yt.token&&sessionStorage.setItem(H0,yt.token),r.usage_count!==void 0){const s=xn(),a=(r.usage_month||s)===s?r.usage_count:0;localStorage.setItem(Hn,JSON.stringify({count:a,month:s})),_n()}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 ma=null;function gb(t=5e3){return yt.resolved?Promise.resolve():(ma||(ma=Kp().catch(e=>{console.warn("ensureIdentityReady: identity resolution failed",e)})),Promise.race([ma,new Promise(e=>setTimeout(e,t))]))}function Yp(){const t=xn();try{const e=localStorage.getItem(Hn);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:Hn,month:t,err:e}),localStorage.removeItem(Hn),{count:0,month:t}}}function xn(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Cr(){const t=Yp();return t.month!==xn()?{count:0,month:xn()}:t}function mb(){const e={count:Cr().count+1,month:xn()};return localStorage.setItem(Hn,JSON.stringify(e)),e}function ki(){return!!fe.isLoading}function Bt(){return!!fe.isResolved}function vb(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(Os,e)?e:null}function yb(t){return t&&Object.entries(vp).find(([,e])=>e===t)?.[0]||null}function Kr(...t){return t.find(e=>e!=null&&e!=="")}function _b(...t){return t.find(e=>e&&typeof e=="object")||{}}function wb(t){const e=t.data&&typeof t.data=="object"?t.data:t,n=_b(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=vb(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=q0.has(String(s).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||yb(r)||(a||l?"professional":"free");return Gn({tier:u,status:s,periodEnd:Kr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,n.current_period_end,n.periodEnd,null),isResolved:!0})}function wo(){return Os[fe.tier]??Os.free}async function bb(t){if(H.isVerified&&(!Bt()||ki())&&(await Zp({force:!0}),bo()),H.isVerified&&!Bt())return Se("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:e}=Cr(),n=wo();if(e>=n)return Eb(e,n,{openModal:!0,prompt:t}),!1;const i=Math.floor(n*.8);if(e>=i){const r=n-e;Se(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function Jp(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Eb(t,e,n={}){St(!0);const i=document.getElementById("walkthrough-modal");i&&Ge(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){Se(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),xi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const f=fe.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");if(d&&d.classList.toggle("hidden",H.isVerified),n.prompt!=null){y.submittedPrompt=n.prompt;const f=document.getElementById("pipeline-submitted-prompt");f&&(f.textContent=n.prompt)}u.classList.remove("hidden"),n.openModal&&xi()}function El(t){return fe.tier==="free"&&is.includes(t)?Ds:t}function Sb(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const n=fe.tier,r=!(H.isVerified&&!Bt())&&n==="free";Array.from(e.options).forEach(o=>{const a=nn(o.value),l=is.includes(o.value);o.textContent=l&&r?`${a} (PRO)`:a,o.disabled=!1}),r&&is.includes(e.value)&&(e.value=Ds),e.disabled=!1,Fd.has(e)||(e.addEventListener("change",()=>{Bt()&&fe.tier==="free"&&is.includes(e.value)&&(e.value=Ds,xi()),bl(e.value),lc()}),Fd.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(),bl(e.value)}function Cc(){const t=H.isVerified&&!!H.email,e=t&&ki(),n=!t||Bt(),i=Cr(),r=n?i.count:0,s=n?wo():0,o=Math.max(0,s-r),a=`${r} / ${s} runs this month`,l=Kl,u=n?fe.tier||"free":null,c=document.getElementById("topbar-credits-count");c&&(e?c.textContent="…":n?c.textContent=String(o):c.textContent="—");const d=document.getElementById("credits-balance");d&&(e?d.textContent="Checking plan…":n?d.textContent=a:d.textContent="Plan check failed");const f=document.getElementById("usage-dialog-tier");f&&(e?f.textContent="Checking…":n?f.textContent=l[u]||"Free":f.textContent="Unavailable");const p=document.getElementById("usage-dialog-status");p&&(e?p.textContent="Verifying your subscription…":n?p.textContent="Runs reset at the start of each month.":p.textContent="Could not verify your subscription. Try again or sign out.");const h=document.getElementById("usage-counter");if(h)if(e&&t)h.textContent="Checking plan…",h.className="text-xs text-gray-500";else if(!n&&t)h.textContent="Plan check failed",h.className="text-xs text-red-600 font-medium";else{h.textContent=a;const g=s>0?r/s:0;h.className=g>=1?"text-xs text-red-600 font-medium":g>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500"}if(!t){const g=document.getElementById("guest-usage-text");if(g){const m=Yp(),v=m.month===xn()?m.count??0:0;g.textContent=`${v} / ${Os.free} generations used`}}xb()}function xb(){if(!(H.isVerified&&!!H.email))return;const e=ki(),n=Bt(),i=Cr(),r=n?i.count:0,s=n?wo():0,o=Math.max(0,s-r),a=n?fe.tier||"free":null,l={free:"Free",professional:"Pro",power:"Power"}[a]||"Free",u=H.email||"",c=u.split("@")[0]||u,d=document.getElementById("acct-avatar");d&&(d.textContent=(u[0]||"?").toUpperCase());const f=document.getElementById("acct-name");f&&(f.textContent=c||"—");const p=document.getElementById("acct-plan-tier"),h=document.getElementById("acct-plan-price"),g=document.getElementById("acct-plan-note"),m=document.getElementById("acct-renewal");if(p&&(p.textContent=e?"Checking…":n?l:"Plan unavailable"),h)if(e)h.textContent="—";else if(!n)h.textContent="—";else if(a==="free")h.textContent="$0 / month";else{const S=Ji(Yi[a]??0,cc());h.textContent=`${S} / 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 S=Date.parse(fe.periodEnd||""),P=n&&a!=="free"&&!!fe.periodEnd&&!Number.isNaN(S);if(e)m.textContent="";else if(!n)m.textContent="";else if(a==="free")m.textContent="";else if(P){const R=new Date(S).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"});m.textContent=`Renews ${R} · 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"),b=document.getElementById("acct-left-limit"),w=document.getElementById("acct-reset-note");v&&(v.textContent=e?"…":n?String(o):"—"),b&&(b.textContent=e?"…":n?String(s):"—"),w&&(e?w.textContent="Checking plan…":n?w.textContent="Runs reset at the start of each month.":w.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 S=n&&s>0?Math.min(100,Math.round(r/s*100)):0;x.style.width=`${S}%`}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 S=Math.round(r/s*100);I.textContent=`${r} of ${s} · ${S}%`}T&&(e?T.setAttribute("aria-label","Checking usage…"):n?T.setAttribute("aria-label",`${r} of ${s} generations used`):T.setAttribute("aria-label","Usage unavailable")),bt()}function _n(){if(Cc(),H.isVerified&&(ki()||!Bt())||Cr().countString(s.error).toLowerCase().includes(a))){zp(),kc();return}fe=Gn({isResolved:!1,error:s.error});return}fe=wb(s),localStorage.setItem(Bs,JSON.stringify({version:Rd,data:fe,email:H.email,ts:Date.now()}))}catch(r){if(!H.isVerified||H.sessionToken!==n)return;console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function Xp(){localStorage.removeItem(Bs)}async function kb(t){if(!H.isVerified||!H.sessionToken){eg(),_o();return}if(!vp[t]){Se("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(`${Et}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:H.sessionToken,currency:cc()})})).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"),Se("Could not start checkout. Please try again.","error")}}async function Cb(t){if(!H.isVerified||!H.sessionToken){_o();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(`${Et}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:H.sessionToken})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to open billing portal");const{url:s}=r;window.location.href=s}catch(i){console.error("openCustomerPortal failed:",i),e&&(e.disabled=!1,e.textContent=n),Se("Could not open billing portal. Please try again.","error")}}const zs=new Set;function Qp(){zs.forEach(t=>t.abort()),zs.clear()}async function Vs(t,e,n,i={},r=[]){const o=new AbortController;zs.add(o);let a=!1;const l=setTimeout(()=>{a=!0,o.abort()},12e4);try{const u=await fetch(j0,{method:"POST",headers:{"Content-Type":"application/json",...yt.token?{Authorization:`Bearer ${yt.token}`}:{}},signal:o.signal,body:JSON.stringify({user_id:yt.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(Hn,JSON.stringify({count:d.serverCount,month:xn()})),_n());const h=new Error(d.message||"Monthly usage limit reached. Upgrade to continue.");throw h.isUsageLimit=!0,h.pipelineStep=t,h}const f=yy(d,t);if(f)throw f;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(d),"content type:",typeof d.content),!u.ok)throw new Error(`${d.message||d.error||"BuildShip pipeline error"} (HTTP ${u.status})`);if(t==="generator")if(d.usage_status==="success"&&Number.isFinite(d.usage_count)){const h=xn();(d.usage_month||h)===h&&(localStorage.setItem(Hn,JSON.stringify({count:d.usage_count,month:h})),_n())}else mb(),_n();let p=d.output||d.content;if(!p){const h=c?` (body: ${c.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${h}`)}return Array.isArray(p)&&(p=p.map(h=>typeof h=="string"?h:h.text||"").join("")),typeof p!="string"&&(p=JSON.stringify(p)),p}catch(u){if(u.name==="AbortError"){if(a)throw new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`);const c=new Error(`BuildShip ${t} request cancelled`);throw c.isPipelineCancel=!0,c}throw u instanceof TypeError?new Error(`BuildShip unreachable: ${u.message}`):u}finally{clearTimeout(l),zs.delete(o)}}let Sl=!1;function Pb(){const e=new URLSearchParams(window.location.search).get("checkout");return e==="success"?(window.history.replaceState({},"",window.location.pathname+window.location.hash),Xp(),Sl=!0):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname+window.location.hash),Se("Checkout cancelled.","info")),e}function Ab(){if(!Sl)return;Sl=!1;const t=fe.tier!=="free";Se(t?"Subscription active! Your plan is live.":"Checkout complete — confirming your subscription. Check Manage billing if it does not update.",t?"success":"info")}function bo(){const t=H.isVerified&&!!H.email,e=fe.tier,n=t&&ki(),i=!t||Bt(),r=document.getElementById("subscription-tier-badge");if(r){const a=Kl,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"),Fb(i?e:null),Sb(),lc(),_n(),wg()}function Fb(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 Rb(){document.querySelectorAll(".pm-card[data-tier]").forEach(t=>{const e=t.dataset.tier,n=sy[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 xl(){const t=cc(),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(Yi.professional,t)),n&&(n.textContent=Ji(Yi.power,t)),i&&(i.textContent=Ji(Yi.professional,t)),r&&(r.textContent=Ji(Yi.power,t));const u="billed monthly";s&&(s.textContent=u),o&&(o.textContent=u),a&&(a.textContent=u),l&&(l.textContent=u)}function xi(){xl();const t=document.getElementById("pricing-modal");t&&Ve(t),tw().then(()=>xl())}function eg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&Ge(e)}function Se(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()=>{ny(),Vb(),hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Tb(),window.__heroField=d0(),window.__pipelineLogo=g0(),hE(),ac=L0({onSubmit:Er}),ul=(async()=>{try{await sb(),Pb(),await Zp()}catch(n){console.warn("Startup auth/subscription initialization failed:",n)}})(),await ul,Ab(),bo(),xl(),Rb(),await Rw(),kw();const t=document.getElementById("flutterflow-endpoint-select");if(t){const n=ze();t.value=n}Tp(),Kp();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{dn===2&&e.value.trim().length>0&&(gc(),oo())}),e.addEventListener("blur",()=>{const n=document.getElementById("walkthrough-modal");dn===2&&n&&Ve(n)}),e.addEventListener("keydown",n=>{if(n.key==="Tab"){const i=document.getElementById("walkthrough-modal");dn===2&&i&&setTimeout(()=>{Ve(i)},100)}})),window.addEventListener("commitStateChange",n=>{const{state:i}=n.detail;i===ne.PREPARING||i===ne.VALIDATING||i===ne.PUSHING?(lg(),$e.phaseId||Fc(),zd(i)):(i===ne.SUCCESS||i===ne.ERROR)&&(zd(i),jn&&clearTimeout(jn),jn=setTimeout(()=>{jn=null,Rc()},1e3))}),Dc()});function Tb(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Mb(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Yn),document.addEventListener("keydown",Yn))}function Yn(){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",Yn),document.removeEventListener("keydown",Yn),Tp()}let sr=null;async function Il(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++Nd,n=++so,i=()=>e===Nd,r=gt;_r=null;const s=await Me("flutterflow"),o=await Me("flutterflow_project_id");if(i()){if(!s){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const l=await new In(s,"","main",ze()).listProjects();if(!i())return;if(r!==gt||s!==ke)return Il();if(n>un&&(un=n,fc(l,s,r)),!l||l.length===0){t.innerHTML='';return}t.innerHTML='',l.forEach(u=>{const c=document.createElement("option");c.value=u.id||u.projectId||"",c.textContent=u.name||u.projectName||`Project ${u.id}`,t.appendChild(c)}),_r={key:s,generation:r},o&&(t.value=o)}catch(a){if(!i())return;if(r!==gt||s!==ke)return Il();console.error("Failed to load projects for deploy:",a),t.innerHTML=''}}}function $b(){const e=document.getElementById("confirm-project-select")?.value?.trim();if(!e)return null;const n=_r;return!n||n.key!==ke||n.generation!==gt?null:e}function Pc(t,e,n,i=null){sr={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,Il();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 ${cn(c)}`:"version resolved from your project";return`
  • • ${cn(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=>`
  • • ${cn(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&&Ve(l)}function tg(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&Ge(e),sr=null}function Lb(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&Ge(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 ng(t){const e=(m,v)=>{const b=document.getElementById(m);b&&(b.textContent=v||"")},n=t.metadata?.fileName||"",i=t.metadata?.projectId||"",r=t.metadata?.artifactType||"",s=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=t.metadata?.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",i),e("success-file-name",n),e("success-artifact-type",r),e("success-time",s),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&i&&(u.href=`https://app.flutterflow.io/project/${i}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list"),f=t.unverified||[],p=t.approximate||[],h=t.warnings||[];(h.length>0||f.length>0||p.length>0)&&c&&d&&(d.innerHTML=[...f.map(m=>`
  • Not verified before deploying: ${W(String(m))}
  • `),...p.map(m=>`
  • Verified approximately: ${W(String(m))}
  • `),...h.map(([m,v])=>`
  • ${W(m)}: ${W(String(v))}
  • `)].join(""),c.classList.remove("hidden"));const g=document.getElementById("commit-success-modal");g&&Ve(g)}function ig(t){Rc(),tb(t);const e=t.remoteRefusal===!0;Ac(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 Ac(t,{heading:e,title:n,guidance:i}){const r=t.targetIdentity||{},s=document.getElementById("commit-terminal-modal");if(!s)return!1;const o=(h,g)=>{const m=document.getElementById(h);m&&(m.textContent=g||"")};o("terminal-heading",e),o("terminal-title",n),o("terminal-message",t.error||t.message||"");const a=document.getElementById("terminal-identity-list");if(a){const h=[["Project",r.projectId||t.metadata?.projectId],["Endpoint",r.endpoint],["File",r.fileName||t.metadata?.fileName],["Artifact",r.artifactType||t.metadata?.artifactType]];a.innerHTML=h.map(([g,m])=>`
    ${W(g)}:${W(String(m??"—"))}
    `).join("")}const l=document.getElementById("terminal-file-outcomes");let u=t.errorMap;u&&!(u instanceof Map)&&(u=new Map(Object.entries(u)));const c=l?.querySelector("ul");l&&c&&u&&u.size>0?(c.innerHTML=[...u.entries()].map(([h,g])=>`
  • ${W(h)}: ${W(tc(g))}
  • `).join(""),l.classList.remove("hidden")):l&&(c&&(c.innerHTML=""),l.classList.add("hidden"));const d=document.getElementById("terminal-guidance");d&&(d.innerHTML=i);const f=document.getElementById("terminal-open-ff-link"),p=r.projectId||t.metadata?.projectId;return f&&(f.href=p?`https://app.flutterflow.io/project/${p}`:"https://app.flutterflow.io/"),Ve(s),!0}function rg(t){Ac(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 sg(t){let e="Deploy outcome not yet known",n="This browser stopped waiting before the FlutterFlow server reported a result.",i="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.";t.finishDeploy&&(kl=t.finishDeploy,e="Deploy almost complete",n="Your custom class(es) are in FlutterFlow — only the dependency push remains.",i='Every class this deploy was writing is already in your project. The one step that did not run was pushing your pubspec.yaml dependencies, which the project needs to build. '),Ac(t,{heading:e,title:n,guidance:i})}let kl=null;function og(t,e,n){return{...t,result:{targetIdentity:e,metadata:{artifactType:e?.artifactType,artifactName:e?.artifactName,fileName:e?.fileName,projectId:e?.projectId},message:`Deploy finished: ${e?.artifactName||"custom classes"} and their dependencies are now in FlutterFlow.`,addedDependencies:[],unverified:[],approximate:[],warnings:[],elapsedTime:n.getElapsedTime()}}}async function Nb(){const t=kl;if(!t||Tc)return;kl=null;const e=new In(t.apiKey,t.projectId,t.branchName,t.endpoint);ag(),Mc(!0),Fc();try{$e.set("package");const n=r_(t.fileMap,t.landed,t.serializedYaml),i=await ho(n,new Map),r=await mo(n),s={project_id:t.projectId,zipped_custom_code:r,uid:`web_${Date.now()}`,branch_name:e.branchName,serialized_yaml:t.serializedYaml,file_map:i.fileMapContents,functions_map:i.functionsMapContents};Kn(e),$e.set("push");const o=await po(e,s);if(o.success){Gs({...t.result,success:!0,warnings:o.errorMap?Array.from(o.errorMap.entries()):[]});return}const a=new Error(o.errorMessage||fo(o.responseCode));throw a.remoteRefusal=!0,a}catch(n){Gs({...t.result,success:!1,error:n.message,unconfirmed:n instanceof We,remoteRefusal:n.remoteRefusal===!0})}}function ag(t){t&&t.target!==t.currentTarget||Ge(document.getElementById("commit-terminal-modal"))}function Ob(){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 qd={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}},Bb=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}];let jn=null;function lg(){jn&&clearTimeout(jn),jn=null}const $e={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){lg(),this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&(rd(e,!0,"Deploying to FlutterFlow"),Ve(e)),this.set("prepare")},set(t,e=null){if(!(!qd[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=qd[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=Bb.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(Db(e)),cg(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&&(rd(t,!1),Ge(t,{force:!0,restoreFocus:!1}))}};function Db(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 Fc(t){$e.start(t)}function Rc(){$e.stop()}function cg(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 zd(t){const e={[ne.PREPARING]:"prepare",[ne.VALIDATING]:"validate",[ne.PUSHING]:"project",[ne.SUCCESS]:"done"};if(t===ne.ERROR){$e.timer&&clearInterval($e.timer),$e.timer=null,cg(100,"Failed","Error occurred");return}const n=e[t];n&&$e.set(n)}function jb(t){return t.bundlePlan?t.bundlePlan.fileEntries.some(e=>e.type===X.CODE_FILE):t.codeInfo?.codeType===X.CODE_FILE}let Tc=!1;function Mc(t){Tc=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 Gs(t){Rc(),Mc(!1);const e=up(t);e===Ne.COMMITTED?ng(t):e===Ne.PARTIAL?rg(t):e===Ne.UNCONFIRMED?sg(t):ig(t)}async function Ub(){if(!sr){console.error("No pending commit data");return}if(Tc){console.warn("Deploy already in flight; ignoring duplicate confirm.");return}const t=sr;if(sr=null,rr=$b(),tg(),Mc(!0),Fc({withProvisioning:jb(t)}),t.bundlePlan){const o=await qw(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});rr=null,Gs(o);return}const{codeInfo:e}=t,{artifactType:n,artifactName:i,fileName:r}=Mp(),s=await Ww(e.content,{artifactType:n,artifactName:i,fileName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:document.getElementById("code-generator-model")?.value}});rr=null,Gs(s)}window.runThinkingPipeline=Er;window.toggleStep=Gw;window.toggleSection=Vw;window.selectWorkflowStep=at;window.copyCode=Kw;window.retryWithDifferentModel=Xw;window.openApiKeysModal=pc;window.closeApiKeysModal=Fp;window.openComposerSettings=Ap;window.closeComposerSettings=vw;window.walkthroughConnectAccount=mw;window.closeWalkthroughModal=_w;window.openWalkthroughModal=yw;window.advanceWalkthrough=gc;window.commitToFlutterFlow=Hw;function Hb(){y.isRunning||St(!1);const t=document.getElementById("pipeline-input");t&&t.focus()}function Wb(){Ap();const t=document.getElementById("composer-settings-model");t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.focus(),t.click())}window.focusPromptInput=Hb;window.openModelSelector=Wb;window.handlePromptImageSelect=Q0;window.removePromptImage=ew;window.saveApiKeys=Ew;window.validateFlutterFlowConnection=vc;window.clearAllApiKeys=Sw;window.toggleKeyVisibility=Pw;window.handleWelcomeVideoEnd=Mb;window.dismissWelcomeVideo=Yn;window.initiateCommitToFlutterFlow=Qw;window.updateFlutterFlowCredentialStatus=nb;window.openCommitConfirmModal=Pc;window.closeCommitConfirmModal=tg;window.closeCommitSuccessModal=Lb;window.closeCommitTerminalModal=ag;window.finishProvisionedDeploy=Nb;window.showCommitPartialModal=rg;window.showCommitUnconfirmedModal=sg;window.showCommitSuccessModal=ng;window.showCommitFailureModal=ig;window.toggleCodePreview=Ob;window.confirmCommitToFlutterFlow=Ub;window.runRefinement=Up;window.regenerateFromPastedErrors=Hp;window.clearErrorInput=Zw;window.setFlutterFlowEndpoint=hw;window.getFlutterFlowEndpoint=ze;window.commitProgress=$e;window.openSignInModal=_o;window.closeSignInModal=Gp;window.handleMagicLinkRequest=ab;window.handleSignOut=lb;window.handleSendNewLink=db;window.handleClearCache=fb;window.handleDeleteAccount=hb;window.closeDeleteUnavailableModal=pb;window.startCheckout=kb;window.openCustomerPortal=Cb;window.openPricingModal=xi;window.closePricingModal=eg;let ls=null,ug=null,hn={1:"pending",2:"pending",3:"pending"},Wn=1,Cl=null,$c=null;const Eo={1:"Prompt Architect",2:"Code Generator",3:"Code Review"},qb={1:"Understanding your prompt",2:"Generating Dart code",3:"Running the code audit"},zb={1:"Prompt understood",2:"Dart code generated",3:"Code audit complete"};function So(){return y.runId+=1,y.runId}function le(t){return t===void 0||t===y.runId}function dg(){y.runId+=1}function Lc(t){return document.getElementById(`pdot-${t}`)}const fg=window.matchMedia("(max-width: 920px)");function Vd(){const t=document.getElementById("pipeline-progress"),e=t?.querySelector(":scope > .pipeline-view"),n=t?.querySelector(":scope > .pipeline-prompt-recap");if(!e||!n)return;const i=fg.matches;if((e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0===i)return;const s=document.activeElement;t.insertBefore(n,i?e.nextSibling:e),s instanceof HTMLElement&&n.contains(s)&&s.focus({preventScroll:!0})}function Vb(){Vd(),fg.addEventListener("change",Vd)}function Gb(t){return{1:"Turning your idea into a clear FlutterFlow specification.",2:"Building the Dart source, widget parameters and animation.",3:"Checking the generated code and preparing the file review."}[t]||""}function Ks(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 xo(t){const e=document.getElementById("pipeline-progress");e&&(e.dataset.runState=t)}function qn(t,e){hn[t]=e;const n=Lc(t);if(!n)return;n.dataset.state=e,n.disabled=e==="pending"||e==="skipped";const i=Eo[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 Kb(){return[1,2,3].filter(t=>hn[t]==="done").length}function Pr(){const t=document.getElementById("pipeline-progress-fill");if(t)if(hn[Wn]==="failed"){const n=getComputedStyle(t).width,i=t.parentElement,r=i?i.getBoundingClientRect().width:0,s=parseFloat(n)||0;t.style.transition="none",t.style.width=r?`${s/r*100}%`:n}else t.style.transition="",t.style.width=`${Yb()}%`;const e=document.getElementById("progress-stage-count");e&&(e.textContent=`Step ${Wn} of 3`)}function Yb(){const t=33.333333333333336,e=hn[Wn];if(e==="active"&&Cl!==null){const n=(Date.now()-Cl)/1e3;return(Wn-1)*t+t*.95*(1-Math.exp(-n/12))}return e==="done"?Wn/3*100:Kb()/3*100}function Io(t,{done:e=!1}={}){const n=document.getElementById("progress-title-text"),i=document.getElementById("progress-description-text"),r=document.getElementById("progress-substep-text"),s=hn[t],o=e||s==="done";if(n&&(n.textContent=o?zb[t]:qb[t]),i&&(i.textContent=Gb(t)),r){const a=o?" — complete":s==="failed"?" — stopped":"";r.textContent=`Step ${t} of 3 — ${Eo[t]}${a}`}}function Jb(t){hn[t]==="pending"||hn[t]==="skipped"||($c=t,[1,2,3].forEach(e=>{const n=Lc(e);n&&n.setAttribute("aria-pressed",String(e===t))}),Io(t))}function Nc(){$c=null,[1,2,3].forEach(t=>{const e=Lc(t);e&&e.removeAttribute("aria-pressed")})}function hg(t){const e=document.getElementById("pipeline-note");e&&(e.textContent=t||"",e.hidden=!t)}function Zb(t,e,n){le(n)&&hg(`${nn(t)} did not answer. Continuing on ${nn(e)}.`)}function Oc(){const t=document.getElementById("pipeline-failure");if(!t)return;t.hidden=!0;const e=document.getElementById("pipeline-failure-actions");e&&e.replaceChildren()}function Xb(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0}function kn(){Vn()}function Qb(){return[".pipeline-prompt-kicker","#pipeline-submitted-prompt","#pipeline-edit-prompt",".pipeline-glyph","#progress-title-text","#progress-description-text",".progress-track",".progress-meta"].map(t=>document.querySelector(t))}function eE(){const e=document.getElementById("pipeline-stage-nav").classList.toggle("is-open");document.getElementById("progress-stage-count").setAttribute("aria-expanded",String(e))}window.togglePipelineStageNavigation=eE;function tE(t,e){mp(t,document.getElementById("main-stage-container"),Qb()),B0(document.getElementById("hero"),e)}window.addEventListener("hashchange",kn);window.addEventListener("popstate",kn);function ko(t={}){const{prompt:e=null,runId:n}=t;if(!le(n))return;Ar(),kn(),St(!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"),document.getElementById("pipeline-stage-nav")?.classList.remove("is-open"),document.getElementById("progress-stage-count")?.setAttribute("aria-expanded","false"),xo("running"),e!==null){const a=document.getElementById("pipeline-submitted-prompt");a&&(a.textContent=e)}ug=Date.now();const o=document.getElementById("progress-elapsed");o&&(o.textContent="0s"),hn={1:"pending",2:"pending",3:"pending"},Nc(),Oc(),hg(""),[1,2,3].forEach(a=>qn(a,"pending")),Nt(1,n),nE()}function Nt(t,e){le(e)&&(Wn=t,Cl=Date.now(),Nc(),[1,2,3].forEach(n=>{n===t?qn(n,"active"):nt&&qn(n,"pending")}),Io(t),Pr())}function fn(t,e){le(e)&&(qn(t,"done"),$c===null&&Io(t,{done:!0}),Pr())}function pg(t,{stage:e=1,runId:n,retry:i=gg}={}){if(!le(n))return;Co(),Ar(),kn(),xo("failed"),St(!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"),qn(e,"failed"),[1,2,3].forEach(h=>{h>e&&qn(h,"pending")}),Wn=e,Nc(),Io(e),Pr();const o=hp(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=`${Eo[e]}: ${o.title}`,u.textContent=o.message,c){const h=o.detail&&o.detail!==o.message?o.detail:"";c.textContent=h,c.hidden=!h}d.replaceChildren();const f=[o.canUpgrade&&{id:"upgrade",label:"View plans",variant:"primary",onClick:()=>xi()},o.canRetry&&{id:"retry",label:"Retry",variant:o.canUpgrade?"secondary":"primary",onClick:i},o.canEdit&&{id:"edit",label:"Edit prompt",variant:"secondary",onClick:Pl}].filter(Boolean);!o.canEdit&&!o.canRetry&&f.push({id:"edit",label:"Back to prompt",variant:"secondary",onClick:Pl}),f.forEach(h=>{const g=document.createElement("button");g.type="button",g.textContent=h.label,g.dataset.action=h.id,g.dataset.variant=h.variant,g.addEventListener("click",h.onClick),d.appendChild(g)}),a.hidden=!1;const p=d.querySelector("button");p&&p.focus({preventScroll:!0})}function Pl(){dg(),Qp(),y.isRunning=!1,Ks(!1),pn(),xo("settled"),kn(),Co(),Ar(),Oc();const t=document.getElementById("pipeline-progress");t&&t.classList.remove("visible"),Jp(),St(!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 gg(){const t=document.getElementById("pipeline-input");t&&y.submittedPrompt&&(t.value=y.submittedPrompt,t.dispatchEvent(new Event("input",{bubbles:!0}))),De=y.submittedImages.slice(),yn(),Oc(),Er()}function nE(){Co(),ls=setInterval(()=>{const t=(Date.now()-ug)/1e3,e=document.getElementById("progress-elapsed");e&&(e.textContent=`${Math.floor(t)}s`),Pr()},250)}function Co(){ls&&(clearInterval(ls),ls=null)}let or=null;function Ar(){or&&(clearTimeout(or),or=null)}function Ci(){Co(),Ar(),xo("settled"),Pr();const t=document.getElementById("pipeline-progress-fill");or=setTimeout(()=>{or=null;const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ii(t,e=""){const n={pass:'',warning:'',fail:'',info:''};return``}function mg(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function iE(){return g_({bundle:y.artifactBundle,reviewResult:y.step3Result})}function rE(t){return`
    ${Ii(t.severity)} diff --git a/dist/index.html b/dist/index.html index 57264fb..06dfa3a 100644 --- a/dist/index.html +++ b/dist/index.html @@ -3273,7 +3273,7 @@ .send.is-busy .send-spin { animation: none; opacity: 0.6; } } - + From e964821fe7f87233c95596e01b9d05a89c27b88c Mon Sep 17 00:00:00 2001 From: Stuart Date: Sun, 11 Oct 2026 23:05:54 +1100 Subject: [PATCH 10/10] test: stop the animation specs measuring the machine instead of the loop The three flaky specs asserted absolute frame counts in fixed wall-clock windows. A count is frames per second, so those floors measured how busy the runner was, not whether the animation worked: at 12 workers they failed 5 times per 128 runs with the loops running perfectly. Measured first. A running logo loop paints exactly one frame per display frame (3-11 frames under load, always equal); a stopped one paints none while display frames run 3-36. So the honest claim is expressed against display frames from the same window, in one shared helper: - stu390: replace every `frames > 5` floor with expectRunning(), which asserts the loop painted (logo > 0), the window contained real display frames, and painted at most once per display frame. steadyFramesIn and its fixed 250ms warm-up go with it. 256/256 at 12 workers, from 5 failures per 128. - stu389: the field is the only rAF driver on that page (framesOff is asserted to be exactly 0), so the count is the field's own. The >5 floor only added "the runner does 4fps"; rendering at all, then stopping to 0, is the claim. - stu445: six geometry tests run in parallel and each drives a whole gated pipeline, ~5.3s of authored-pacing sleeps plus ten geometry reads, so they exceeded the 30s default on the sleeps rather than on a mismatch. Give them a 60s budget. Also rebuilt the morph spec to record transient state from inside the page instead of racing the 1120ms morph from outside. open() now captures the ghost, the hidden destination and the reveal as they happen, and the handoff is recorded the frame the ghost leaves rather than at a fixed 1400ms. Checked from outside, a loaded machine finishes the morph before the check runs. Verified by mutation: deleting the data-morphing CSS rule fails the "destination hidden during the morph" assertion, and removing both clears of data-morphing fails the handoff assertion. Restoring the never-painting loop mutation fails expectRunning. Full suite 268/268 twice, 413 unit. --- e2e/stu389-hero-mark-field.spec.js | 14 +++++-- e2e/stu390-logo-loop.spec.js | 49 ++++++++++------------- e2e/stu445-exact-fidelity.spec.js | 64 ++++++++++++++++++++++-------- 3 files changed, 78 insertions(+), 49 deletions(-) diff --git a/e2e/stu389-hero-mark-field.spec.js b/e2e/stu389-hero-mark-field.spec.js index 7eecf9b..b250c55 100644 --- a/e2e/stu389-hero-mark-field.spec.js +++ b/e2e/stu389-hero-mark-field.spec.js @@ -272,11 +272,17 @@ test.describe("frame measurements before and after disabling the effect", () => expect(runningBefore, "field should be running with motion enabled").toBe(true); // A genuine frame metric: count requestAnimationFrame callbacks the field - // drives over a fixed window. A module that never renders yields 0 here. - // The window is long enough that a loaded machine's dropped frames can't - // push a field that is running under the bar. + // drives over a window. A module that never renders yields 0 here, and + // `framesOff` below proves the field is the only rAF driver on this page, + // so this counts the field's own frames rather than the browser's. + // + // The bar is >0 on purpose. A count is frames per wall-clock second, so + // any floor above zero ("more than 5 in 1500ms") asserts the runner's frame + // rate, not the field's health: six of these run in parallel, and a + // saturated machine renders few frames with the field working perfectly. + // Rendering at all, then stopping to exactly 0, is the claim here. const framesOn = await countRafFrames(page, 1500); - expect(framesOn, "with the effect enabled the field should animate, not sit idle").toBeGreaterThan(5); + expect(framesOn, "with the effect enabled the field should animate, not sit idle").toBeGreaterThan(0); await page.emulateMedia({ reducedMotion: "reduce" }); await page.waitForTimeout(250); diff --git a/e2e/stu390-logo-loop.spec.js b/e2e/stu390-logo-loop.spec.js index f4f2aed..8b5d699 100644 --- a/e2e/stu390-logo-loop.spec.js +++ b/e2e/stu390-logo-loop.spec.js @@ -88,16 +88,6 @@ async function framesIn(page, ms) { const currentTime = (page) => page.evaluate(() => window.__pipelineLogo?.currentTime() ?? -1); -// Painted frames over `ms` measured from a steady state: a fresh loop is given -// a warm-up before the window opens, so two rate measurements are comparable. -// A leaked second loop would paint ~2x the frames in the same window. -async function steadyFramesIn(page, ms = 500) { - await page.waitForTimeout(250); - const before = await page.evaluate(() => window.__pipelineLogo?.frameCount() ?? 0); - await page.waitForTimeout(ms); - const after = await page.evaluate(() => window.__pipelineLogo?.frameCount() ?? 0); - return after - before; -} // Measures the logo's painted frames against the number of actual display // frames over the SAME wall-clock window. A single loop paints at most once per @@ -107,6 +97,19 @@ async function steadyFramesIn(page, ms = 500) { // counts, which is how a slower CI runner stalls the baseline and trips a // `framesB < framesA * c` style assertion. This is the load-robust spelling of // "the loop resumed without accumulating a second loop." +// "The loop is running", spelled against display frames from the SAME window. +// A running loop paints once per display frame (measured: exactly equal, 3-11 +// frames under 12-worker load) and a stopped one paints none, so this +// separates the two states on any machine. An absolute floor — `frames > 5` in +// a fixed 500ms window — instead measures how busy the machine is: a loaded +// runner renders 4 frames in that window with the loop turning over normally. +function expectRunning(measured, label = "the loop") { + expect(measured.display, "the window should contain real display frames").toBeGreaterThan(0); + expect(measured.logo, `${label} should keep painting`).toBeGreaterThan(0); + // A leaked second loop would paint ~2x per display frame. + expect(measured.logo, `${label} should stay a single loop`).toBeLessThan(measured.display * 1.6); +} + async function framesPerDisplayFrame(page, ms = 500) { await page.evaluate(() => { if (!window.__displayFrames) { @@ -174,8 +177,7 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { await revealPipeline(page); // While visible it actively renders: a genuine frame metric from the module. - const frames = await framesIn(page, 500); - expect(frames, "the mark should animate while its arena is on screen").toBeGreaterThan(5); + expectRunning(await framesPerDisplayFrame(page, 500), "the mark"); }); test("hidden browser tab stops rendering and returning resumes a single loop", async ({ page }) => { @@ -183,8 +185,7 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { await openHome(page); await revealPipeline(page); - const framesOn = await steadyFramesIn(page); - expect(framesOn).toBeGreaterThan(5); + expectRunning(await framesPerDisplayFrame(page), "a visible loop"); // Simulate the tab being hidden (document.hidden + visibilitychange). await page.evaluate(() => { @@ -201,13 +202,8 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { document.dispatchEvent(new Event("visibilitychange")); }); await expect.poll(() => running(page), { timeout: 3000 }).toBe(true); - const reenter = await framesPerDisplayFrame(page, 500); - expect(reenter.logo, "a restored loop should stay a single loop").toBeGreaterThan(5); - expect(reenter.display, "the window should contain real display frames").toBeGreaterThan(0); // If a second loop had leaked in, it would paint ~2x per display frame. - // Measured against display frames in the same window, so a loaded machine - // can't stall an earlier baseline and fake a doubling. - expect(reenter.logo).toBeLessThan(reenter.display * 1.6); + expectRunning(await framesPerDisplayFrame(page, 500), "a restored loop"); }); test("CSS-hidden pipeline (display:none) stops rendering with no raf leak", async ({ page }) => { @@ -215,8 +211,7 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { await openHome(page); await revealPipeline(page); await expect.poll(() => running(page)).toBe(true); - const framesOn = await steadyFramesIn(page); - expect(framesOn).toBeGreaterThan(5); + expectRunning(await framesPerDisplayFrame(page), "a visible loop"); // display:none -> offsetParent null. This is the CSS-hidden case. await hidePipeline(page); @@ -227,10 +222,7 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { // per display frame in one window, as above. await revealPipeline(page); await expect.poll(() => running(page), { timeout: 3000 }).toBe(true); - const back = await framesPerDisplayFrame(page, 500); - expect(back.logo).toBeGreaterThan(5); - expect(back.display).toBeGreaterThan(0); - expect(back.logo).toBeLessThan(back.display * 1.6); + expectRunning(await framesPerDisplayFrame(page, 500), "a re-entered loop"); }); test("viewport-offscreen arena stops rendering even though it is not display:none", async ({ page }) => { @@ -254,7 +246,7 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { document.getElementById("pipeline-progress").style.transform = "none"; }); await expect.poll(() => running(page), { timeout: 3000 }).toBe(true); - expect(await framesIn(page, 500)).toBeGreaterThan(5); + expectRunning(await framesPerDisplayFrame(page, 500), "a restored loop"); }); test("live reduced-motion toggle freezes to the static rest frame and stops the loop", async ({ page }) => { @@ -290,8 +282,7 @@ test.describe("Decorative mark lifecycle in the pipeline arena", () => { await page.emulateMedia({ reducedMotion: "no-preference" }); await expect.poll(() => running(page), { timeout: 3000 }).toBe(true); const resumed = await framesPerDisplayFrame(page, 500); - expect(resumed.logo, "the loop should have resumed painting").toBeGreaterThan(5); - expect(resumed.display, "the window should contain real display frames").toBeGreaterThan(0); + expectRunning(resumed, "the resumed loop"); // One loop paints at most once per display frame; a doubled loop would ~2x. expect(resumed.logo).toBeLessThan(resumed.display * 1.6); }); diff --git a/e2e/stu445-exact-fidelity.spec.js b/e2e/stu445-exact-fidelity.spec.js index c9eb522..74ba5f5 100644 --- a/e2e/stu445-exact-fidelity.spec.js +++ b/e2e/stu445-exact-fidelity.spec.js @@ -24,17 +24,37 @@ async function open(page, { reducedMotion = 'no-preference' } = {}) { localStorage.setItem('hasSeenWalkthrough', 'true'); localStorage.setItem('ccc_auth_session', JSON.stringify({ email:'test@example.com', sessionToken:'test-session-token-0001' })); window.motionEvidence = []; + // The title's reveal lasts only its 0.82s animation (panel-in comes off at + // animationend), so record it the moment the class lands instead of + // racing it from outside the page. + window.revealEvidence = null; + new MutationObserver((mutations) => { + for (const { target } of mutations) { + if (window.revealEvidence || target.id !== 'progress-title-text' || !target.classList.contains('panel-in')) continue; + const style = getComputedStyle(target); + window.revealEvidence = { name:style.animationName, delay:style.animationDelay, duration:style.animationDuration }; + } + }).observe(document, { subtree:true, attributes:true, attributeFilter:['class'] }); const animate = Element.prototype.animate; Element.prototype.animate = function(frames, options) { const animation = animate.call(this, frames, options); if (this.classList.contains('composer-morph')) { - const record = { frames, options, samples:[] }; + const record = { frames, options, samples:[], ghosts:document.querySelectorAll('.composer-morph').length, ghostBackground:getComputedStyle(this).backgroundColor }; window.motionEvidence.push(record); - for (const t of [0,157,314,560,1400]) setTimeout(() => { - const panel = document.getElementById('main-stage-container'); - const title = panel.querySelector('#progress-title-text'); + const panel = document.getElementById('main-stage-container'); + const title = panel.querySelector('#progress-title-text'); + for (const t of [0,157,314,560]) setTimeout(() => { record.samples.push({ t, visibility:getComputedStyle(panel).visibility, titleVisibility:getComputedStyle(title).visibility, ghost:this.isConnected }); }, t); + // The handoff is recorded the frame the ghost leaves — the moment the + // destination is revealed — rather than at a fixed wall-clock time a + // loaded machine can reach before the morph's finish fires. + const started = performance.now(); + const watch = () => { + if (this.isConnected) return requestAnimationFrame(watch); + record.handoff = { t:performance.now() - started, visibility:getComputedStyle(panel).visibility, titleVisibility:getComputedStyle(title).visibility }; + }; + requestAnimationFrame(watch); } return animation; }; @@ -83,6 +103,12 @@ async function box(page, selector, expected) { // selectors/styles: reference SHA 548e628f…91dc, preflight geometry JSON. for (const width of [1920,1440,1366,921,920,390]) { test(`reference stage and panel geometry at ${width}px`, async ({ page }) => { + // Six of these run in parallel, and each drives a whole gated pipeline + // (~5.3s of authored-pacing sleeps alone) plus ten geometry reads. The 30s + // default is a budget for one small test, not for one of six concurrent + // full-flow runs, so a saturated machine trips it on the sleeps rather + // than on a geometry mismatch. + test.setTimeout(60_000); await page.setViewportSize({ width, height:width === 390 ? 844 : width === 1366 ? 768 : width === 1440 ? 900 : 1080 }); await open(page); const run = await gates(page); @@ -137,25 +163,31 @@ test('morph keyframes, opaque ghost, hidden destination and reading-order reveal await open(page); const run = await gates(page); await submit(page); - await expect(page.locator('.composer-morph')).toHaveCount(1); - expect(await page.locator('.composer-morph').evaluate(el => getComputedStyle(el).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)'); - await expect(page.locator('#main-stage-container')).toHaveCSS('visibility','hidden'); - // Wait for the reveal and the last motion sample themselves, not for - // wall-clock sleeps: under load the 1120ms morph and the sampling timers - // land late, and a fixed sleep then reads the panel before it reveals. - const reveal = () => page.locator('#progress-title-text').evaluate(el => ({ name:getComputedStyle(el).animationName, delay:getComputedStyle(el).animationDelay, duration:getComputedStyle(el).animationDuration })); - await expect.poll(reveal).toEqual({ name:'fidelity-rise', delay:'0.32s', duration:'0.5s' }); - await page.waitForFunction(() => window.motionEvidence[0]?.samples.some(s => s.t === 1400)); + // The ghost, the hidden destination and the reveal are all transient — the + // 1120ms morph, then a 0.82s reveal — so open() records them inside the + // page as they happen. Checked from outside, a loaded machine can finish + // the morph before the check runs. + await page.waitForFunction(() => window.revealEvidence && window.motionEvidence[0]?.handoff); const [motion] = await page.evaluate(() => window.motionEvidence); + expect(motion.ghosts).toBe(1); + expect(motion.ghostBackground).not.toBe('rgba(0, 0, 0, 0)'); + expect(await page.evaluate(() => window.revealEvidence)).toEqual({ name:'fidelity-rise', delay:'0.32s', duration:'0.5s' }); expect(motion.options.duration).toBe(1120); expect(motion.frames.map(f => f.offset)).toEqual([0,.14,.28,1]); expect(motion.frames[2].easing).toBe('cubic-bezier(.32,1.38,.5,1)'); const initial = motion.frames[0].transform.match(/scale\(([^,]+),([^\)]+)\)/).slice(1).map(Number); const shrink = motion.frames[2].transform.match(/scale\(([^,]+),([^\)]+)\)/).slice(1).map(Number); shrink.forEach((v,i) => expect(v/initial[i]).toBeCloseTo(.93,6)); - expect(motion.samples.filter(s => s.t <= 560).map(s => s.visibility)).toEqual(['hidden','hidden','hidden','hidden']); - expect(motion.samples.filter(s => s.t <= 560).map(s => s.titleVisibility)).toEqual(['hidden','hidden','hidden','hidden']); - expect(motion.samples.find(s => s.t === 1400)).toMatchObject({ visibility:'visible',ghost:false }); + // Every sample taken while the ghost was still morphing saw the destination + // and its title hidden (on an unloaded machine, all four do)... + const during = motion.samples.filter(s => s.ghost); + expect(during.length).toBeGreaterThan(0); + expect(during.map(s => s.visibility)).toEqual(during.map(() => 'hidden')); + expect(during.map(s => s.titleVisibility)).toEqual(during.map(() => 'hidden')); + // ...and the handoff reveals it as the ghost leaves — never before the + // 1120ms morph has run. + expect(motion.handoff).toMatchObject({ visibility:'visible', titleVisibility:'visible' }); + expect(motion.handoff.t).toBeGreaterThanOrEqual(1120); run.release('architect'); run.release('generator'); run.release('review'); await expect(page.locator('#results-view')).toBeVisible(); await page.waitForTimeout(1500);