react-semaphor 0.1.101 → 0.1.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/dist/chunks/{dashboard-controls-DZ3mfITk.js → dashboard-controls-B69rp7Eg.js} +1 -1
  2. package/dist/chunks/{dashboard-controls-BOWrupBW.js → dashboard-controls-BcI9OPvx.js} +3 -3
  3. package/dist/chunks/{dashboard-json-37BidbHV.js → dashboard-json-BJ1c04y3.js} +1 -1
  4. package/dist/chunks/{dashboard-json-BHLhFEdC.js → dashboard-json-DsxHtR1h.js} +1 -1
  5. package/dist/chunks/{edit-dashboard-visual-D7Ic8u1b.js → edit-dashboard-visual-C2PPgPSf.js} +3 -3
  6. package/dist/chunks/{edit-dashboard-visual-BJD5eZpR.js → edit-dashboard-visual-CRvSRhC4.js} +1 -1
  7. package/dist/chunks/{editor-action-buttons-DPAlJF2w.js → editor-action-buttons-18dPoIIF.js} +1 -1
  8. package/dist/chunks/{editor-action-buttons-DpbEl7Rx.js → editor-action-buttons-D74G-fOO.js} +2 -2
  9. package/dist/chunks/{index-DUJ50AjE.js → index-BYjv54tY.js} +1 -1
  10. package/dist/chunks/{index-CGyjzIO0.js → index-DLEb3N-R.js} +4 -4
  11. package/dist/chunks/{resource-management-panel-Ddyzqha7.js → resource-management-panel-DToljP14.js} +1 -1
  12. package/dist/chunks/{resource-management-panel-DpASGkNn.js → resource-management-panel-k_ZQIBfh.js} +2 -2
  13. package/dist/chunks/{schedule-dashboard-e0SVfJ6s.js → schedule-dashboard-fjtSpUVj.js} +4 -4
  14. package/dist/chunks/schedule-dashboard-vZXqGP-q.js +6 -0
  15. package/dist/chunks/{use-visual-utils-CfCFNHJ6.js → use-visual-utils-Btxew3Er.js} +1 -1
  16. package/dist/chunks/{use-visual-utils-CFuV8lsO.js → use-visual-utils-CMaqO2nT.js} +1 -1
  17. package/dist/dashboard/index.cjs +1 -1
  18. package/dist/dashboard/index.js +1 -1
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.js +4 -4
  21. package/dist/surfboard/index.cjs +1 -1
  22. package/dist/surfboard/index.js +1 -1
  23. package/package.json +1 -1
  24. package/dist/chunks/schedule-dashboard-Dy7czCFY.js +0 -6
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-DUJ50AjE.js"),f=require("react");require("react-dom");const O=require("./schedule-dashboard-Dy7czCFY.js"),ne=require("./editor-action-buttons-DPAlJF2w.js");function Ce(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const D=Ce(f);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-BYjv54tY.js"),f=require("react");require("react-dom");const O=require("./schedule-dashboard-vZXqGP-q.js"),ne=require("./editor-action-buttons-18dPoIIF.js");function Ce(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const D=Ce(f);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,10 +1,10 @@
1
1
  import { jsxs as n, jsx as e, Fragment as E } from "react/jsx-runtime";
2
- import { b as J, bp as Ns, bq as ys, u as y, aC as Ce, aD as Se, B as k, aF as Me, aG as W, br as ke, a8 as Ve, aj as R, ao as oe, bs as ws, aU as Le, ap as ie, aq as le, ar as ce, as as Pe, at as te, bt as Q, ax as Qe, I as V, bu as xs, aW as Ds, bv as Cs, bw as qe, bx as He, c as X, by as Be, bz as Ss, bA as Ms, bB as ks, bC as Ls, bD as Ps, ah as C, z as ze, ad as de, bE as ue, bF as Ke, av as As, bG as Is, ac as H, aR as _, bH as Es, bI as Fs, bJ as Ts, bK as We, bL as Je, bM as re, bN as ne, bj as be, aM as ve, bO as Ne, aX as Xe, bP as ye, aw as Ye, a$ as Ze, bQ as Gs, b3 as Rs, b4 as Os, b5 as Us, b6 as qs, b7 as zs, b8 as _s, b9 as $s, ba as js, bR as Vs, aO as Qs, be as Hs, bS as Bs, bT as Ks, aa as _e, aA as se, bU as Ws, R as fe, bV as Js, bW as Xs, bX as Ys, bY as Zs, y as ea, bZ as sa, b_ as aa, b$ as ta, c0 as ra, v as na } from "./index-CGyjzIO0.js";
2
+ import { b as J, bp as Ns, bq as ys, u as y, aC as Ce, aD as Se, B as k, aF as Me, aG as W, br as ke, a8 as Ve, aj as R, ao as oe, bs as ws, aU as Le, ap as ie, aq as le, ar as ce, as as Pe, at as te, bt as Q, ax as Qe, I as V, bu as xs, aW as Ds, bv as Cs, bw as qe, bx as He, c as X, by as Be, bz as Ss, bA as Ms, bB as ks, bC as Ls, bD as Ps, ah as C, z as ze, ad as de, bE as ue, bF as Ke, av as As, bG as Is, ac as H, aR as _, bH as Es, bI as Fs, bJ as Ts, bK as We, bL as Je, bM as re, bN as ne, bj as be, aM as ve, bO as Ne, aX as Xe, bP as ye, aw as Ye, a$ as Ze, bQ as Gs, b3 as Rs, b4 as Os, b5 as Us, b6 as qs, b7 as zs, b8 as _s, b9 as $s, ba as js, bR as Vs, aO as Qs, be as Hs, bS as Bs, bT as Ks, aa as _e, aA as se, bU as Ws, R as fe, bV as Js, bW as Xs, bX as Ys, bY as Zs, y as ea, bZ as sa, b_ as aa, b$ as ta, c0 as ra, v as na } from "./index-DLEb3N-R.js";
3
3
  import * as S from "react";
4
4
  import { useState as w, useMemo as ae, useEffect as oa } from "react";
5
5
  import "react-dom";
6
- import { g as we, A as ia, V as la, S as ca } from "./schedule-dashboard-e0SVfJ6s.js";
7
- import { S as $e } from "./editor-action-buttons-DpbEl7Rx.js";
6
+ import { g as we, A as ia, V as la, S as ca } from "./schedule-dashboard-fjtSpUVj.js";
7
+ import { S as $e } from "./editor-action-buttons-D74G-fOO.js";
8
8
  /**
9
9
  * @license lucide-react v0.453.0 - ISC
10
10
  *
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),a=require("./index-DUJ50AjE.js");require("react");require("react-dom");function i(){const o=a.useDashboardStore(e=>e.dashboard),r=a.useDashboardStore(e=>e.actions.setDashboard),t=a.useDashboardStore(e=>e.showDashboardJSON),n=a.useDashboardStore(e=>e.actions.setShowDashboardJSON);return s.jsxs("div",{className:a.cn("relative p-2",{hidden:!t}),children:[s.jsxs(a.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>n(!1),children:[s.jsx(a.X,{className:"mr-2 h-4 w-4"}),"Close"]}),s.jsx(a.de,{onChange:e=>{if(e)try{JSON.parse(e),r(JSON.parse(e))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(o,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}exports.default=i;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),a=require("./index-BYjv54tY.js");require("react");require("react-dom");function i(){const o=a.useDashboardStore(e=>e.dashboard),r=a.useDashboardStore(e=>e.actions.setDashboard),t=a.useDashboardStore(e=>e.showDashboardJSON),n=a.useDashboardStore(e=>e.actions.setShowDashboardJSON);return s.jsxs("div",{className:a.cn("relative p-2",{hidden:!t}),children:[s.jsxs(a.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>n(!1),children:[s.jsx(a.X,{className:"mr-2 h-4 w-4"}),"Close"]}),s.jsx(a.de,{onChange:e=>{if(e)try{JSON.parse(e),r(JSON.parse(e))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(o,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}exports.default=i;
@@ -1,5 +1,5 @@
1
1
  import { jsxs as o, jsx as r } from "react/jsx-runtime";
2
- import { u as s, c as l, B as h, X as d, d as c } from "./index-CGyjzIO0.js";
2
+ import { u as s, c as l, B as h, X as d, d as c } from "./index-DLEb3N-R.js";
3
3
  import "react";
4
4
  import "react-dom";
5
5
  function N() {
@@ -1,10 +1,10 @@
1
1
  import { jsxs as a, jsx as e, Fragment as ae } from "react/jsx-runtime";
2
- import { b as xe, ah as at, ab as ne, aa as A, c1 as ua, at as V, c2 as Y, c3 as W, c4 as X, c5 as Z, c6 as B, aQ as ve, B as q, aU as qe, aP as ma, c7 as cs, c8 as ds, c9 as us, ca as ms, cb as Ut, i as st, X as Ae, cc as Wa, aX as hs, ao as gt, ap as xt, aq as vt, ar as bt, as as Mt, ag as Ie, bi as je, bk as ke, bl as Te, cd as Ln, c as Q, bm as Ee, ce as Xa, u as we, ax as la, cf as nt, aM as _t, aw as Ke, cg as ps, ch as fs, ci as Za, cj as Al, a$ as gs, ck as en, cl as El, cm as xs, bG as vs, cn as Je, co as Vn, cp as Dl, cq as Il, cr as Ol, cs as tn, ct as bs, cu as Ns, cv as Ft, cw as ys, cx as Ml, bq as Rl, cy as Pl, cz as Cs, cA as Fl, cB as an, cC as Ll, ad as Vl, aO as zl, cD as jl, cE as Ba, cF as Nt, cG as Re, cH as yt, ac as ha, cI as Bl, cJ as ws, b_ as $a, aB as nn, cK as pa, cL as Jt, cM as $l, b1 as fa, cN as Ct, aA as ql, cO as qa, aH as sn, a8 as Ss, cP as ln, cQ as Kl, cR as ks, cS as Ts, cT as ra, bY as Ea, cU as Gl, cV as As, cW as Ul, cX as _l, cY as Jl, cZ as ga, c_ as Hl, c$ as Ql, d0 as zn, d1 as Yl, E as xa, f as rn, d2 as Wl, d3 as on, bs as Xl, I as De, d4 as Zl, d5 as er, bK as va, bL as ba, bM as Ye, bN as na, d6 as tr, aj as Ht, d7 as cn, d8 as ar, d9 as nr, da as sr, db as Es, dc as lr, dd as dn, de as un, df as mn, dg as hn, dh as Qt, di as Na, dj as Ds, dk as Ka, dl as pn, dm as fn, dn as Is, dp as Os, dq as Ms, dr as gn, ds as ya, dt as Ca, du as rr, P as lt, h as rt, j as it, bj as xn, au as Fe, aC as Rs, aD as Ps, aF as Fs, bu as Ls, aW as Vs, dv as pt, dw as ir, dx as or, dy as cr, dz as dr, dA as ur, bD as mr, az as zt, dB as hr, dC as zs, dD as vn, dE as Rt, dF as Bt, dG as js, dH as ze, dI as ue, dJ as me, dK as he, bt as Ne, dL as tt, b$ as Bs, dM as pr, dN as fr, dO as gr, dP as xr, dQ as vr, dR as br, a4 as $s, dS as Nr, dT as yr, dU as Cr, k as wa, l as Sa, m as ka, n as Ta, o as Ot, p as Yt, dV as wr, dW as Ve, dX as Zt, dY as jn, dZ as Sr, d_ as Bn, d$ as kr, q as Wt, e0 as Pe, e1 as Tr, e2 as $n, e3 as qn, e4 as Ar, e5 as Er, e6 as Dr, e7 as Ir, e8 as Da, e9 as qs, ea as Kn, bT as Or, eb as Mr, ec as Rr, ed as Pr, ee as Fr, ef as Lr, a0 as Gn, eg as Un, eh as Vr, ei as zr, ej as Ks, ek as jr, el as Gs, em as Br, en as $r, eo as qr, ep as Kr, eq as Gr, er as Ur, es as _r, et as Jr, eu as Hr, ev as Qr, ew as Us, ex as Yr, ey as Wr, ez as Xr, eA as Zr, eB as ei, eC as ti, eD as ai, eE as _s, aE as ni, eF as Ia, eG as Oa, eH as bn, G as si, eI as li, eJ as ri, bF as Js, eK as Be, av as ii, J as ia, eL as oi, eM as ci, eN as Nn, eO as Hs, eP as yn, eQ as di, bn as ui, eR as _n, eS as mi, eT as hi, eU as pi, eV as sa, eW as $t, eX as qt, eY as fi, eZ as gi, e_ as xi, e$ as Qs, f0 as vi, f1 as Ga, f2 as bi, f3 as Ni, f4 as oa, f5 as ft, f6 as Ua, f7 as _a, f8 as ca, f9 as Ys, fa as Kt, fb as Gt, fc as Cn, fd as yi, fe as Ma, ff as Ra, fg as Ci, fh as Pa, fi as wi, fj as Jn, fk as Si, fl as ki, fm as Ti, fn as Ai, fo as Ei, fp as Fa, fq as Di, fr as Ii, fs as Oi, F as Mi } from "./index-CGyjzIO0.js";
2
+ import { b as xe, ah as at, ab as ne, aa as A, c1 as ua, at as V, c2 as Y, c3 as W, c4 as X, c5 as Z, c6 as B, aQ as ve, B as q, aU as qe, aP as ma, c7 as cs, c8 as ds, c9 as us, ca as ms, cb as Ut, i as st, X as Ae, cc as Wa, aX as hs, ao as gt, ap as xt, aq as vt, ar as bt, as as Mt, ag as Ie, bi as je, bk as ke, bl as Te, cd as Ln, c as Q, bm as Ee, ce as Xa, u as we, ax as la, cf as nt, aM as _t, aw as Ke, cg as ps, ch as fs, ci as Za, cj as Al, a$ as gs, ck as en, cl as El, cm as xs, bG as vs, cn as Je, co as Vn, cp as Dl, cq as Il, cr as Ol, cs as tn, ct as bs, cu as Ns, cv as Ft, cw as ys, cx as Ml, bq as Rl, cy as Pl, cz as Cs, cA as Fl, cB as an, cC as Ll, ad as Vl, aO as zl, cD as jl, cE as Ba, cF as Nt, cG as Re, cH as yt, ac as ha, cI as Bl, cJ as ws, b_ as $a, aB as nn, cK as pa, cL as Jt, cM as $l, b1 as fa, cN as Ct, aA as ql, cO as qa, aH as sn, a8 as Ss, cP as ln, cQ as Kl, cR as ks, cS as Ts, cT as ra, bY as Ea, cU as Gl, cV as As, cW as Ul, cX as _l, cY as Jl, cZ as ga, c_ as Hl, c$ as Ql, d0 as zn, d1 as Yl, E as xa, f as rn, d2 as Wl, d3 as on, bs as Xl, I as De, d4 as Zl, d5 as er, bK as va, bL as ba, bM as Ye, bN as na, d6 as tr, aj as Ht, d7 as cn, d8 as ar, d9 as nr, da as sr, db as Es, dc as lr, dd as dn, de as un, df as mn, dg as hn, dh as Qt, di as Na, dj as Ds, dk as Ka, dl as pn, dm as fn, dn as Is, dp as Os, dq as Ms, dr as gn, ds as ya, dt as Ca, du as rr, P as lt, h as rt, j as it, bj as xn, au as Fe, aC as Rs, aD as Ps, aF as Fs, bu as Ls, aW as Vs, dv as pt, dw as ir, dx as or, dy as cr, dz as dr, dA as ur, bD as mr, az as zt, dB as hr, dC as zs, dD as vn, dE as Rt, dF as Bt, dG as js, dH as ze, dI as ue, dJ as me, dK as he, bt as Ne, dL as tt, b$ as Bs, dM as pr, dN as fr, dO as gr, dP as xr, dQ as vr, dR as br, a4 as $s, dS as Nr, dT as yr, dU as Cr, k as wa, l as Sa, m as ka, n as Ta, o as Ot, p as Yt, dV as wr, dW as Ve, dX as Zt, dY as jn, dZ as Sr, d_ as Bn, d$ as kr, q as Wt, e0 as Pe, e1 as Tr, e2 as $n, e3 as qn, e4 as Ar, e5 as Er, e6 as Dr, e7 as Ir, e8 as Da, e9 as qs, ea as Kn, bT as Or, eb as Mr, ec as Rr, ed as Pr, ee as Fr, ef as Lr, a0 as Gn, eg as Un, eh as Vr, ei as zr, ej as Ks, ek as jr, el as Gs, em as Br, en as $r, eo as qr, ep as Kr, eq as Gr, er as Ur, es as _r, et as Jr, eu as Hr, ev as Qr, ew as Us, ex as Yr, ey as Wr, ez as Xr, eA as Zr, eB as ei, eC as ti, eD as ai, eE as _s, aE as ni, eF as Ia, eG as Oa, eH as bn, G as si, eI as li, eJ as ri, bF as Js, eK as Be, av as ii, J as ia, eL as oi, eM as ci, eN as Nn, eO as Hs, eP as yn, eQ as di, bn as ui, eR as _n, eS as mi, eT as hi, eU as pi, eV as sa, eW as $t, eX as qt, eY as fi, eZ as gi, e_ as xi, e$ as Qs, f0 as vi, f1 as Ga, f2 as bi, f3 as Ni, f4 as oa, f5 as ft, f6 as Ua, f7 as _a, f8 as ca, f9 as Ys, fa as Kt, fb as Gt, fc as Cn, fd as yi, fe as Ma, ff as Ra, fg as Ci, fh as Pa, fi as wi, fj as Jn, fk as Si, fl as ki, fm as Ti, fn as Ai, fo as Ei, fp as Fa, fq as Di, fr as Ii, fs as Oi, F as Mi } from "./index-DLEb3N-R.js";
3
3
  import * as Ja from "react";
4
4
  import Ha, { useState as $, useEffect as ge, useRef as We, useCallback as $e, useContext as wn, useMemo as Se, Suspense as Ri } from "react";
5
- import { d as Sn } from "./editor-action-buttons-DpbEl7Rx.js";
5
+ import { d as Sn } from "./editor-action-buttons-D74G-fOO.js";
6
6
  import { createPortal as Pi } from "react-dom";
7
- import { u as Fi } from "./use-visual-utils-CfCFNHJ6.js";
7
+ import { u as Fi } from "./use-visual-utils-Btxew3Er.js";
8
8
  import { u as Li } from "./use-click-outside-CMeO_QFI.js";
9
9
  /**
10
10
  * @license lucide-react v0.453.0 - ISC
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-DUJ50AjE.js"),E=require("react"),Je=require("./editor-action-buttons-DPAlJF2w.js"),Ys=require("react-dom"),Ws=require("./use-visual-utils-CFuV8lsO.js"),Xs=require("./use-click-outside-B9T3lmcw.js");function Zs(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const Ke=Zs(E);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-BYjv54tY.js"),E=require("react"),Je=require("./editor-action-buttons-18dPoIIF.js"),Ys=require("react-dom"),Ws=require("./use-visual-utils-CMaqO2nT.js"),Xs=require("./use-click-outside-B9T3lmcw.js");function Zs(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const Ke=Zs(E);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,4 +1,4 @@
1
- "use strict";const s=require("react/jsx-runtime"),e=require("./index-DUJ50AjE.js"),v=require("./use-visual-utils-CFuV8lsO.js"),C=require("react");/**
1
+ "use strict";const s=require("react/jsx-runtime"),e=require("./index-BYjv54tY.js"),v=require("./use-visual-utils-CMaqO2nT.js"),C=require("react");/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,6 +1,6 @@
1
1
  import { jsxs as u, jsx as y, Fragment as C } from "react/jsx-runtime";
2
- import { b as Q, ab as g, aa as t, B as S, c as b, q as k, u as D, a8 as F, ac as z, ad as I, ae as E, af as B, ag as L, X as U, ah as h } from "./index-CGyjzIO0.js";
3
- import { u as K, a as N } from "./use-visual-utils-CfCFNHJ6.js";
2
+ import { b as Q, ab as g, aa as t, B as S, c as b, q as k, u as D, a8 as F, ac as z, ad as I, ae as E, af as B, ag as L, X as U, ah as h } from "./index-DLEb3N-R.js";
3
+ import { u as K, a as N } from "./use-visual-utils-Btxew3Er.js";
4
4
  import { useState as V } from "react";
5
5
  /**
6
6
  * @license lucide-react v0.453.0 - ISC
@@ -1063,7 +1063,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1063
1063
 
1064
1064
  `)},flush(e){e.enqueue(`data: [DONE]
1065
1065
 
1066
- `)}})}});var KZe=HGe(()=>mJ(Ar([Un({type:ut("text-start"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("text-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Un({type:ut("text-end"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("error"),errorText:$e()}),Un({type:ut("tool-input-start"),toolCallId:$e(),toolName:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Un({type:ut("tool-input-delta"),toolCallId:$e(),inputTextDelta:$e()}),Un({type:ut("tool-input-available"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional()}),Un({type:ut("tool-input-error"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional(),errorText:$e()}),Un({type:ut("tool-output-available"),toolCallId:$e(),output:co(),providerExecuted:wr().optional(),dynamic:wr().optional(),preliminary:wr().optional()}),Un({type:ut("tool-output-error"),toolCallId:$e(),errorText:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Un({type:ut("reasoning-start"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("reasoning-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Un({type:ut("reasoning-end"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("source-url"),sourceId:$e(),url:$e(),title:$e().optional(),providerMetadata:ir.optional()}),Un({type:ut("source-document"),sourceId:$e(),mediaType:$e(),title:$e(),filename:$e().optional(),providerMetadata:ir.optional()}),Un({type:ut("file"),url:$e(),mediaType:$e(),providerMetadata:ir.optional()}),Un({type:uJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:$e().optional(),data:co(),transient:wr().optional()}),Un({type:ut("start-step")}),Un({type:ut("finish-step")}),Un({type:ut("start"),messageId:$e().optional(),messageMetadata:co().optional()}),Un({type:ut("finish"),messageMetadata:co().optional()}),Un({type:ut("abort")}),Un({type:ut("message-metadata"),messageMetadata:co()})])));function XZe(e){return e.type.startsWith("data-")}function CJ(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=CJ(o,s):n[r]=s}return n}function QZe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function NJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await _w({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await _w({text:QZe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Fy(e){return e.type.startsWith("tool-")}function JZe(e){return e.type==="dynamic-tool"}function QE(e){return Fy(e)||JZe(e)}function K$(e){return e.type.split("-").slice(1).join("-")}function eKe({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function tKe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,p,m;function g(w){const C=u.message.parts.filter(Fy).find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(w){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(w){var S;const C=u.message.parts.find(k=>Fy(k)&&k.toolCallId===w.toolCallId),j=w,_=C;C!=null?(C.state=w.state,_.input=j.input,_.output=j.output,_.errorText=j.errorText,_.rawInput=j.rawInput,_.preliminary=j.preliminary,_.providerExecuted=(S=j.providerExecuted)!=null?S:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var S;const C=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),j=w,_=C;C!=null?(C.state=w.state,_.toolName=w.toolName,_.input=j.input,_.output=j.output,_.errorText=j.errorText,_.rawInput=(S=j.rawInput)!=null?S:_.rawInput,_.preliminary=j.preliminary,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function v(w){if(w!=null){const S=u.message.metadata!=null?CJ(u.message.metadata,w):w;t!=null&&await W$({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(Fy);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await NJ(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:K$(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:K$(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(XZe(a)){(n==null?void 0:n[a.type])!=null&&await W$({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(C=>w.type===C.type&&w.id===C.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function nKe({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}Tx({prefix:"aitxt",size:24});Tx({prefix:"aiobj",size:24});var rKe=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};Tx({prefix:"aiobj",size:24});var sKe={};zZe(sKe,{object:()=>iKe,text:()=>oKe});var oKe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),iKe=({schema:e})=>{const t=$Ze(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await NJ(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await _w({text:n});if(!s.success)throw new G$({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await lI({value:s.value,schema:t});if(!o.success)throw new G$({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}},aKe=$f({name:$e(),version:$e()}),uI=$f({_meta:pr(qt({}).loose())}),mb=uI,lKe=qt({method:$e(),params:pr(uI)}),cKe=$f({experimental:pr(qt({}).loose()),logging:pr(qt({}).loose()),prompts:pr($f({listChanged:pr(wr())})),resources:pr($f({subscribe:pr(wr()),listChanged:pr(wr())})),tools:pr($f({listChanged:pr(wr())}))});mb.extend({protocolVersion:$e(),capabilities:cKe,serverInfo:aKe,instructions:pr($e())});var uKe=mb.extend({nextCursor:pr($e())}),dKe=qt({name:$e(),description:pr($e()),inputSchema:qt({type:ut("object"),properties:pr(qt({}).loose())}).loose()}).loose();uKe.extend({tools:ru(dKe)});var fKe=qt({type:ut("text"),text:$e()}).loose(),hKe=qt({type:ut("image"),data:sJ(),mimeType:$e()}).loose(),jJ=qt({uri:$e(),mimeType:pr($e())}).loose(),pKe=jJ.extend({text:$e()}),mKe=jJ.extend({blob:sJ()}),gKe=qt({type:ut("resource"),resource:Ar([pKe,mKe])}).loose();mb.extend({content:ru(Ar([fKe,hKe,gKe])),isError:wr().default(!1).optional()}).or(mb.extend({toolResult:co()}));var ZS="2.0",bKe=qt({jsonrpc:ut(ZS),id:Ar([$e(),hb().int()])}).merge(lKe).strict(),xKe=qt({jsonrpc:ut(ZS),id:Ar([$e(),hb().int()]),result:mb}).strict(),yKe=qt({jsonrpc:ut(ZS),id:Ar([$e(),hb().int()]),error:qt({code:hb().int(),message:$e(),data:pr(co())})}).strict(),vKe=qt({jsonrpc:ut(ZS)}).merge(qt({method:$e(),params:pr(uI)})).strict();Ar([bKe,vKe,xKe,yKe]);async function wKe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var SKe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await wf(this.body),l=await wf(this.headers),u=await wf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},p=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:U$({"Content-Type":"application/json",...h},`ai-sdk/${Z$}`,H$()),body:JSON.stringify(p),credentials:m,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await wf(this.body),a=await wf(this.headers),l=await wf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,m=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:U$(f,`ai-sdk/${Z$}`,H$()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},dI=class extends SKe{constructor(e={}){super(e)}processResponseStream(e){return qGe({stream:e,schema:KZe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},CKe=class{constructor({generateId:e=AGe,id:t=e(),transport:n=new dI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new rKe,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await wKe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(m=x.role)!=null?m:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:p,output:m,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>QE(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>QE(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:eKe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let p;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}p=g}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await nKe({stream:tKe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function NKe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(QE);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function jKe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var kKe=jKe;const EKe=zc(kKe);var kJ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(kJ(e,t,"read from private field"),n?n.call(e):t.get(e)),Yi=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Wl=(e,t,n,r)=>(kJ(e,t,"write to private field"),t.set(e,n),n);function _Ke(e,t){return t!=null?EKe(e,t):e}var ko,$y,Ly,Fm,$m,Lm,Ef,JE,e_,MKe=class{constructor(e=[]){Yi(this,ko,void 0),Yi(this,$y,"ready"),Yi(this,Ly,void 0),Yi(this,Fm,new Set),Yi(this,$m,new Set),Yi(this,Lm,new Set),this.pushMessage=t=>{Wl(this,ko,Tn(this,ko).concat(t)),Tn(this,Ef).call(this)},this.popMessage=()=>{Wl(this,ko,Tn(this,ko).slice(0,-1)),Tn(this,Ef).call(this)},this.replaceMessage=(t,n)=>{Wl(this,ko,[...Tn(this,ko).slice(0,t),this.snapshot(n),...Tn(this,ko).slice(t+1)]),Tn(this,Ef).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?_Ke(t,n):t;return Tn(this,Fm).add(r),()=>{Tn(this,Fm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,$m).add(t),()=>{Tn(this,$m).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Lm).add(t),()=>{Tn(this,Lm).delete(t)}),Yi(this,Ef,()=>{Tn(this,Fm).forEach(t=>t())}),Yi(this,JE,()=>{Tn(this,$m).forEach(t=>t())}),Yi(this,e_,()=>{Tn(this,Lm).forEach(t=>t())}),Wl(this,ko,e)}get status(){return Tn(this,$y)}set status(e){Wl(this,$y,e),Tn(this,JE).call(this)}get error(){return Tn(this,Ly)}set error(e){Wl(this,Ly,e),Tn(this,e_).call(this)}get messages(){return Tn(this,ko)}set messages(e){Wl(this,ko,[...e]),Tn(this,Ef).call(this)}};ko=new WeakMap;$y=new WeakMap;Ly=new WeakMap;Fm=new WeakMap;$m=new WeakMap;Lm=new WeakMap;Ef=new WeakMap;JE=new WeakMap;e_=new WeakMap;var _f,X$=class extends CKe{constructor({messages:e,...t}){const n=new MKe(e);super({...t,state:n}),Yi(this,_f,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,_f)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,_f)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,_f)["~registerErrorCallback"](r),Wl(this,_f,n)}};_f=new WeakMap;function EJ({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new X$(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new X$(n));const o="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=N.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=N.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return N.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function DKe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function TKe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function RKe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function IKe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function _J(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:IKe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function MJ(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function AKe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=J(x=>x.dashboard.aiScopeTables),r=(b=Uw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=EJ({transport:new dI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Bi.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:nW(x)}})}),onToolCall:p,sendAutomaticallyWhen:NKe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:_J(n||[])}}),x.toolName==="getDashboardContext"){const y=J.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=MJ(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function DJ(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=Uw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=bn({queryKey:["assistant-profile",n],queryFn:()=>qn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function TJ({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(Y6,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Mw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(B_,{className:r});case"view":return c.jsx(vc,{className:r});case"materialized view":return c.jsx(sie,{className:r});case"model":return c.jsx(Xw,{className:r});case"file":return c.jsx(Ti,{className:r});case"dataset":return c.jsx(hl,{className:r});case"upload":return c.jsx(W_,{className:r});case"url":return c.jsx(r8,{className:r});default:return c.jsx(Kw,{className:r})}}const RJ=M.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Ea,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(us.Input,{ref:n,className:K("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));RJ.displayName=us.Input.displayName;const ly=e=>e.label||(e==null?void 0:e.name),Q$=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function PKe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=N.useState(""),[m,g]=N.useState(""),b=s.filter(C=>{if(!h)return!0;const j=ly(C).toLowerCase(),_=Q$(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||_.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(ly(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>ly(j)===m);C&&(o.some(_=>"id"in C&&"id"in _?C.id===_.id:C.name===_.name&&C.connectionId===_.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(_S,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(RJ,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(jr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),l==null||l()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(MS,{className:"min-h-60",children:[c.jsx(DS,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(jr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(TS,{children:b.map((C,j)=>{const _=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,E=ly(C);return c.jsxs(RS,{value:E,onSelect:()=>{_?n==null||n(C):t(C)},onMouseDown:T=>{T.preventDefault(),T.stopPropagation()},className:K("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:Mw(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:Q$(C)})]}),_&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Rr,{className:"h-3 w-3 text-background"})})]},k)})})]})]})})}const t_=e=>e.name||e.name,OKe=e=>{const t=t_(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function FKe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=N.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(er,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(wn,{children:[c.jsx(Sn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[Mw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:t_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(En,{side:"top",className:"max-w-xs",children:OKe(d)})]},h)}),u&&c.jsxs(wn,{open:s,onOpenChange:o,children:[c.jsx(Sn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(R_,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(En,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:Mw(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:t_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function IJ(e){return e.type==="dataset"&&e.label||e.name}function $Ke(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function LKe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ce,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),IJ(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function zKe(e){const{tokenProps:t}=Ge(),n=J(l=>l.authToken)||e;Ee(l=>l.selectedConnectionId),Ee(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=bn({queryKey:["semantic-domains"],queryFn:()=>qn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function BKe(e,t){const{tokenProps:n}=Ge(),r=J(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=bn({queryKey:["datasets",e],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function VKe(e){var g,b;const{tokenProps:t}=Ge(),n=J(x=>x.authToken)||e,{connections:r}=zi(e),s=Ee(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=bn({queryKey:["databases",s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:m||[],refetch:p,label:l}}function HKe(e){var g;const{tokenProps:t}=Ge(),n=J(b=>b.authToken)||e,{connections:r}=zi(e),s=Ee(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ee(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=bn({queryKey:["schemas",s,o],queryFn:()=>qn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function AJ(e){const{tokenProps:t}=Ge(),n=J(h=>h.authToken)||e,{connections:r}=zi(e),s=Ee(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=bn({queryKey:["dataModels",s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function UKe(){var S,C,j;const e=Ee(_=>_.card.dataSource);Ee(_=>_.actions.updateDirectSource);const t=Ee(_=>_.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=zi(),{databases:i,isPending:a,error:l,label:u}=VKe(),{schemas:d,isPending:f,error:h,label:p}=HKe(),{error:m}=AJ(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=p==null?void 0:p.toLowerCase(),v=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:_},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(et,{children:i.map(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(rt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(et,{children:d.map(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function WKe(){const e=Ee(l=>l.card.dataSource),t=Ee(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(W_,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ti,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function qKe(){const e=Ee(f=>f.card.dataSource),t=Ee(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Cn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Cn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(jr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Kw,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function YKe(e,t){var y,v;const{tokenProps:n}=Ge(),r=J(w=>w.authToken)||t,{connections:s}=zi(t),o=Ee(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=Ee(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=Ee(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=bn({queryKey:[e,o,i,a],queryFn:()=>qn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var S;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function Dw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(md,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function GKe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=zi(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=cr(),{entities:m,isLoading:g,error:b}=YKe("table"),{dataModels:x,isPending:y,error:v}=AJ(),w=E=>{const T=s.find(O=>O.id===E);if(!T)return;const R=T.type==="upload"?"upload":T.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:T.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(E)},S=E=>{var D,I;const T=n||[],R=T.some(F=>F.name===E.name&&F.type===E.type);let O;if(R)O=T.filter(F=>!(F.name===E.name&&F.type===E.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((D=e.dbSelection)==null?void 0:D.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:E.name,dialect:E.dialect};O=[...T,F]}t==null||t(O)},C=E=>{const T=n||[],R=T.some(D=>D.type==="model"&&D.name===E.name);let O;R?O=T.filter(D=>!(D.type==="model"&&D.name===E.name)):O=[...T,E],t==null||t(O)},j=m.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),_=x.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const E=n||[];let T=[...E];if(d==="tables"){const O=j.filter(D=>!E.some(I=>I.name===D.name&&I.type==="table")).map(D=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:D.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:D.name,dialect:D.dialect}});T=[...E,...O]}else if(d==="datamodels"){const R=_.filter(O=>!E.some(D=>D.name===O.name&&D.type==="model"));T=[...E,...R]}t(T)},[d,j,_,n,e,t]);return N.useEffect(()=>{r&&r(k)},[r,k]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(et,{children:s.map(E=>c.jsx(pe,{className:"hover:bg-muted",value:E.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(hl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:E.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(WKe,{}),e.connectionType==="url"&&c.jsx(qKe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(UKe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(ls,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ut,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ut,{value:"datamodels",children:["Data Models (",_.length,")"]})]}),c.jsxs(Yn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Dw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const T=n.some(R=>R.name===E.name&&R.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[c.jsx(un,{id:`table-${E.name}`,checked:T,onCheckedChange:()=>S(E),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),c.jsxs(Yn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Dw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(E=>{const T=n.some(R=>R.name===E.name&&R.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(E),children:[c.jsx(un,{id:`dataModel-${E.name}`,checked:T,onCheckedChange:()=>C(E),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:E.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function ZKe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,u]=N.useState(""),d=N.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);N.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=zKe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=BKe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],_=j.some(E=>E.id===C.id&&E.type==="dataset");let k;if(_)k=j.filter(E=>!(E.id===C.id&&E.type==="dataset"));else{const E={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};k=[...j,E]}n==null||n(k)},v=g.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],_=v.filter(E=>!C.some(T=>T.id===E.id&&T.type==="dataset")).map(E=>({id:E.id,datasetType:E.type,name:E.name||E.table,label:E.label,domainId:E.domainId,description:E.description,database:E.database,schema:E.schema,type:"dataset",connectionId:E.connectionId,connectionType:E.connectionType,dialect:E.dialect,datamodelId:E.datamodelId,sql:E.sql})),k=[...C,..._];n(k)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),c.jsx(et,{children:m.map(C=>c.jsx(pe,{className:"hover:bg-muted",value:C.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:C.label}),c.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),p&&c.jsx(Dw,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search datasets...",value:l,onChange:C=>u(C.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Dw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(C=>{const j=r.some(_=>_.id===C.id&&_.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[c.jsx(un,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:_=>_.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:C.label||C.name}),c.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function fI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=cr(),d=J(T=>T.isVisualEditing),f=J(T=>T.dashboard.aiContext),{setAiContext:h}=Gt(),p=N.useRef(null),[m,g]=N.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=N.useCallback(T=>{const R=T;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:R,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...R!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=N.useCallback(T=>{u({...n,...T})},[n,u]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),N.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),N.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const S=T=>{const R=a.filter(O=>!(O.name===T.name&&O.type===T.type));l(R)},C=()=>{l([])},j=N.useCallback(T=>{l(T)},[]),_=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(T=>{p.current=T,g(!0)},[]);function E(){var T,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(T=a==null?void 0:a[0])==null?void 0:T.connectionId,D=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:D,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(as,{open:e,onOpenChange:t,children:c.jsx(Br,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Vr,{className:"flex-shrink-0",children:[c.jsx(Hr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Ds,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(ls,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsx(Ut,{value:"database",children:"Direct Source"}),c.jsx(Ut,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(ZKe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:k}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(GKe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(LKe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ms,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:_,disabled:!m,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:E,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function KKe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=N.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Ya-n;if(l.length>u){ze.error(`You can only attach ${Ya} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=gQ(l);if(f.forEach(({file:h,error:p})=>{ze.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>JR(p)));e(h)}catch(h){console.error("Failed to process files:",h),ze.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ya}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ya,title:n>=Ya?`Maximum ${Ya} files allowed`:"Attach files",children:c.jsx(F_,{className:"h-4 w-4 text-muted-foreground"})})]})}function XKe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=N.useState(!1),a=N.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=N.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=N.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=N.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=Ya-r;if(h.length>p){ze.error(`You can only attach ${Ya} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=gQ(h);if(g.forEach(({file:b,error:x})=>{ze.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>JR(x)));t(b),ze.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),ze.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:K("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(W_,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ya-r," slot(s) available"]})]})})]})}const hI=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),b=N.useRef(null),x=_p();rCe(),nCe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=$1(),{queueMessage:C}=Mp(),{addFileAttachment:j,removeFileAttachment:_,clearFileAttachments:k,getFileAttachments:E}=DD(),T=MD(l),R=Ee(B=>B.card.dataSource),O=J(B=>B.dashboard.aiContext),D=J(B=>{var G;return(G=B.dashboard.aiContext)==null?void 0:G.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const B=b.current;if(B){if(!e||e.length===0){B.style.height="10px";return}B.style.height="auto";const G=Math.min(Math.max(B.scrollHeight,10),200);B.style.height=`${G}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const B=setTimeout(()=>{I()},0);return()=>clearTimeout(B)},[I]);const F=()=>{const B=e.trim();!B&&T.length===0||(a!=="ready"?(C(l,B,T),t(""),k(l)):r({preventDefault:()=>{}}))},z=B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),F()),B.key==="@"&&(U(),f(!0))},V=N.useCallback(B=>{const G=dUe(B.nativeEvent);G.length>0&&(B.preventDefault(),G.forEach(async Z=>{const re=await JR(Z);j(l,re)}))},[j,l]),$=N.useCallback(B=>{B.forEach(G=>{j(l,G)})},[j,l]),P=N.useCallback(B=>{B.forEach(G=>{j(l,G)})},[j,l]),H=N.useCallback(B=>{_(l,B)},[_,l]),L=B=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===B.id||Z.name===B.name)){const Z=x.selectedEntities.filter(re=>!(re.id&&re.id===B.id||re.name===B.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,B];y({selectedEntities:Z})}},A=B=>{L(B)},W=B=>{var re;if(!x.selectedEntities.some(X=>X.id&&X.id===B.id||X.name===B.name)){const X=[...x.selectedEntities,B];y({selectedEntities:X})}const Z="label"in B?B.label:B.name;t(e+`@${Z} `),f(!1),(re=b.current)==null||re.focus()},q=B=>{const G=x.selectedEntities.filter(X=>!(X.id&&X.id===B.id||X.name===B.name));y({selectedEntities:G});const re=`@${"label"in B?B.label:B.name}`;e.includes(re)&&t(e.replace(re,"").trim())},Y=B=>{const G=new Set(B.map(X=>X.id||X.name)),Z=x.selectedEntities.filter(X=>!G.has(X.id||X.name));y({selectedEntities:Z});let re=e;B.forEach(X=>{const ne=`@${"label"in X?X.label:X.name}`;re=re.replace(ne,"").trim()}),t(re)},U=N.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(XKe,{onFilesDropped:$,currentFileCount:T.length,disabled:s,className:"space-y-4",children:[c.jsx(FKe,{entities:x.selectedEntities,availableEntities:D||[],onRemoveEntity:q,onRemoveEntities:Y}),T.length>0&&c.jsx(fUe,{files:T,onRemove:H,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:z,onPaste:V,onFocus:()=>{I(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Ss,{open:d,onOpenChange:B=>{B&&U(),f(B)},children:[c.jsx(Cs,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Qoe,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(Ns,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:B=>B.preventDefault(),children:c.jsx(PKe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var B;f(!1),(B=b.current)==null||B.focus()},availableEntities:D||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{D&&y({selectedEntities:D})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(KKe,{onFilesSelected:P,disabled:s,currentFileCount:T.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(pie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&T.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:F,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(u8,{className:"size-4"})})]})]})]}),c.jsx(fI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||qS,dialogMode:"aiContext"})]})});hI.displayName="ChatInputWithContext";function PJ({assistantType:e,className:t}){const n=rW(e),{removeFromQueue:r}=Mp();return n.length===0?null:c.jsxs("div",{className:K("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(vl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function OJ({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=rW(e),{dequeueMessage:o}=Mp();N.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function FJ(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=N.useRef(null),[a,l]=N.useState(!0),[u,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(0),b=N.useRef(!1),x=N.useRef(0),y=N.useRef(a),v=N.useRef(),w=N.useRef({key:null,count:0,length:0}),S=N.useCallback(()=>{const k=i.current;return k?k.scrollHeight-k.scrollTop-k.clientHeight:0},[]),C=N.useCallback((k={})=>{if(!i.current)return;const{force:T=!1,instant:R=!1}=k;if(!T&&!y.current||!a&&!T)return;const O=R||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!T&&!y.current){b.current=!1,v.current=void 0;return}const D=i.current;if(!D){b.current=!1,v.current=void 0;return}const I=D.scrollHeight;O==="smooth"&&"scrollTo"in D?D.scrollTo({top:I,behavior:O}):D.scrollTop=I,g.current=D.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),j=N.useCallback(()=>{const k=i.current;if(!k)return;const E=g.current,T=k.scrollTop,R=T-E;if(g.current=T,R<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=S()<=n;d(O),l(O),y.current=O,O&&(h(!1),m(0))},[S,n]),_=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>{y.current=a},[a]),N.useEffect(()=>{const k=i.current;if(!k||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=k?k.scrollTop:0,x.current=k?k.scrollHeight:0;return}g.current=k.scrollTop,x.current=k.scrollHeight;const E=w.current,T=e[e.length-1],R=(T==null?void 0:T.id)??(T==null?void 0:T.messageId)??(T==null?void 0:T.createdAt)??(T==null?void 0:T.timestamp)??e.length,O=Array.isArray(T==null?void 0:T.parts)?T.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(T==null?void 0:T.content)=="string"?T.content.length:typeof(T==null?void 0:T.text)=="string"?T.text.length:0,D=e.length>E.count,I=R!==E.key,F=O>E.length,z=s&&(T==null?void 0:T.role)==="assistant"&&!D&&(I||F),V=o||z;if(w.current={key:R,count:e.length,length:O},a&&(D||I||F||V)){C({force:!1,instant:V});return}if(!a&&D){const $=e.length-E.count;$>0&&(h(!0),m(P=>P+$))}else!a&&F&&(h(!0),m($=>$>0?$:1))},[e,C,a,s,o]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>{if(typeof ResizeObserver>"u")return;const k=i.current;if(!k)return;x.current=k.scrollHeight;const E=new ResizeObserver(()=>{const T=i.current;if(!T)return;const R=x.current,O=T.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return E.observe(k),()=>{E.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:_}}function $J(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=N.useState(r),a=N.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=N.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=N.useCallback(()=>{i(r)},[r]);return N.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function LJ(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:bQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const QKe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function JKe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Lw),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=ip(),y=N.useRef(null);J(Ve=>Ve.dashboard.aiScopeTables),J(Ve=>Ve.isDashboardEditing);const v=J(Ve=>Ve.selectedSheetId),{setDataSource:w}=cr(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Gt(),_=_p(),{setCurrentAIContext:k,updateSelectedEntities:E,setReasoningEffort:T,setShowReasoning:R}=$1(),{clearQueue:O}=Mp(),{clearFileAttachments:D,getFileAttachments:I}=DD(),F=MD("dashboard"),z=J(Ve=>Ve.dashboard.aiContext),V=Ee(Ve=>Ve.card.dataSource),{assistantProfile:$}=DJ(),P=J(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:H,isLoading:L,messages:A,setMessages:W,status:q,stop:Y,errorMessage:U,clearError:B}=AKe(),G=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),Z=N.useCallback(()=>{G(!g)},[g,G]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,G]);const[re,X]=N.useState(""),Q=Ve=>{X(Ve.target.value)};function ne({sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:Ne,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:Ne,dataSource:Te}),!v)return;const Le={id:Dr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ke==="horizontalBar"?"y":"x"}},type:Ke,sql:Ve,python:ve,dataSource:Te,config:Ne,connectionId:He},nt={id:Dr(),cards:[Le],activeCardId:Le.id};j(!0),S(v,nt,"end"),C(nt.id)}const le=Ve=>{Ve.preventDefault();const Ue=re.trim();if(!Ue&&F.length===0)return;const ht=[];Ue&&ht.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&ht.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),H({role:"user",parts:ht}),X(""),D("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),OJ({assistantType:"dashboard",status:q,isLoading:L,sendMessage:H});const{hasActiveTools:ae}=LJ(A),{visibleMessages:fe,hasMoreMessages:xe,totalMessageCount:ke,loadMoreMessages:Me,resetMessageWindow:de}=$J(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:Oe,hasNewMessages:mt,newMessageCount:be,scrollToBottom:se,handleScroll:ue,resetNewMessageCount:we}=FJ(fe,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ze();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};H(Ue)}function Pe(Ve){Ze(),H({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ze(),H({role:"user",parts:[{type:"text",text:Ve}]}),se({force:!0})}const Nt=N.useCallback(async()=>{const Ve=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ve),ze.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),ze.error("Unable to copy conversation")}},[A]);function Ze(){_.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const Lt=(re==null?void 0:re.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ce(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Mt(){return c.jsxs(sp,{children:[c.jsx(op,{asChild:!0,children:c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Mb,{className:"size-3.5"})})}),c.jsxs(Vd,{align:"end",children:[c.jsx(Wf,{children:"Options"}),c.jsx(bd,{}),c.jsx(Hm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Hm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Hm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const fn=c.jsxs("div",{"data-role":"dashboard-assistant",className:K("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ce(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Mt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Nt,children:"Copy Conversation"}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(O_,{className:"size-4"}):c.jsx(Qw,{className:"size-4"})}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),B(),de()},children:c.jsx(Jw,{className:"size-4"})}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(_l,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ue,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[xe&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:Me,className:"text-xs",children:["Load ",Math.min(5,ke-fe.length)," ","more messages (",ke-fe.length," ","hidden)"]})}),c.jsx(yQ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ae&&c.jsx(xQ,{status:q,errorMessage:U})]}),c.jsx(Ko,{orientation:"horizontal"})]}),e&&!Oe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ys,{className:"h-4 w-4"}),mt&&be>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:be>9?"9+":be})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&Lt&&c.jsx(vQ,{onClick:Se,placeholders:QKe}),c.jsx("div",{children:Lt&&$&&c.jsx(TJ,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(PJ,{assistantType:"dashboard",className:"mb-3"}),c.jsx(hI,{ref:y,setInput:X,stop:Y,input:re,handleInputChange:Q,handleSubmit:Ve=>{Ze(),le(Ve),se({force:!0})},isLoading:L,status:q,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(fI,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:V||qS,dialogMode:"aiContext"})]});return g&&s?In.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:fn})}),s):fn}function eXe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Gt(),o=J(d=>d.dashboard.sheets),a=J(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=J(d=>d.isDashboardEditing),u=J(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),ze.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=$T(m),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),ze.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function tXe(e,t){switch(e.interactionMode){case"drillToDetail":nXe(e,t);break;case"drillThrough":rXe(e,t);break;case"drillToURL":sXe(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function nXe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function rXe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function sXe(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function oXe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Br,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Vr,{children:[c.jsx(Hr,{children:i||"Insight Detail"}),c.jsx(Ds,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(RZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(AZ,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function iXe(){const e=zt(w=>w.interactionStates),t=zt(w=>w.setInteractionState),n=zt(w=>w.clearLastInteractionEvent),r=zt(w=>w.replaceCardWithInsight),s=zt(w=>w.setPendingDrillThrough),o=zt(w=>w.pendingDrillThrough),i=zt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Gt(),{selectDashboard:u}=_b(),d=J(w=>w.dashboard),f=J(w=>w.filterValues),{data:h,isLoading:p}=dde((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=PZ(m.insightId,{enabled:m.open&&!!m.insightId}),x=N.useRef(new Set),y=N.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:C})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:w,insightId:S,filters:C,contextMode:j})=>{r(w,S,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:_})=>{const E={sourceCardId:da,interactionMode:"clickFilter",filterGroups:[{filters:w}]},T={...Po(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:_};t(da,T)}}),[a,r,f,l,d,s,t]);N.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const C=S.lastInteractionEvent,j=`${w}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{tXe(C,y)}catch(_){console.error("Error executing interaction event:",_)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),N.useEffect(()=>{if(!(!o||!h||p))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(oXe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function aXe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=lXe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function lXe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function cXe(e){return e?`Back to ${e}`:"Back"}function uXe(){var x,y,v,w,S;const e=zt(C=>C.interactionStates[da]),t=J(C=>C.actions.goBackFromDrill),n=J(C=>C.actions.clearDrillContext),{selectDashboard:r}=_b(),[s,o]=N.useState({x:16,y:16}),[i,a]=N.useState(!1),l=N.useRef({x:0,y:0});N.useEffect(()=>{if(!i)return;const C=_=>{o({x:_.clientX-l.current.x,y:_.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},m=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),l.current={x:C.clientX-s.x,y:C.clientY-s.y})};aXe(f);const b=cXe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((C,j)=>{const _=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[_," = ",k]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(I6,{className:"mr-2 h-4 w-4"}),b]})})]})})}function zJ(){var X;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=ip(),s=((X=n==null?void 0:n.cardDisplay)==null?void 0:X.mode)==="print",o=N.useRef(null),i=N.useRef(null),[a,l]=N.useState(!1),u=nd(Q=>Q.setFullscreen),d=nd(Q=>Q.setPanelOpen),f=nd(Q=>Q.setContainer),h=JU("dashboard"),p=eW(),m=tW("dashboard"),g=h.isOpen,b=p==="dashboard",x=J(Q=>Q.isVisualEditing),y=J(Q=>Q.themeStyle),v=J(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.sheets}),w=J(Q=>Q.isDashboardEditing),S=J(Q=>Q.selectedSheetId),C=J(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),j=J(Q=>Q.isDashboardPanelOpen),_=J(Q=>Q.actions.setIsDashboardPanelOpen),{getDefaultSheetId:k,setDefaultSheetId:E,clearDefaultSheetId:T}=b6(C),[R,O]=N.useState(null);u1(At.DASHBOARD);const{setSelectedSheetId:D,setSheetTitle:I,addSheet:F,setSheets:z}=Gt();eXe(i);const{setActiveAssistantType:V}=$1();N.useEffect(()=>{if(C){const Q=k();O(Q)}},[C,k]),N.useEffect(()=>{g?V("dashboard"):p==="dashboard"&&u(null)},[g,V,p,u]);function $(Q){var ne,le;Q?((ne=o.current)==null||ne.resize(40),d("dashboard",!0),V("dashboard")):(d("dashboard",!1),u(null),(le=o.current)==null||le.resize(0),V(null))}function P(){const Q={id:Dr(),title:"New Sheet"};F(Q),D(Q.id)}function H(Q,ne){if(!C)return;R===Q?(T(),O(null),ze.success("Default sheet cleared")):(E(Q),O(Q),ze.success(`"${ne}" set as default sheet`))}function L(Q){Q<1?(d("dashboard",!1),u(null),V(null)):(g||d("dashboard",!0),V("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(Q,ne)=>{Q.dataTransfer.setData("tabIndex",ne.toString())},q=Q=>{Q.preventDefault()},Y=(Q,ne)=>{const le=Q.dataTransfer.getData("tabIndex");if(le===ne.toString())return;const ae=Array.from(v||[]),[fe]=ae.splice(parseInt(le),1);ae.splice(ne,0,fe),z(ae)},U=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function B(){var Q,ne;if(v&&v.length>1||w)return c.jsxs(Ur,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&U&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{_(!j)},className:"h-8 p-2",children:j?c.jsx(W6,{className:"h-4 w-4"}):c.jsx(q6,{className:"h-4 w-4"})}),v==null?void 0:v.map((le,ae)=>{const fe=S===le.id,xe=R===le.id;return c.jsxs(Ut,{draggable:!0,onDragStart:ke=>W(ke,ae),onDragOver:q,onDrop:ke=>Y(ke,ae),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>D(le.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:le.id,children:[c.jsx(Gg,{enabled:w&&fe,text:le.title,onSave:ke=>I(le.id,ke),children:le.title},le.id),!w&&fe&&c.jsx("div",{title:xe?"Clear default sheet":"Set as default sheet",children:c.jsx(bie,{className:K("ml-1 size-3 cursor-pointer transition-all",xe?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ke=>{ke.stopPropagation(),H(le.id,le.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},le.id)}),w&&c.jsx("div",{style:{borderRadius:(ne=(Q=y==null?void 0:y.chart)==null?void 0:Q.options)==null?void 0:ne.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(jr,{className:"size-3"})})]})}function G(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(Q=>c.jsx(Yn,{style:{backgroundColor:A()},className:K("mt-0",{}),value:Q.id,children:c.jsx(ELe,{sheet:Q})},Q.id))})}function Z(){var Q;return c.jsxs(ls,{"data-role":"dashboard-tabs-container",className:K("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:ne=>{D(ne)},value:S||((Q=v==null?void 0:v[0])==null?void 0:Q.id),children:[B(),c.jsx(_l,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:G()}),c.jsx(o6e,{open:a,setOpen:l})]})}const re=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(iXe,{}),c.jsx(uXe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(TR,{className:K("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(ib,{children:Z()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(s6e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(ib,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:L,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(JKe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:Q=>u(Q?"dashboard":null),fullscreenContainer:m})})})]})]}),c.jsx("div",{ref:re,className:K("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(z_,{className:"h-5 w-5"})})})]})]}):null}function pI({children:e}){return c.jsx(Da,{style:{height:"100%",width:"100%"},children:c.jsx(pre,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(er,{delayDuration:0,children:e})})})}function BJ({children:e,preferences:t}){const{currentUser:n}=_s(),r=N.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(r9.Provider,{value:r,children:c.jsx(oR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function VJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Dl,{FallbackComponent:iS,children:c.jsx(E_,{dashboardProps:e,children:c.jsx(pI,{children:c.jsx(BJ,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(TD,{...e,type:"dashboard",children:c.jsx(zJ,{})})})})})})})}function mI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return bn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return qn(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function HJ(e,t,n){if(t==="source")return{isValid:!0};const r=Ks(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function UJ(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const WJ=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=mI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=cr(),h=Ee(D=>D.card.type),p=e==null?void 0:e.id,m=N.useCallback(D=>{if(!(e!=null&&e.config))return[];switch(D){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=N.useCallback((D,I)=>{if(p)switch(D){case"groupBy":{r(p,{groupByColumns:I});break}case"metrics":{r(p,{metricColumns:I});break}case"pivotBy":{r(p,{pivotByColumns:I});break}case"sortBy":{r(p,{sortByColumns:I});break}}},[p,r]),b=N.useCallback((D,I,F)=>{if(!p)return;const V=m(D)[I];if(V)switch(D){case"groupBy":s(p,V.id,{label:F});break;case"metrics":o(p,V.id,{label:F});break;case"pivotBy":i(p,V.id,{label:F});break;case"sortBy":a(p,V.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((D,I)=>{if(!p)return;const z=m("metrics")[D];z&&o(p,z.id,{aggregate:I,label:TH(z.name,I)})},[p,m,o]),y=N.useCallback((D,I,F)=>{if(!p)return;const V=m("groupBy")[D];if(!V)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,V.id,$)},[p,m,s]),v=N.useCallback((D,I)=>{if(!p)return;const z=m("groupBy")[D];z&&s(p,z.id,{granularity:I})},[p,m,s]),w=N.useCallback((D,I)=>{if(!p)return;const z=m("metrics")[D];z&&o(p,z.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((D,I)=>{if(console.log("handleValueAliasesChange",D,I),!p)return;console.log("handleValueAliasesChange",D,I);const z=m("metrics")[D];z&&(console.log("handleValueAliasesChange",I),o(p,z.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(D=>{if(!p)return;if(m("metrics").length===0){ze.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:D})},[p,r,m]),j=N.useCallback(D=>{p&&r(p,{showTrendline:D})},[p,r]),_=N.useCallback(D=>{p&&r(p,{trendlineWindow:D})},[p,r]),k=N.useCallback(D=>{p&&r(p,{trendlineGranularity:D})},[p,r]),E=N.useCallback(D=>{p&&r(p,{targetValue:D})},[p,r]),T=N.useCallback(D=>{var H;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=E1e(D,I,{joinPlan:(H=e==null?void 0:e.config)==null?void 0:H.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&_H();return}const z=D1e(D,I,h);if(!z){ze.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const V=HJ(D,z,h);if(!V.isValid){ze.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3});return}const $=m(z);if(MH(D,$))return;const P=RH(D,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&UJ(h,e==null?void 0:e.config,r,p,L)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),R=N.useCallback((D,I)=>{if(!p)return;const z=m(D)[I];if(z){if(D!=="sortBy"){const V=m("sortBy"),$=V.filter(P=>!(P.name===z.name&&P.qualifiedEntityName===z.qualifiedEntityName));$.length!==V.length&&r(p,{sortByColumns:$})}switch(D){case"groupBy":l(p,z.id);break;case"metrics":u(p,z.id);break;case"pivotBy":d(p,z.id);break;case"sortBy":f(p,z.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:S,removeField:R,handleFieldClick:T,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:E,cardType:h}};function Rx(e,t){var Pe,Qe,Nt,Ze,Lt;const{tokenProps:n}=Ge(),r=Co(),s=Ge().authToken||e,o=Ee(Ce=>Ce.selectedConnectionId),i=Ee(Ce=>Ce.card),{queryKey:a}=Ahe(i),l=Ee(Ce=>Ce.selectedDatamodelId),u=Ee(Ce=>Ce.isDevMode),d=Ee(Ce=>Ce.selectedDatabaseName),f=Ee(Ce=>Ce.selectedSchemaName),h=Ee(Ce=>Ce.selectedTableName),p=Ee(Ce=>Ce.actions.setSelectedConnectionId),m=Ee(Ce=>Ce.actions.setSelectedDatamodelId),g=Ee(Ce=>Ce.actions.setSelectedDatabaseName),b=Ee(Ce=>Ce.actions.setSelectedSchemaName),x=Ee(Ce=>Ce.actions.setSelectedTableName);Ee(Ce=>Ce.actions.setCardSql);const{setQueryConfig:y}=cr();function v(Ce){var fn;return o&&Ce==="API"?!1:o&&Ce==="S3"?!0:!(!o||!d||d==="NA"||((fn=k==null?void 0:k.capabilities)==null?void 0:fn.path.includes("schema"))&&!f)}function w(Ce){return o&&Ce?!(Ce==="API"||Ce==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:_,selectedConnection:k}=zi(e),{refetch:E,data:T,isLoading:R,isError:O}=bn({queryKey:["models",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),D=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:z,isFetching:V,isError:$,refetch:P}=bn({queryKey:["databases",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(D)}),{data:H,isLoading:L,isFetching:A,isError:W,refetch:q}=bn({queryKey:["schemas",o,d],queryFn:()=>qn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:Y,isLoading:U,isFetching:B,isError:G,refetch:Z}=bn({queryKey:["tables",o,d,f],queryFn:()=>qn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(D)}),{columns:re,isColumnsLoading:X,isColumnsFetching:Q,isColumnsError:ne,refetchColumns:le}=IH(e);N.useEffect(()=>{(D==="S3"||D==="API")&&(g(""),b(""),m(""),D==="API"&&x("api"))},[D,x,g,b,m]);const ae=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",fe=I?"":f||"";function xe(Ce){x(Ce),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ke(Ce){b(Ce),x("")}function Me(Ce){g(Ce==="none"?"":Ce),b(""),x(""),Ce!=="none"&&Ce!==""&&m("")}function de(Ce){p(Ce)}function Re(Ce){m(Ce==="none"?"":Ce),Ce!=="none"&&Ce!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,H&&((Nt=H==null?void 0:H.schemas)==null?void 0:Nt.length)>0;const Oe=C==null?void 0:C.connections.map(Ce=>({id:Ce.id,name:Ce.name,type:Ce.type})),mt=(Ze=T==null?void 0:T.datamodels)==null?void 0:Ze.map(Ce=>({id:Ce.id,name:Ce.name})),be=F==null?void 0:F.databases.map(Ce=>({id:Ce.database_name,name:Ce.database_name})),se=H==null?void 0:H.schemas.map(Ce=>({id:Ce.schema_name,name:Ce.schema_name})),ue=Y==null?void 0:Y.tables.map(Ce=>({id:Ce.table_name,name:Ce.table_name})),we=(Lt=T==null?void 0:T.datamodels.find(Ce=>Ce.id===l))==null?void 0:Lt.name,Se=Uy({schemaName:fe,tableName:ae,modelName:we,connectionType:D,databaseName:d||""});return{connectionItems:Oe,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:_,modelItems:mt,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:be,isDatabasesLoadingOrFetching:z||V,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:ue,selectedTableName:h,isTableLoadingOrFetching:U||B,isTableError:G,columns:re,isColumnsLoadingOrFetching:X||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:D,tableName:ae,formattedTableName:Se,schemaName:fe,refetchConnections:S,refetchModels:E,refetchDatabases:P,refetchSchemas:q,refetchTables:Z,refetchColumns:le,handleConnectionChange:de,handleDatamodelChange:Re,handleDatabaseChange:Me,handleSchemaChange:ke,handleTableChange:xe}}function cy(e){return`${e}-${Dr()}`}function J$(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function dXe(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function gI(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function qJ(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function YJ(){const e=Ee(C=>C.sqlGen),t=Ee(C=>C.isDevMode),n=Ee(C=>C.card.dataSource),r=Ee(C=>{var j,_;return(_=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=gI(n),a=qJ(n),l=Ee(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=cr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Rx(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var _;if(!t)return;const j=y(C);if(t&&a&&s){const k=x_(j,e);p(k);const E=(_=b==null?void 0:b.find(R=>R.id===l))==null?void 0:_.name,T=b_(k,bi(o||""),bi(s),E||"",g,i||"");T&&(f(T),h(!0))}else if(!t){if(kb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:cy(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:cy(j.column_name),name:j.column_name,label:J$(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Bc(j.data_type)){const k={...j,role:"groupby",id:cy(j.column_name),name:j.column_name,type:j.data_type,label:dXe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:cy(j.column_name),name:j.column_name,label:J$(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Uy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Uy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>Vo(C.dataType)}}function GJ(){const e=Ee(m=>m.selectedConnectionId),t=Ee(m=>m.selectedDatamodelId),n=Ee(m=>m.selectedDatabaseName),r=Ee(m=>m.selectedSchemaName),s=Ee(m=>m.selectedTableName),o=J(m=>m.dashboard.filters)||[],i=J(m=>m.selectedSheetId),a=J(m=>m.actions.addFilter),l=J(m=>m.actions.removeFilter),{removeFilterValues:u}=Gt(),{modelItems:d,tableName:f,connectionType:h}=Rx();function p(m,g="sheet",b){var k;const x=bi(m.column_name),y=bi(n||""),v=bi(r||""),w=bi(f);let S=zw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(E=>E.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${xg}.${j}.${x}`,S=`${xg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let _;if(g==="sheet"&&i?_=oje(o,C,w,n||"",y,i):_=o==null?void 0:o.find(E=>E.column===C&&E.table===w&&(E.database===y||E.database===n)),_)u(_.id),l(_.id);else{const E=Dr(),T=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:T,sql:w4(m.data_type,S,x)}),E):(a({id:E,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:T,sql:w4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),E)}}return{assignFilter:p}}function fXe({column:e}){const[t,n]=N.useState(!1),r=Ee(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=gI(r),a=Ee(x=>x.selectedDatamodelId),l=Ee(x=>x.sqlGen),{modelItems:u,connectionType:d}=Rx(),f=Ee(x=>x.actions.setSqlGen),h=Ee(x=>x.actions.setCardSql),p=Ee(x=>x.actions.setRunSql),m=qJ(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=x_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=b_(v,bi(o||""),bi(s),w||"",d,i||"");S&&(h(S),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(jp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(kp,{asChild:!0,children:c.jsx(Mb,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Gd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function hXe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function pXe({field:e,context:t="editor",fieldState:n}){const r=Ee(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=J(L=>L.dashboard.filters),a=J(L=>L.selectedSheetId),l=J(L=>L.actions.removeFilter),{removeFilterValues:u}=Gt(),{assignFilter:d}=GJ(),f=s?Xc(i,a):i,h=s?f==null?void 0:f.find(L=>{var A;return L.title===e.name||((A=L.column)==null?void 0:A.includes(e.name))}):void 0,p=!!h,m=h&&s?i==null?void 0:i.find(L=>L.id===h.id):void 0,g=m&&(m.applyToSheetIds&&m.applyToSheetIds.length>1||m.excludeSheetIds&&m.excludeSheetIds.length>0||!m.applyToSheetIds&&!m.excludeSheetIds&&!m.sheetId);s&&p&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:a});const[b,x]=N.useState(!1),[y,v]=N.useState(null),{attributes:w,listeners:S,setNodeRef:C,transform:j,transition:_,isDragging:k}=kS({id:e.id,disabled:o}),[E,T]=N.useState(!1),R=Ee(L=>L.card),{handleFieldClick:O}=WJ(R),{handleDevModeFieldClick:D,isNumberField:I}=YJ(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},z=()=>{if(s){const L={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};p&&g?(v({column:L,field:e}),x(!0)):d(L,"sheet",e)}else r?D(e):O(e)},V={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:Pi.Transform.toString(j),transition:_},H=(()=>{if(!n||s)return{};const A={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...A},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...A},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...A}}[n.state]||A})();return c.jsxs("div",{ref:C,style:$,...o?{}:w,...o?{}:S,className:K("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",H.borderColor||"border-transparent",H.bgColor||"",H.hoverBorderColor,H.hoverBgColor||"hover:bg-muted",H.opacity,H.cursor,p&&"border-accent-foreground/20 bg-accent",{"cursor-pointer":r||s,"cursor-grab active:cursor-grabbing":!o&&!r&&!s}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:z,children:[Jg(e.dataType),c.jsx(er,{children:c.jsxs(wn,{children:[c.jsx(Sn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${E?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(En,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(hXe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(fXe,{column:V})})]}),E&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Mi,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(d8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(yie,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx($b,{open:b,onOpenChange:x,children:c.jsxs(ap,{children:[c.jsxs(lp,{children:[c.jsx(up,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(dp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(cp,{children:[c.jsx(hp,{children:"Cancel"}),c.jsx(fp,{onClick:F,children:"Remove Filter"})]})]})})]})}const mXe="SEMAPHOR_CALCULATED_FIELD",gXe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function ZJ(e){return!!e.expression}function bXe(e){return!!e.expression}function xXe(e){return!!e.expression}var KJ=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(KJ||{}),Al="Accordion",yXe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[bI,vXe,wXe]=t1(Al),[KS]=Er(Al,[wXe,LZ]),xI=LZ(),XJ=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(bI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(jXe,{...o,ref:t}):c.jsx(NXe,{...s,ref:t})})});XJ.displayName=Al;var[QJ,SXe]=KS(Al),[JJ,CXe]=KS(Al,{collapsible:!1}),NXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=Fr({prop:n,defaultProp:r,onChange:s});return c.jsx(QJ,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(JJ,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(eee,{...i,ref:t})})})}),jXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=Fr({prop:n,defaultProp:r,onChange:s}),l=N.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=N.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(QJ,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(JJ,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(eee,{...o,ref:t})})})}),[kXe,XS]=KS(Al),eee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=N.useRef(null),l=ft(a,t),u=vXe(n),f=$d(s)==="ltr",h=je(e.onKeyDown,p=>{var _;if(!yXe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var E;return!((E=k.ref.current)!=null&&E.disabled)}),b=g.findIndex(k=>k.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,S=()=>{y=b+1,y>w&&(y=v)},C=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():C());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?C():S());break;case"ArrowUp":o==="vertical"&&C();break}const j=y%x;(_=g[j].ref.current)==null||_.focus()});return c.jsx(kXe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(bI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Tw="AccordionItem",[EXe,yI]=KS(Tw),tee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=XS(Tw,n),i=SXe(Tw,n),a=xI(n),l=rr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(EXe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(VZ,{"data-orientation":o.orientation,"data-state":aee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});tee.displayName=Tw;var nee="AccordionHeader",ree=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=XS(Al,n),o=yI(nee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":aee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ree.displayName=nee;var n_="AccordionTrigger",see=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=XS(Al,n),o=yI(n_,n),i=CXe(n_,n),a=xI(n);return c.jsx(bI.ItemSlot,{scope:n,children:c.jsx(D4e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});see.displayName=n_;var oee="AccordionContent",iee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=XS(Al,n),o=yI(oee,n),i=xI(n);return c.jsx(T4e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});iee.displayName=oee;function aee(e){return e?"open":"closed"}var _Xe=XJ,MXe=tee,DXe=ree,lee=see,cee=iee;const uee=_Xe,vI=M.forwardRef(({className:e,...t},n)=>c.jsx(MXe,{ref:n,className:K("border-b",e),...t}));vI.displayName="AccordionItem";const wI=M.forwardRef(({className:e,children:t,...n},r)=>c.jsx(DXe,{className:"flex",children:c.jsxs(lee,{ref:r,className:K("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(Ys,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));wI.displayName=lee.displayName;const SI=M.forwardRef(({className:e,children:t,...n},r)=>c.jsx(cee,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:K("pb-4 pt-0",e),children:t})}));SI.displayName=cee.displayName;function TXe({context:e="editor"}={}){var E,T,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");Ee(D=>D.isDevMode);const o=Ee(D=>D.card.dataSource),i=Ee(D=>D.card.config),a=Ee(D=>D.card),{autoJoinMetadata:l}=wa(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=hD(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=mI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(T=(E=i==null?void 0:i.joinPlan)==null?void 0:E.baseEntity)==null||T.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,YJ();const b=u.filter(D=>D.name.toLowerCase().includes(t.toLowerCase())||D.dataType.toLowerCase().includes(t.toLowerCase())||D.label&&D.label.toLowerCase().includes(t.toLowerCase())||D.qualifiedEntityName&&D.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=D=>{if(D.role==="metric"&&ZJ(D)||D.role==="groupby"&&D.expression)return"calculated";if(D.dataType==="number"||D.dataType==="integer"||D.dataType==="float"||D.dataType==="decimal"||D.dataType==="currency")return"metrics";const I=Ks(D.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(D=>x(D)===r)).reduce((D,I)=>{const F=I.qualifiedEntityName||"Other Fields";return D[F]||(D[F]={label:v_(I.entityName),fields:[]}),D[F].fields.push(I),D},{}),S=Object.keys(v),C=b.filter(D=>x(D)==="dimensions").length,j=b.filter(D=>x(D)==="metrics").length,_=b.filter(D=>x(D)==="calculated").length,k=b.length>0;return f?c.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:c.jsx(Tc,{size:"md",color:"muted","aria-label":"Loading data"})}):h?c.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[c.jsx(hl,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:h.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?c.jsx(Es,{className:"h-[calc(100vh-200px)] w-[290px]",children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx(hl,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):c.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&c.jsxs("div",{className:"relative mb-4",children:[c.jsx(Ea,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Bn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:D=>n(D.target.value)}),t&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),k&&c.jsx(ls,{defaultValue:"all",value:r,onValueChange:D=>s(D),className:"mb-4",children:c.jsxs(Ur,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ut,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ut,{value:"dimensions",className:"text-xs",children:[c.jsx(Xw,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ut,{value:"metrics",className:"text-xs",children:[c.jsx(Zh,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ut,{value:"calculated",className:"text-xs",children:[c.jsx(D_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]})]})})]}),c.jsxs(_l,{className:"py-2",children:[c.jsx(uee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([D,I])=>{const F=d.find(z=>z.entityName===D)||{entityName:D,label:I.label};return c.jsxs(vI,{value:D,className:"border-none",children:[c.jsx(wI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:F.label||F.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:F.label||F.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx(SI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const V=pD(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(pXe,{field:z,context:e,fieldState:V},z.id)})})})]},D)})}),Object.keys(v).length===0&&u.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(v).length===0&&u.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Ko,{orientation:"horizontal"}),c.jsx(Ko,{orientation:"vertical"})]})]})}function dee({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(TXe,{context:e})," "]})}function fee(){const e=Ee(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=cr();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=gI(e),d=(p=e.selectedEntities)==null?void 0:p[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function RXe(){fee();const e=J(l=>l.selectedSheetId),t=J(l=>l.selectedFrameId),n=J(l=>l.dashboard),r=J(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Gt(),{setCard:o}=cr(),i=Ee(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function IXe(){const e=J(n=>n.actions.setShowFilters),{hasEntities:t}=RXe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(FZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(hl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow",children:c.jsx(NS,{collisionDetection:vS,children:c.jsx(jS,{items:[],strategy:vR,children:c.jsx(dee,{context:"filter"})})})})]})}function AXe(){const e=J(r=>r.dashboard.filters),t=J(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:K("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(aR,{filter:r}),c.jsx(gS,{filter:r})]},r.id))}):null}function PXe(){const e=J(r=>r.showFilters),t=J(r=>r.isVisualEditing),n=J(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:K("",{"max-h-0 overflow-hidden":t,"flex grow overflow-auto":!t}),children:[c.jsxs("section",{className:"flex grow flex-col",children:[n&&c.jsx(AXe,{}),c.jsx(zJ,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex",children:c.jsx(IXe,{})})]})}const OXe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-DZ3mfITk.js"))),FXe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BJD5eZpR.js"))),$Xe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-37BidbHV.js"))),LXe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-Ddyzqha7.js")).then(e=>({default:e.ResourceManagementPanel})));function zXe({showControls:e=!1,showFooter:t=!0,...n}){const r=J(m=>m.isDashboardPanelOpen),s=J(m=>m.isVisualEditing),o=J(m=>m.showDashboardJSON),i=J(m=>m.actions.setIsDashboardPanelOpen),a=20,l=20,u=30,d=r,f=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{f.current&&h.current&&(r?(f.current.resize(a),h.current.resize(100-a)):(f.current.resize(0),h.current.resize(100)))},[r]);const{preferences:p}=n;return c.jsx(Dl,{FallbackComponent:iS,children:c.jsxs(E_,{dashboardProps:n,children:[c.jsx(Xue,{}),c.jsx(pI,{children:c.jsxs(BJ,{preferences:p,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx($Xe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(OXe,{})}),c.jsxs(TR,{direction:"horizontal",className:"flex grow overflow-hidden",children:[c.jsx(ib,{ref:f,className:K("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?a:0,minSize:d?l:0,maxSize:d?u:0,children:d&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(LXe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})})}),c.jsx(tX,{className:K("",{"w-0":!d})}),c.jsx(ib,{ref:h,className:"flex min-w-0 flex-1",defaultSize:d?100-a:100,minSize:d?40:100,children:c.jsxs(TD,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(FXe,{})}),c.jsx(PXe,{})]})})]})]})]})})]})})}var BXe=Object.defineProperty,VXe=(e,t,n)=>t in e?BXe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,uy=(e,t,n)=>VXe(e,typeof t!="symbol"?t+"":t,n);const HXe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},UXe={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},WXe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},qXe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},YXe={stringify:e=>e,parse:e=>e},W2={string:YXe,number:qXe,boolean:HXe,function:UXe,json:WXe};function GXe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const dy=Symbol.for("r2wc.render"),fy=Symbol.for("r2wc.connected"),gu=Symbol.for("r2wc.context"),za=Symbol.for("r2wc.props");function ZXe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=GXe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),uy(this,o,!0),uy(this,s),uy(this,r,{}),uy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[za].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?W2[x]:null;y!=null&&y.parse&&b&&(this[za][m]=y.parse(b,g,this))}for(const m of a)this[za][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[fy]=!0,this[dy]()}disconnectedCallback(){this[fy]=!1,this[gu]&&n.unmount(this[gu]),delete this[gu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?W2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[za][x]=v.parse(b,m,this),this[dy]())}[(o=fy,s=gu,r=za,dy)](){this[fy]&&(this[gu]?n.update(this[gu],this[za]):this[gu]=n.mount(this.container,e,this[za]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[za][p]},set(b){this[za][p]=b;const x=g?W2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[dy]()}})}return h}function KXe(e,t,n){const r=sj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function XXe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function QXe({root:e}){e.unmount()}function JXe(e,t={}){return ZXe(e,t,{mount:KXe,update:XXe,unmount:QXe})}const eQe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},tQe=JXe(VJ,{props:eQe});function nQe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function eL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function tL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?eL(Object(n),!0).forEach(function(r){nQe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):eL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function rQe(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function sQe(e,t){if(e==null)return{};var n=rQe(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function oQe(e,t){return iQe(e)||aQe(e,t)||lQe(e,t)||cQe()}function iQe(e){if(Array.isArray(e))return e}function aQe(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function lQe(e,t){if(e){if(typeof e=="string")return nL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return nL(e,t)}}function nL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function cQe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1066
+ `)}})}});var KZe=HGe(()=>mJ(Ar([Un({type:ut("text-start"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("text-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Un({type:ut("text-end"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("error"),errorText:$e()}),Un({type:ut("tool-input-start"),toolCallId:$e(),toolName:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Un({type:ut("tool-input-delta"),toolCallId:$e(),inputTextDelta:$e()}),Un({type:ut("tool-input-available"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional()}),Un({type:ut("tool-input-error"),toolCallId:$e(),toolName:$e(),input:co(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional(),errorText:$e()}),Un({type:ut("tool-output-available"),toolCallId:$e(),output:co(),providerExecuted:wr().optional(),dynamic:wr().optional(),preliminary:wr().optional()}),Un({type:ut("tool-output-error"),toolCallId:$e(),errorText:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Un({type:ut("reasoning-start"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("reasoning-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Un({type:ut("reasoning-end"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("source-url"),sourceId:$e(),url:$e(),title:$e().optional(),providerMetadata:ir.optional()}),Un({type:ut("source-document"),sourceId:$e(),mediaType:$e(),title:$e(),filename:$e().optional(),providerMetadata:ir.optional()}),Un({type:ut("file"),url:$e(),mediaType:$e(),providerMetadata:ir.optional()}),Un({type:uJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:$e().optional(),data:co(),transient:wr().optional()}),Un({type:ut("start-step")}),Un({type:ut("finish-step")}),Un({type:ut("start"),messageId:$e().optional(),messageMetadata:co().optional()}),Un({type:ut("finish"),messageMetadata:co().optional()}),Un({type:ut("abort")}),Un({type:ut("message-metadata"),messageMetadata:co()})])));function XZe(e){return e.type.startsWith("data-")}function CJ(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=CJ(o,s):n[r]=s}return n}function QZe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function NJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await _w({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await _w({text:QZe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Fy(e){return e.type.startsWith("tool-")}function JZe(e){return e.type==="dynamic-tool"}function QE(e){return Fy(e)||JZe(e)}function K$(e){return e.type.split("-").slice(1).join("-")}function eKe({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function tKe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,p,m;function g(w){const C=u.message.parts.filter(Fy).find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(w){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(w){var S;const C=u.message.parts.find(k=>Fy(k)&&k.toolCallId===w.toolCallId),j=w,_=C;C!=null?(C.state=w.state,_.input=j.input,_.output=j.output,_.errorText=j.errorText,_.rawInput=j.rawInput,_.preliminary=j.preliminary,_.providerExecuted=(S=j.providerExecuted)!=null?S:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var S;const C=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),j=w,_=C;C!=null?(C.state=w.state,_.toolName=w.toolName,_.input=j.input,_.output=j.output,_.errorText=j.errorText,_.rawInput=(S=j.rawInput)!=null?S:_.rawInput,_.preliminary=j.preliminary,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function v(w){if(w!=null){const S=u.message.metadata!=null?CJ(u.message.metadata,w):w;t!=null&&await W$({value:S,schema:t}),u.message.metadata=S}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,w.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const w=u.message.parts.filter(Fy);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:S}=await NJ(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerMetadata:a.providerMetadata}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:K$(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:K$(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(XZe(a)){(n==null?void 0:n[a.type])!=null&&await W$({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(C=>w.type===C.type&&w.id===C.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function nKe({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}Tx({prefix:"aitxt",size:24});Tx({prefix:"aiobj",size:24});var rKe=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};Tx({prefix:"aiobj",size:24});var sKe={};zZe(sKe,{object:()=>iKe,text:()=>oKe});var oKe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),iKe=({schema:e})=>{const t=$Ze(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await NJ(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await _w({text:n});if(!s.success)throw new G$({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await lI({value:s.value,schema:t});if(!o.success)throw new G$({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}},aKe=$f({name:$e(),version:$e()}),uI=$f({_meta:pr(qt({}).loose())}),mb=uI,lKe=qt({method:$e(),params:pr(uI)}),cKe=$f({experimental:pr(qt({}).loose()),logging:pr(qt({}).loose()),prompts:pr($f({listChanged:pr(wr())})),resources:pr($f({subscribe:pr(wr()),listChanged:pr(wr())})),tools:pr($f({listChanged:pr(wr())}))});mb.extend({protocolVersion:$e(),capabilities:cKe,serverInfo:aKe,instructions:pr($e())});var uKe=mb.extend({nextCursor:pr($e())}),dKe=qt({name:$e(),description:pr($e()),inputSchema:qt({type:ut("object"),properties:pr(qt({}).loose())}).loose()}).loose();uKe.extend({tools:ru(dKe)});var fKe=qt({type:ut("text"),text:$e()}).loose(),hKe=qt({type:ut("image"),data:sJ(),mimeType:$e()}).loose(),jJ=qt({uri:$e(),mimeType:pr($e())}).loose(),pKe=jJ.extend({text:$e()}),mKe=jJ.extend({blob:sJ()}),gKe=qt({type:ut("resource"),resource:Ar([pKe,mKe])}).loose();mb.extend({content:ru(Ar([fKe,hKe,gKe])),isError:wr().default(!1).optional()}).or(mb.extend({toolResult:co()}));var ZS="2.0",bKe=qt({jsonrpc:ut(ZS),id:Ar([$e(),hb().int()])}).merge(lKe).strict(),xKe=qt({jsonrpc:ut(ZS),id:Ar([$e(),hb().int()]),result:mb}).strict(),yKe=qt({jsonrpc:ut(ZS),id:Ar([$e(),hb().int()]),error:qt({code:hb().int(),message:$e(),data:pr(co())})}).strict(),vKe=qt({jsonrpc:ut(ZS)}).merge(qt({method:$e(),params:pr(uI)})).strict();Ar([bKe,vKe,xKe,yKe]);async function wKe(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var SKe=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await wf(this.body),l=await wf(this.headers),u=await wf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},p=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:U$({"Content-Type":"application/json",...h},`ai-sdk/${Z$}`,H$()),body:JSON.stringify(p),credentials:m,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await wf(this.body),a=await wf(this.headers),l=await wf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,m=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:U$(f,`ai-sdk/${Z$}`,H$()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},dI=class extends SKe{constructor(e={}){super(e)}processResponseStream(e){return qGe({stream:e,schema:KZe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},CKe=class{constructor({generateId:e=AGe,id:t=e(),transport:n=new dI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new rKe,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await wKe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(m=x.role)!=null?m:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:p,output:m,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>QE(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>QE(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.id})}),this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=l,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:eKe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let p;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}p=g}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await nKe({stream:tKe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function NKe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(QE);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function jKe(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var kKe=jKe;const EKe=zc(kKe);var kJ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(kJ(e,t,"read from private field"),n?n.call(e):t.get(e)),Yi=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},Wl=(e,t,n,r)=>(kJ(e,t,"write to private field"),t.set(e,n),n);function _Ke(e,t){return t!=null?EKe(e,t):e}var ko,$y,Ly,Fm,$m,Lm,Ef,JE,e_,MKe=class{constructor(e=[]){Yi(this,ko,void 0),Yi(this,$y,"ready"),Yi(this,Ly,void 0),Yi(this,Fm,new Set),Yi(this,$m,new Set),Yi(this,Lm,new Set),this.pushMessage=t=>{Wl(this,ko,Tn(this,ko).concat(t)),Tn(this,Ef).call(this)},this.popMessage=()=>{Wl(this,ko,Tn(this,ko).slice(0,-1)),Tn(this,Ef).call(this)},this.replaceMessage=(t,n)=>{Wl(this,ko,[...Tn(this,ko).slice(0,t),this.snapshot(n),...Tn(this,ko).slice(t+1)]),Tn(this,Ef).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?_Ke(t,n):t;return Tn(this,Fm).add(r),()=>{Tn(this,Fm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,$m).add(t),()=>{Tn(this,$m).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Lm).add(t),()=>{Tn(this,Lm).delete(t)}),Yi(this,Ef,()=>{Tn(this,Fm).forEach(t=>t())}),Yi(this,JE,()=>{Tn(this,$m).forEach(t=>t())}),Yi(this,e_,()=>{Tn(this,Lm).forEach(t=>t())}),Wl(this,ko,e)}get status(){return Tn(this,$y)}set status(e){Wl(this,$y,e),Tn(this,JE).call(this)}get error(){return Tn(this,Ly)}set error(e){Wl(this,Ly,e),Tn(this,e_).call(this)}get messages(){return Tn(this,ko)}set messages(e){Wl(this,ko,[...e]),Tn(this,Ef).call(this)}};ko=new WeakMap;$y=new WeakMap;Ly=new WeakMap;Fm=new WeakMap;$m=new WeakMap;Lm=new WeakMap;Ef=new WeakMap;JE=new WeakMap;e_=new WeakMap;var _f,X$=class extends CKe{constructor({messages:e,...t}){const n=new MKe(e);super({...t,state:n}),Yi(this,_f,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,_f)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,_f)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,_f)["~registerErrorCallback"](r),Wl(this,_f,n)}};_f=new WeakMap;function EJ({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new X$(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new X$(n));const o="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=N.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=N.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return N.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:l,addToolResult:r.current.addToolResult}}function DKe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function TKe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function RKe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function IKe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function _J(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:IKe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function MJ(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function AKe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=J(x=>x.dashboard.aiScopeTables),r=(b=Uw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=EJ({transport:new dI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Bi.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:nW(x)}})}),onToolCall:p,sendAutomaticallyWhen:NKe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:_J(n||[])}}),x.toolName==="getDashboardContext"){const y=J.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=MJ(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function DJ(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=Uw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=bn({queryKey:["assistant-profile",n],queryFn:()=>qn(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function TJ({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(Y6,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Mw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(B_,{className:r});case"view":return c.jsx(vc,{className:r});case"materialized view":return c.jsx(sie,{className:r});case"model":return c.jsx(Xw,{className:r});case"file":return c.jsx(Ti,{className:r});case"dataset":return c.jsx(hl,{className:r});case"upload":return c.jsx(W_,{className:r});case"url":return c.jsx(r8,{className:r});default:return c.jsx(Kw,{className:r})}}const RJ=M.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Ea,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(us.Input,{ref:n,className:K("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));RJ.displayName=us.Input.displayName;const ly=e=>e.label||(e==null?void 0:e.name),Q$=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function PKe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=N.useState(""),[m,g]=N.useState(""),b=s.filter(C=>{if(!h)return!0;const j=ly(C).toLowerCase(),_=Q$(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||_.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(ly(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>ly(j)===m);C&&(o.some(_=>"id"in C&&"id"in _?C.id===_.id:C.name===_.name&&C.connectionId===_.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(_S,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(RJ,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(jr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),l==null||l()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(MS,{className:"min-h-60",children:[c.jsx(DS,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(jr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(TS,{children:b.map((C,j)=>{const _=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,E=ly(C);return c.jsxs(RS,{value:E,onSelect:()=>{_?n==null||n(C):t(C)},onMouseDown:T=>{T.preventDefault(),T.stopPropagation()},className:K("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:Mw(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:Q$(C)})]}),_&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Rr,{className:"h-3 w-3 text-background"})})]},k)})})]})]})})}const t_=e=>e.name||e.name,OKe=e=>{const t=t_(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function FKe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=N.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(er,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(wn,{children:[c.jsx(Sn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[Mw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:t_(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(En,{side:"top",className:"max-w-xs",children:OKe(d)})]},h)}),u&&c.jsxs(wn,{open:s,onOpenChange:o,children:[c.jsx(Sn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(R_,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(vt,{className:"h-3 w-3"})})]})}),c.jsx(En,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:Mw(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:t_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function IJ(e){return e.type==="dataset"&&e.label||e.name}function $Ke(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function LKe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ce,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Fe,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),IJ(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function zKe(e){const{tokenProps:t}=Ge(),n=J(l=>l.authToken)||e;Ee(l=>l.selectedConnectionId),Ee(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=bn({queryKey:["semantic-domains"],queryFn:()=>qn(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function BKe(e,t){const{tokenProps:n}=Ge(),r=J(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=bn({queryKey:["datasets",e],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function VKe(e){var g,b;const{tokenProps:t}=Ge(),n=J(x=>x.authToken)||e,{connections:r}=zi(e),s=Ee(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:p}=bn({queryKey:["databases",s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:m||[],refetch:p,label:l}}function HKe(e){var g;const{tokenProps:t}=Ge(),n=J(b=>b.authToken)||e,{connections:r}=zi(e),s=Ee(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ee(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:p}=bn({queryKey:["schemas",s,o],queryFn:()=>qn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function AJ(e){const{tokenProps:t}=Ge(),n=J(h=>h.authToken)||e,{connections:r}=zi(e),s=Ee(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=bn({queryKey:["dataModels",s],queryFn:()=>qn(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function UKe(){var S,C,j;const e=Ee(_=>_.card.dataSource);Ee(_=>_.actions.updateDirectSource);const t=Ee(_=>_.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=zi(),{databases:i,isPending:a,error:l,label:u}=VKe(),{schemas:d,isPending:f,error:h,label:p}=HKe(),{error:m}=AJ(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=p==null?void 0:p.toLowerCase(),v=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:_},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(oe,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(et,{children:i.map(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(rt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(et,{children:d.map(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function WKe(){const e=Ee(l=>l.card.dataSource),t=Ee(l=>l.actions.updateDataSource),[n,r]=N.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(W_,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(oe,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ti,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function qKe(){const e=Ee(f=>f.card.dataSource),t=Ee(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(p=>p.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Cn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Cn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(jr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Kw,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function YKe(e,t){var y,v;const{tokenProps:n}=Ge(),r=J(w=>w.authToken)||t,{connections:s}=zi(t),o=Ee(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=Ee(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=Ee(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:p,isLoading:m,error:g,refetch:b}=bn({queryKey:[e,o,i,a],queryFn:()=>qn(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var S;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function Dw({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(md,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function GKe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=zi(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=cr(),{entities:m,isLoading:g,error:b}=YKe("table"),{dataModels:x,isPending:y,error:v}=AJ(),w=E=>{const T=s.find(O=>O.id===E);if(!T)return;const R=T.type==="upload"?"upload":T.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:T.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(E)},S=E=>{var D,I;const T=n||[],R=T.some(F=>F.name===E.name&&F.type===E.type);let O;if(R)O=T.filter(F=>!(F.name===E.name&&F.type===E.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((D=e.dbSelection)==null?void 0:D.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:E.name,dialect:E.dialect};O=[...T,F]}t==null||t(O)},C=E=>{const T=n||[],R=T.some(D=>D.type==="model"&&D.name===E.name);let O;R?O=T.filter(D=>!(D.type==="model"&&D.name===E.name)):O=[...T,E],t==null||t(O)},j=m.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),_=x.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const E=n||[];let T=[...E];if(d==="tables"){const O=j.filter(D=>!E.some(I=>I.name===D.name&&I.type==="table")).map(D=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:D.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:D.name,dialect:D.dialect}});T=[...E,...O]}else if(d==="datamodels"){const R=_.filter(O=>!E.some(D=>D.name===O.name&&D.type==="model"));T=[...E,...R]}t(T)},[d,j,_,n,e,t]);return N.useEffect(()=>{r&&r(k)},[r,k]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(et,{children:s.map(E=>c.jsx(pe,{className:"hover:bg-muted",value:E.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(hl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:E.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(WKe,{}),e.connectionType==="url"&&c.jsx(qKe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(UKe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(ls,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ut,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ut,{value:"datamodels",children:["Data Models (",_.length,")"]})]}),c.jsxs(Yn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(Dw,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(E=>{const T=n.some(R=>R.name===E.name&&R.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(E),children:[c.jsx(un,{id:`table-${E.name}`,checked:T,onCheckedChange:()=>S(E),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),c.jsxs(Yn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:E=>u(E.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(Dw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(E=>{const T=n.some(R=>R.name===E.name&&R.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(E),children:[c.jsx(un,{id:`dataModel-${E.name}`,checked:T,onCheckedChange:()=>C(E),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:E.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function ZKe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,u]=N.useState(""),d=N.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);N.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=zKe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=BKe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],_=j.some(E=>E.id===C.id&&E.type==="dataset");let k;if(_)k=j.filter(E=>!(E.id===C.id&&E.type==="dataset"));else{const E={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};k=[...j,E]}n==null||n(k)},v=g.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],_=v.filter(E=>!C.some(T=>T.id===E.id&&T.type==="dataset")).map(E=>({id:E.id,datasetType:E.type,name:E.name||E.table,label:E.label,domainId:E.domainId,description:E.description,database:E.database,schema:E.schema,type:"dataset",connectionId:E.connectionId,connectionType:E.connectionType,dialect:E.dialect,datamodelId:E.datamodelId,sql:E.sql})),k=[...C,..._];n(k)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),c.jsx(et,{children:m.map(C=>c.jsx(pe,{className:"hover:bg-muted",value:C.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:C.label}),c.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),p&&c.jsx(Dw,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search datasets...",value:l,onChange:C=>u(C.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(Dw,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(C=>{const j=r.some(_=>_.id===C.id&&_.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[c.jsx(un,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:_=>_.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:C.label||C.name}),c.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function fI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=cr(),d=J(T=>T.isVisualEditing),f=J(T=>T.dashboard.aiContext),{setAiContext:h}=Gt(),p=N.useRef(null),[m,g]=N.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=N.useCallback(T=>{const R=T;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:R,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...R!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=N.useCallback(T=>{u({...n,...T})},[n,u]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),N.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),N.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const S=T=>{const R=a.filter(O=>!(O.name===T.name&&O.type===T.type));l(R)},C=()=>{l([])},j=N.useCallback(T=>{l(T)},[]),_=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(T=>{p.current=T,g(!0)},[]);function E(){var T,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(T=a==null?void 0:a[0])==null?void 0:T.connectionId,D=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:D,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(as,{open:e,onOpenChange:t,children:c.jsx(Br,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Vr,{className:"flex-shrink-0",children:[c.jsx(Hr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Ds,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(ls,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsx(Ut,{value:"database",children:"Direct Source"}),c.jsx(Ut,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(ZKe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:k}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(GKe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(LKe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ms,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(oe,{variant:"outline",onClick:_,disabled:!m,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:E,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function KKe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=N.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Ya-n;if(l.length>u){ze.error(`You can only attach ${Ya} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=gQ(l);if(f.forEach(({file:h,error:p})=>{ze.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>JR(p)));e(h)}catch(h){console.error("Failed to process files:",h),ze.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ya}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ya,title:n>=Ya?`Maximum ${Ya} files allowed`:"Attach files",children:c.jsx(F_,{className:"h-4 w-4 text-muted-foreground"})})]})}function XKe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=N.useState(!1),a=N.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=N.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=N.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=N.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=Ya-r;if(h.length>p){ze.error(`You can only attach ${Ya} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=gQ(h);if(g.forEach(({file:b,error:x})=>{ze.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>JR(x)));t(b),ze.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),ze.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:K("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(W_,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ya-r," slot(s) available"]})]})})]})}const hI=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),b=N.useRef(null),x=_p();rCe(),nCe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=$1(),{queueMessage:C}=Mp(),{addFileAttachment:j,removeFileAttachment:_,clearFileAttachments:k,getFileAttachments:E}=DD(),T=MD(l),R=Ee(B=>B.card.dataSource),O=J(B=>B.dashboard.aiContext),D=J(B=>{var G;return(G=B.dashboard.aiContext)==null?void 0:G.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const B=b.current;if(B){if(!e||e.length===0){B.style.height="10px";return}B.style.height="auto";const G=Math.min(Math.max(B.scrollHeight,10),200);B.style.height=`${G}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const B=setTimeout(()=>{I()},0);return()=>clearTimeout(B)},[I]);const F=()=>{const B=e.trim();!B&&T.length===0||(a!=="ready"?(C(l,B,T),t(""),k(l)):r({preventDefault:()=>{}}))},z=B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),F()),B.key==="@"&&(U(),f(!0))},V=N.useCallback(B=>{const G=dUe(B.nativeEvent);G.length>0&&(B.preventDefault(),G.forEach(async Z=>{const re=await JR(Z);j(l,re)}))},[j,l]),$=N.useCallback(B=>{B.forEach(G=>{j(l,G)})},[j,l]),P=N.useCallback(B=>{B.forEach(G=>{j(l,G)})},[j,l]),H=N.useCallback(B=>{_(l,B)},[_,l]),L=B=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===B.id||Z.name===B.name)){const Z=x.selectedEntities.filter(re=>!(re.id&&re.id===B.id||re.name===B.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,B];y({selectedEntities:Z})}},A=B=>{L(B)},W=B=>{var re;if(!x.selectedEntities.some(X=>X.id&&X.id===B.id||X.name===B.name)){const X=[...x.selectedEntities,B];y({selectedEntities:X})}const Z="label"in B?B.label:B.name;t(e+`@${Z} `),f(!1),(re=b.current)==null||re.focus()},q=B=>{const G=x.selectedEntities.filter(X=>!(X.id&&X.id===B.id||X.name===B.name));y({selectedEntities:G});const re=`@${"label"in B?B.label:B.name}`;e.includes(re)&&t(e.replace(re,"").trim())},Y=B=>{const G=new Set(B.map(X=>X.id||X.name)),Z=x.selectedEntities.filter(X=>!G.has(X.id||X.name));y({selectedEntities:Z});let re=e;B.forEach(X=>{const ne=`@${"label"in X?X.label:X.name}`;re=re.replace(ne,"").trim()}),t(re)},U=N.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(XKe,{onFilesDropped:$,currentFileCount:T.length,disabled:s,className:"space-y-4",children:[c.jsx(FKe,{entities:x.selectedEntities,availableEntities:D||[],onRemoveEntity:q,onRemoveEntities:Y}),T.length>0&&c.jsx(fUe,{files:T,onRemove:H,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:z,onPaste:V,onFocus:()=>{I(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(Ss,{open:d,onOpenChange:B=>{B&&U(),f(B)},children:[c.jsx(Cs,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Qoe,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(Ns,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:B=>B.preventDefault(),children:c.jsx(PKe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var B;f(!1),(B=b.current)==null||B.focus()},availableEntities:D||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{D&&y({selectedEntities:D})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(KKe,{onFilesSelected:P,disabled:s,currentFileCount:T.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(pie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&T.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:F,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(u8,{className:"size-4"})})]})]})]}),c.jsx(fI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||qS,dialogMode:"aiContext"})]})});hI.displayName="ChatInputWithContext";function PJ({assistantType:e,className:t}){const n=rW(e),{removeFromQueue:r}=Mp();return n.length===0?null:c.jsxs("div",{className:K("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(vl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:c.jsx(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function OJ({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=rW(e),{dequeueMessage:o}=Mp();N.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function FJ(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=N.useRef(null),[a,l]=N.useState(!0),[u,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(0),b=N.useRef(!1),x=N.useRef(0),y=N.useRef(a),v=N.useRef(),w=N.useRef({key:null,count:0,length:0}),S=N.useCallback(()=>{const k=i.current;return k?k.scrollHeight-k.scrollTop-k.clientHeight:0},[]),C=N.useCallback((k={})=>{if(!i.current)return;const{force:T=!1,instant:R=!1}=k;if(!T&&!y.current||!a&&!T)return;const O=R||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!T&&!y.current){b.current=!1,v.current=void 0;return}const D=i.current;if(!D){b.current=!1,v.current=void 0;return}const I=D.scrollHeight;O==="smooth"&&"scrollTo"in D?D.scrollTo({top:I,behavior:O}):D.scrollTop=I,g.current=D.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),j=N.useCallback(()=>{const k=i.current;if(!k)return;const E=g.current,T=k.scrollTop,R=T-E;if(g.current=T,R<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const O=S()<=n;d(O),l(O),y.current=O,O&&(h(!1),m(0))},[S,n]),_=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>{y.current=a},[a]),N.useEffect(()=>{const k=i.current;if(!k||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=k?k.scrollTop:0,x.current=k?k.scrollHeight:0;return}g.current=k.scrollTop,x.current=k.scrollHeight;const E=w.current,T=e[e.length-1],R=(T==null?void 0:T.id)??(T==null?void 0:T.messageId)??(T==null?void 0:T.createdAt)??(T==null?void 0:T.timestamp)??e.length,O=Array.isArray(T==null?void 0:T.parts)?T.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(T==null?void 0:T.content)=="string"?T.content.length:typeof(T==null?void 0:T.text)=="string"?T.text.length:0,D=e.length>E.count,I=R!==E.key,F=O>E.length,z=s&&(T==null?void 0:T.role)==="assistant"&&!D&&(I||F),V=o||z;if(w.current={key:R,count:e.length,length:O},a&&(D||I||F||V)){C({force:!1,instant:V});return}if(!a&&D){const $=e.length-E.count;$>0&&(h(!0),m(P=>P+$))}else!a&&F&&(h(!0),m($=>$>0?$:1))},[e,C,a,s,o]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>{if(typeof ResizeObserver>"u")return;const k=i.current;if(!k)return;x.current=k.scrollHeight;const E=new ResizeObserver(()=>{const T=i.current;if(!T)return;const R=x.current,O=T.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return E.observe(k),()=>{E.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:_}}function $J(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=N.useState(r),a=N.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=N.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=N.useCallback(()=>{i(r)},[r]);return N.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function LJ(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:r.text||"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:bQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const QKe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function JKe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Lw),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=ip(),y=N.useRef(null);J(Ve=>Ve.dashboard.aiScopeTables),J(Ve=>Ve.isDashboardEditing);const v=J(Ve=>Ve.selectedSheetId),{setDataSource:w}=cr(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Gt(),_=_p(),{setCurrentAIContext:k,updateSelectedEntities:E,setReasoningEffort:T,setShowReasoning:R}=$1(),{clearQueue:O}=Mp(),{clearFileAttachments:D,getFileAttachments:I}=DD(),F=MD("dashboard"),z=J(Ve=>Ve.dashboard.aiContext),V=Ee(Ve=>Ve.card.dataSource),{assistantProfile:$}=DJ(),P=J(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:H,isLoading:L,messages:A,setMessages:W,status:q,stop:Y,errorMessage:U,clearError:B}=AKe(),G=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),Z=N.useCallback(()=>{G(!g)},[g,G]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,G]);const[re,X]=N.useState(""),Q=Ve=>{X(Ve.target.value)};function ne({sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:Ne,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:Ne,dataSource:Te}),!v)return;const Le={id:Dr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ke==="horizontalBar"?"y":"x"}},type:Ke,sql:Ve,python:ve,dataSource:Te,config:Ne,connectionId:He},nt={id:Dr(),cards:[Le],activeCardId:Le.id};j(!0),S(v,nt,"end"),C(nt.id)}const le=Ve=>{Ve.preventDefault();const Ue=re.trim();if(!Ue&&F.length===0)return;const ht=[];Ue&&ht.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&ht.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),H({role:"user",parts:ht}),X(""),D("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),OJ({assistantType:"dashboard",status:q,isLoading:L,sendMessage:H});const{hasActiveTools:ae}=LJ(A),{visibleMessages:fe,hasMoreMessages:xe,totalMessageCount:ke,loadMoreMessages:Me,resetMessageWindow:de}=$J(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:Oe,hasNewMessages:mt,newMessageCount:be,scrollToBottom:se,handleScroll:ue,resetNewMessageCount:we}=FJ(fe,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ze();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};H(Ue)}function Pe(Ve){Ze(),H({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ze(),H({role:"user",parts:[{type:"text",text:Ve}]}),se({force:!0})}const Nt=N.useCallback(async()=>{const Ve=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ve),ze.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),ze.error("Unable to copy conversation")}},[A]);function Ze(){_.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const Lt=(re==null?void 0:re.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ce(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Mt(){return c.jsxs(sp,{children:[c.jsx(op,{asChild:!0,children:c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Mb,{className:"size-3.5"})})}),c.jsxs(Vd,{align:"end",children:[c.jsx(Wf,{children:"Options"}),c.jsx(bd,{}),c.jsx(Hm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Hm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Hm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const fn=c.jsxs("div",{"data-role":"dashboard-assistant",className:K("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Ce(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Mt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Nt,children:"Copy Conversation"}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(O_,{className:"size-4"}):c.jsx(Qw,{className:"size-4"})}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),B(),de()},children:c.jsx(Jw,{className:"size-4"})}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(_l,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ue,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[xe&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:Me,className:"text-xs",children:["Load ",Math.min(5,ke-fe.length)," ","more messages (",ke-fe.length," ","hidden)"]})}),c.jsx(yQ,{showTools:a,showSystemMessage:u,messages:fe,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ae&&c.jsx(xQ,{status:q,errorMessage:U})]}),c.jsx(Ko,{orientation:"horizontal"})]}),e&&!Oe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ys,{className:"h-4 w-4"}),mt&&be>0&&c.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:be>9?"9+":be})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&Lt&&c.jsx(vQ,{onClick:Se,placeholders:QKe}),c.jsx("div",{children:Lt&&$&&c.jsx(TJ,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(PJ,{assistantType:"dashboard",className:"mb-3"}),c.jsx(hI,{ref:y,setInput:X,stop:Y,input:re,handleInputChange:Q,handleSubmit:Ve=>{Ze(),le(Ve),se({force:!0})},isLoading:L,status:q,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(fI,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:V||qS,dialogMode:"aiContext"})]});return g&&s?In.createPortal(c.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:c.jsx("div",{className:"flex h-full w-full",children:fn})}),s):fn}function eXe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Gt(),o=J(d=>d.dashboard.sheets),a=J(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=J(d=>d.isDashboardEditing),u=J(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),ze.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=$T(m),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),ze.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function tXe(e,t){switch(e.interactionMode){case"drillToDetail":nXe(e,t);break;case"drillThrough":rXe(e,t);break;case"drillToURL":sXe(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function nXe(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function rXe(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function sXe(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function oXe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Br,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Vr,{children:[c.jsx(Hr,{children:i||"Insight Detail"}),c.jsx(Ds,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(RZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(AZ,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function iXe(){const e=zt(w=>w.interactionStates),t=zt(w=>w.setInteractionState),n=zt(w=>w.clearLastInteractionEvent),r=zt(w=>w.replaceCardWithInsight),s=zt(w=>w.setPendingDrillThrough),o=zt(w=>w.pendingDrillThrough),i=zt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Gt(),{selectDashboard:u}=_b(),d=J(w=>w.dashboard),f=J(w=>w.filterValues),{data:h,isLoading:p}=dde((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=PZ(m.insightId,{enabled:m.open&&!!m.insightId}),x=N.useRef(new Set),y=N.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:C})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:w,insightId:S,filters:C,contextMode:j})=>{r(w,S,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:_})=>{const E={sourceCardId:da,interactionMode:"clickFilter",filterGroups:[{filters:w}]},T={...Po(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:_};t(da,T)}}),[a,r,f,l,d,s,t]);N.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const C=S.lastInteractionEvent,j=`${w}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{tXe(C,y)}catch(_){console.error("Error executing interaction event:",_)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),N.useEffect(()=>{if(!(!o||!h||p))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(oXe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(On,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function aXe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=lXe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function lXe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function cXe(e){return e?`Back to ${e}`:"Back"}function uXe(){var x,y,v,w,S;const e=zt(C=>C.interactionStates[da]),t=J(C=>C.actions.goBackFromDrill),n=J(C=>C.actions.clearDrillContext),{selectDashboard:r}=_b(),[s,o]=N.useState({x:16,y:16}),[i,a]=N.useState(!1),l=N.useRef({x:0,y:0});N.useEffect(()=>{if(!i)return;const C=_=>{o({x:_.clientX-l.current.x,y:_.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((S=e.appliedClickFilters)!=null&&S.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},m=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),l.current={x:C.clientX-s.x,y:C.clientY-s.y})};aXe(f);const b=cXe(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((C,j)=>{const _=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[_," = ",k]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(I6,{className:"mr-2 h-4 w-4"}),b]})})]})})}function zJ(){var X;const{showAssistant:e,tokenProps:t}=Ge(),{preferences:n,isConsoleMode:r}=ip(),s=((X=n==null?void 0:n.cardDisplay)==null?void 0:X.mode)==="print",o=N.useRef(null),i=N.useRef(null),[a,l]=N.useState(!1),u=nd(Q=>Q.setFullscreen),d=nd(Q=>Q.setPanelOpen),f=nd(Q=>Q.setContainer),h=JU("dashboard"),p=eW(),m=tW("dashboard"),g=h.isOpen,b=p==="dashboard",x=J(Q=>Q.isVisualEditing),y=J(Q=>Q.themeStyle),v=J(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.sheets}),w=J(Q=>Q.isDashboardEditing),S=J(Q=>Q.selectedSheetId),C=J(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),j=J(Q=>Q.isDashboardPanelOpen),_=J(Q=>Q.actions.setIsDashboardPanelOpen),{getDefaultSheetId:k,setDefaultSheetId:E,clearDefaultSheetId:T}=b6(C),[R,O]=N.useState(null);u1(At.DASHBOARD);const{setSelectedSheetId:D,setSheetTitle:I,addSheet:F,setSheets:z}=Gt();eXe(i);const{setActiveAssistantType:V}=$1();N.useEffect(()=>{if(C){const Q=k();O(Q)}},[C,k]),N.useEffect(()=>{g?V("dashboard"):p==="dashboard"&&u(null)},[g,V,p,u]);function $(Q){var ne,le;Q?((ne=o.current)==null||ne.resize(40),d("dashboard",!0),V("dashboard")):(d("dashboard",!1),u(null),(le=o.current)==null||le.resize(0),V(null))}function P(){const Q={id:Dr(),title:"New Sheet"};F(Q),D(Q.id)}function H(Q,ne){if(!C)return;R===Q?(T(),O(null),ze.success("Default sheet cleared")):(E(Q),O(Q),ze.success(`"${ne}" set as default sheet`))}function L(Q){Q<1?(d("dashboard",!1),u(null),V(null)):(g||d("dashboard",!0),V("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(Q,ne)=>{Q.dataTransfer.setData("tabIndex",ne.toString())},q=Q=>{Q.preventDefault()},Y=(Q,ne)=>{const le=Q.dataTransfer.getData("tabIndex");if(le===ne.toString())return;const ae=Array.from(v||[]),[fe]=ae.splice(parseInt(le),1);ae.splice(ne,0,fe),z(ae)},U=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function B(){var Q,ne;if(v&&v.length>1||w)return c.jsxs(Ur,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&U&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{_(!j)},className:"h-8 p-2",children:j?c.jsx(W6,{className:"h-4 w-4"}):c.jsx(q6,{className:"h-4 w-4"})}),v==null?void 0:v.map((le,ae)=>{const fe=S===le.id,xe=R===le.id;return c.jsxs(Ut,{draggable:!0,onDragStart:ke=>W(ke,ae),onDragOver:q,onDrop:ke=>Y(ke,ae),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>D(le.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:le.id,children:[c.jsx(Gg,{enabled:w&&fe,text:le.title,onSave:ke=>I(le.id,ke),children:le.title},le.id),!w&&fe&&c.jsx("div",{title:xe?"Clear default sheet":"Set as default sheet",children:c.jsx(bie,{className:K("ml-1 size-3 cursor-pointer transition-all",xe?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ke=>{ke.stopPropagation(),H(le.id,le.title||"Sheet")}})}),w&&fe&&v.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},le.id)}),w&&c.jsx("div",{style:{borderRadius:(ne=(Q=y==null?void 0:y.chart)==null?void 0:Q.options)==null?void 0:ne.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(jr,{className:"size-3"})})]})}function G(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(Q=>c.jsx(Yn,{style:{backgroundColor:A()},className:K("mt-0",{}),value:Q.id,children:c.jsx(ELe,{sheet:Q})},Q.id))})}function Z(){var Q;return c.jsxs(ls,{"data-role":"dashboard-tabs-container",className:K("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:ne=>{D(ne)},value:S||((Q=v==null?void 0:v[0])==null?void 0:Q.id),children:[B(),c.jsx(_l,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:G()}),c.jsx(o6e,{open:a,setOpen:l})]})}const re=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(iXe,{}),c.jsx(uXe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(TR,{className:K("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(ib,{children:Z()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(s6e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(ib,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:L,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(JKe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:Q=>u(Q?"dashboard":null),fullscreenContainer:m})})})]})]}),c.jsx("div",{ref:re,className:K("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(z_,{className:"h-5 w-5"})})})]})]}):null}function pI({children:e}){return c.jsx(Da,{style:{height:"100%",width:"100%"},children:c.jsx(pre,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(er,{delayDuration:0,children:e})})})}function BJ({children:e,preferences:t}){const{currentUser:n}=_s(),r=N.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(r9.Provider,{value:r,children:c.jsx(oR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function VJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Dl,{FallbackComponent:iS,children:c.jsx(E_,{dashboardProps:e,children:c.jsx(pI,{children:c.jsx(BJ,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(TD,{...e,type:"dashboard",children:c.jsx(zJ,{})})})})})})})}function mI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return bn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return qn(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function HJ(e,t,n){if(t==="source")return{isValid:!0};const r=Ks(e.dataType);if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function UJ(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const WJ=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=mI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=cr(),h=Ee(D=>D.card.type),p=e==null?void 0:e.id,m=N.useCallback(D=>{if(!(e!=null&&e.config))return[];switch(D){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=N.useCallback((D,I)=>{if(p)switch(D){case"groupBy":{r(p,{groupByColumns:I});break}case"metrics":{r(p,{metricColumns:I});break}case"pivotBy":{r(p,{pivotByColumns:I});break}case"sortBy":{r(p,{sortByColumns:I});break}}},[p,r]),b=N.useCallback((D,I,F)=>{if(!p)return;const V=m(D)[I];if(V)switch(D){case"groupBy":s(p,V.id,{label:F});break;case"metrics":o(p,V.id,{label:F});break;case"pivotBy":i(p,V.id,{label:F});break;case"sortBy":a(p,V.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((D,I)=>{if(!p)return;const z=m("metrics")[D];z&&o(p,z.id,{aggregate:I,label:TH(z.name,I)})},[p,m,o]),y=N.useCallback((D,I,F)=>{if(!p)return;const V=m("groupBy")[D];if(!V)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,V.id,$)},[p,m,s]),v=N.useCallback((D,I)=>{if(!p)return;const z=m("groupBy")[D];z&&s(p,z.id,{granularity:I})},[p,m,s]),w=N.useCallback((D,I)=>{if(!p)return;const z=m("metrics")[D];z&&o(p,z.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((D,I)=>{if(console.log("handleValueAliasesChange",D,I),!p)return;console.log("handleValueAliasesChange",D,I);const z=m("metrics")[D];z&&(console.log("handleValueAliasesChange",I),o(p,z.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(D=>{if(!p)return;if(m("metrics").length===0){ze.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:D})},[p,r,m]),j=N.useCallback(D=>{p&&r(p,{showTrendline:D})},[p,r]),_=N.useCallback(D=>{p&&r(p,{trendlineWindow:D})},[p,r]),k=N.useCallback(D=>{p&&r(p,{trendlineGranularity:D})},[p,r]),E=N.useCallback(D=>{p&&r(p,{targetValue:D})},[p,r]),T=N.useCallback(D=>{var H;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=E1e(D,I,{joinPlan:(H=e==null?void 0:e.config)==null?void 0:H.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&_H();return}const z=D1e(D,I,h);if(!z){ze.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const V=HJ(D,z,h);if(!V.isValid){ze.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3});return}const $=m(z);if(MH(D,$))return;const P=RH(D,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&UJ(h,e==null?void 0:e.config,r,p,L)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),R=N.useCallback((D,I)=>{if(!p)return;const z=m(D)[I];if(z){if(D!=="sortBy"){const V=m("sortBy"),$=V.filter(P=>!(P.name===z.name&&P.qualifiedEntityName===z.qualifiedEntityName));$.length!==V.length&&r(p,{sortByColumns:$})}switch(D){case"groupBy":l(p,z.id);break;case"metrics":u(p,z.id);break;case"pivotBy":d(p,z.id);break;case"sortBy":f(p,z.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:S,removeField:R,handleFieldClick:T,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:E,cardType:h}};function Rx(e,t){var Pe,Qe,Nt,Ze,Lt;const{tokenProps:n}=Ge(),r=Co(),s=Ge().authToken||e,o=Ee(Ce=>Ce.selectedConnectionId),i=Ee(Ce=>Ce.card),{queryKey:a}=Ahe(i),l=Ee(Ce=>Ce.selectedDatamodelId),u=Ee(Ce=>Ce.isDevMode),d=Ee(Ce=>Ce.selectedDatabaseName),f=Ee(Ce=>Ce.selectedSchemaName),h=Ee(Ce=>Ce.selectedTableName),p=Ee(Ce=>Ce.actions.setSelectedConnectionId),m=Ee(Ce=>Ce.actions.setSelectedDatamodelId),g=Ee(Ce=>Ce.actions.setSelectedDatabaseName),b=Ee(Ce=>Ce.actions.setSelectedSchemaName),x=Ee(Ce=>Ce.actions.setSelectedTableName);Ee(Ce=>Ce.actions.setCardSql);const{setQueryConfig:y}=cr();function v(Ce){var fn;return o&&Ce==="API"?!1:o&&Ce==="S3"?!0:!(!o||!d||d==="NA"||((fn=k==null?void 0:k.capabilities)==null?void 0:fn.path.includes("schema"))&&!f)}function w(Ce){return o&&Ce?!(Ce==="API"||Ce==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:_,selectedConnection:k}=zi(e),{refetch:E,data:T,isLoading:R,isError:O}=bn({queryKey:["models",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),D=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:z,isFetching:V,isError:$,refetch:P}=bn({queryKey:["databases",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(D)}),{data:H,isLoading:L,isFetching:A,isError:W,refetch:q}=bn({queryKey:["schemas",o,d],queryFn:()=>qn(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:Y,isLoading:U,isFetching:B,isError:G,refetch:Z}=bn({queryKey:["tables",o,d,f],queryFn:()=>qn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(D)}),{columns:re,isColumnsLoading:X,isColumnsFetching:Q,isColumnsError:ne,refetchColumns:le}=IH(e);N.useEffect(()=>{(D==="S3"||D==="API")&&(g(""),b(""),m(""),D==="API"&&x("api"))},[D,x,g,b,m]);const ae=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",fe=I?"":f||"";function xe(Ce){x(Ce),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ke(Ce){b(Ce),x("")}function Me(Ce){g(Ce==="none"?"":Ce),b(""),x(""),Ce!=="none"&&Ce!==""&&m("")}function de(Ce){p(Ce)}function Re(Ce){m(Ce==="none"?"":Ce),Ce!=="none"&&Ce!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,H&&((Nt=H==null?void 0:H.schemas)==null?void 0:Nt.length)>0;const Oe=C==null?void 0:C.connections.map(Ce=>({id:Ce.id,name:Ce.name,type:Ce.type})),mt=(Ze=T==null?void 0:T.datamodels)==null?void 0:Ze.map(Ce=>({id:Ce.id,name:Ce.name})),be=F==null?void 0:F.databases.map(Ce=>({id:Ce.database_name,name:Ce.database_name})),se=H==null?void 0:H.schemas.map(Ce=>({id:Ce.schema_name,name:Ce.schema_name})),ue=Y==null?void 0:Y.tables.map(Ce=>({id:Ce.table_name,name:Ce.table_name})),we=(Lt=T==null?void 0:T.datamodels.find(Ce=>Ce.id===l))==null?void 0:Lt.name,Se=Uy({schemaName:fe,tableName:ae,modelName:we,connectionType:D,databaseName:d||""});return{connectionItems:Oe,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:_,modelItems:mt,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:be,isDatabasesLoadingOrFetching:z||V,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:ue,selectedTableName:h,isTableLoadingOrFetching:U||B,isTableError:G,columns:re,isColumnsLoadingOrFetching:X||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:D,tableName:ae,formattedTableName:Se,schemaName:fe,refetchConnections:S,refetchModels:E,refetchDatabases:P,refetchSchemas:q,refetchTables:Z,refetchColumns:le,handleConnectionChange:de,handleDatamodelChange:Re,handleDatabaseChange:Me,handleSchemaChange:ke,handleTableChange:xe}}function cy(e){return`${e}-${Dr()}`}function J$(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function dXe(e,t){const n=Yo(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function gI(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function qJ(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function YJ(){const e=Ee(C=>C.sqlGen),t=Ee(C=>C.isDevMode),n=Ee(C=>C.card.dataSource),r=Ee(C=>{var j,_;return(_=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=gI(n),a=qJ(n),l=Ee(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=cr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Rx(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var _;if(!t)return;const j=y(C);if(t&&a&&s){const k=x_(j,e);p(k);const E=(_=b==null?void 0:b.find(R=>R.id===l))==null?void 0:_.name,T=b_(k,bi(o||""),bi(s),E||"",g,i||"");T&&(f(T),h(!0))}else if(!t){if(kb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:cy(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:cy(j.column_name),name:j.column_name,label:J$(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Bc(j.data_type)){const k={...j,role:"groupby",id:cy(j.column_name),name:j.column_name,type:j.data_type,label:dXe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:cy(j.column_name),name:j.column_name,label:J$(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Uy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Uy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>Vo(C.dataType)}}function GJ(){const e=Ee(m=>m.selectedConnectionId),t=Ee(m=>m.selectedDatamodelId),n=Ee(m=>m.selectedDatabaseName),r=Ee(m=>m.selectedSchemaName),s=Ee(m=>m.selectedTableName),o=J(m=>m.dashboard.filters)||[],i=J(m=>m.selectedSheetId),a=J(m=>m.actions.addFilter),l=J(m=>m.actions.removeFilter),{removeFilterValues:u}=Gt(),{modelItems:d,tableName:f,connectionType:h}=Rx();function p(m,g="sheet",b){var k;const x=bi(m.column_name),y=bi(n||""),v=bi(r||""),w=bi(f);let S=zw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(E=>E.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${xg}.${j}.${x}`,S=`${xg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let _;if(g==="sheet"&&i?_=oje(o,C,w,n||"",y,i):_=o==null?void 0:o.find(E=>E.column===C&&E.table===w&&(E.database===y||E.database===n)),_)u(_.id),l(_.id);else{const E=Dr(),T=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:T,sql:w4(m.data_type,S,x)}),E):(a({id:E,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:T,sql:w4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),E)}}return{assignFilter:p}}function fXe({column:e}){const[t,n]=N.useState(!1),r=Ee(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=gI(r),a=Ee(x=>x.selectedDatamodelId),l=Ee(x=>x.sqlGen),{modelItems:u,connectionType:d}=Rx(),f=Ee(x=>x.actions.setSqlGen),h=Ee(x=>x.actions.setCardSql),p=Ee(x=>x.actions.setRunSql),m=qJ(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=x_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=b_(v,bi(o||""),bi(s),w||"",d,i||"");S&&(h(S),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(jp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(kp,{asChild:!0,children:c.jsx(Mb,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Gd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function hXe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function pXe({field:e,context:t="editor",fieldState:n}){const r=Ee(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=J(L=>L.dashboard.filters),a=J(L=>L.selectedSheetId),l=J(L=>L.actions.removeFilter),{removeFilterValues:u}=Gt(),{assignFilter:d}=GJ(),f=s?Xc(i,a):i,h=s?f==null?void 0:f.find(L=>{var A;return L.title===e.name||((A=L.column)==null?void 0:A.includes(e.name))}):void 0,p=!!h,m=h&&s?i==null?void 0:i.find(L=>L.id===h.id):void 0,g=m&&(m.applyToSheetIds&&m.applyToSheetIds.length>1||m.excludeSheetIds&&m.excludeSheetIds.length>0||!m.applyToSheetIds&&!m.excludeSheetIds&&!m.sheetId);s&&p&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:a});const[b,x]=N.useState(!1),[y,v]=N.useState(null),{attributes:w,listeners:S,setNodeRef:C,transform:j,transition:_,isDragging:k}=kS({id:e.id,disabled:o}),[E,T]=N.useState(!1),R=Ee(L=>L.card),{handleFieldClick:O}=WJ(R),{handleDevModeFieldClick:D,isNumberField:I}=YJ(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},z=()=>{if(s){const L={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};p&&g?(v({column:L,field:e}),x(!0)):d(L,"sheet",e)}else r?D(e):O(e)},V={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:Pi.Transform.toString(j),transition:_},H=(()=>{if(!n||s)return{};const A={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...A},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...A},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...A}}[n.state]||A})();return c.jsxs("div",{ref:C,style:$,...o?{}:w,...o?{}:S,className:K("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",H.borderColor||"border-transparent",H.bgColor||"",H.hoverBorderColor,H.hoverBgColor||"hover:bg-muted",H.opacity,H.cursor,p&&"border-accent-foreground/20 bg-accent",{"cursor-pointer":r||s,"cursor-grab active:cursor-grabbing":!o&&!r&&!s}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:z,children:[Jg(e.dataType),c.jsx(er,{children:c.jsxs(wn,{children:[c.jsx(Sn,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${E?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(En,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(hXe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(fXe,{column:V})})]}),E&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Mi,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(d8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(yie,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx($b,{open:b,onOpenChange:x,children:c.jsxs(ap,{children:[c.jsxs(lp,{children:[c.jsx(up,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(dp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(cp,{children:[c.jsx(hp,{children:"Cancel"}),c.jsx(fp,{onClick:F,children:"Remove Filter"})]})]})})]})}const mXe="SEMAPHOR_CALCULATED_FIELD",gXe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function ZJ(e){return!!e.expression}function bXe(e){return!!e.expression}function xXe(e){return!!e.expression}var KJ=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(KJ||{}),Al="Accordion",yXe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[bI,vXe,wXe]=t1(Al),[KS]=Er(Al,[wXe,LZ]),xI=LZ(),XJ=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(bI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(jXe,{...o,ref:t}):c.jsx(NXe,{...s,ref:t})})});XJ.displayName=Al;var[QJ,SXe]=KS(Al),[JJ,CXe]=KS(Al,{collapsible:!1}),NXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=Fr({prop:n,defaultProp:r,onChange:s});return c.jsx(QJ,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(JJ,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(eee,{...i,ref:t})})})}),jXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=Fr({prop:n,defaultProp:r,onChange:s}),l=N.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=N.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(QJ,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(JJ,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(eee,{...o,ref:t})})})}),[kXe,XS]=KS(Al),eee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=N.useRef(null),l=ft(a,t),u=vXe(n),f=$d(s)==="ltr",h=je(e.onKeyDown,p=>{var _;if(!yXe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var E;return!((E=k.ref.current)!=null&&E.disabled)}),b=g.findIndex(k=>k.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,S=()=>{y=b+1,y>w&&(y=v)},C=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():C());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?C():S());break;case"ArrowUp":o==="vertical"&&C();break}const j=y%x;(_=g[j].ref.current)==null||_.focus()});return c.jsx(kXe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(bI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Tw="AccordionItem",[EXe,yI]=KS(Tw),tee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=XS(Tw,n),i=SXe(Tw,n),a=xI(n),l=rr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(EXe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(VZ,{"data-orientation":o.orientation,"data-state":aee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});tee.displayName=Tw;var nee="AccordionHeader",ree=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=XS(Al,n),o=yI(nee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":aee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ree.displayName=nee;var n_="AccordionTrigger",see=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=XS(Al,n),o=yI(n_,n),i=CXe(n_,n),a=xI(n);return c.jsx(bI.ItemSlot,{scope:n,children:c.jsx(D4e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});see.displayName=n_;var oee="AccordionContent",iee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=XS(Al,n),o=yI(oee,n),i=xI(n);return c.jsx(T4e,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});iee.displayName=oee;function aee(e){return e?"open":"closed"}var _Xe=XJ,MXe=tee,DXe=ree,lee=see,cee=iee;const uee=_Xe,vI=M.forwardRef(({className:e,...t},n)=>c.jsx(MXe,{ref:n,className:K("border-b",e),...t}));vI.displayName="AccordionItem";const wI=M.forwardRef(({className:e,children:t,...n},r)=>c.jsx(DXe,{className:"flex",children:c.jsxs(lee,{ref:r,className:K("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,c.jsx(Ys,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));wI.displayName=lee.displayName;const SI=M.forwardRef(({className:e,children:t,...n},r)=>c.jsx(cee,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:K("pb-4 pt-0",e),children:t})}));SI.displayName=cee.displayName;function TXe({context:e="editor"}={}){var E,T,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");Ee(D=>D.isDevMode);const o=Ee(D=>D.card.dataSource),i=Ee(D=>D.card.config),a=Ee(D=>D.card),{autoJoinMetadata:l}=wa(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=hD(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=mI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(T=(E=i==null?void 0:i.joinPlan)==null?void 0:E.baseEntity)==null||T.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,YJ();const b=u.filter(D=>D.name.toLowerCase().includes(t.toLowerCase())||D.dataType.toLowerCase().includes(t.toLowerCase())||D.label&&D.label.toLowerCase().includes(t.toLowerCase())||D.qualifiedEntityName&&D.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=D=>{if(D.role==="metric"&&ZJ(D)||D.role==="groupby"&&D.expression)return"calculated";if(D.dataType==="number"||D.dataType==="integer"||D.dataType==="float"||D.dataType==="decimal"||D.dataType==="currency")return"metrics";const I=Ks(D.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(D=>x(D)===r)).reduce((D,I)=>{const F=I.qualifiedEntityName||"Other Fields";return D[F]||(D[F]={label:v_(I.entityName),fields:[]}),D[F].fields.push(I),D},{}),S=Object.keys(v),C=b.filter(D=>x(D)==="dimensions").length,j=b.filter(D=>x(D)==="metrics").length,_=b.filter(D=>x(D)==="calculated").length,k=b.length>0;return f?c.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:c.jsx(Tc,{size:"md",color:"muted","aria-label":"Loading data"})}):h?c.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[c.jsx(hl,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:h.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?c.jsx(Es,{className:"h-[calc(100vh-200px)] w-[290px]",children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx(hl,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:e==="filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]})}):c.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&c.jsxs("div",{className:"relative mb-4",children:[c.jsx(Ea,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Bn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:D=>n(D.target.value)}),t&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),k&&c.jsx(ls,{defaultValue:"all",value:r,onValueChange:D=>s(D),className:"mb-4",children:c.jsxs(Ur,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ut,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ut,{value:"dimensions",className:"text-xs",children:[c.jsx(Xw,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ut,{value:"metrics",className:"text-xs",children:[c.jsx(Zh,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ut,{value:"calculated",className:"text-xs",children:[c.jsx(D_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]})]})})]}),c.jsxs(_l,{className:"py-2",children:[c.jsx(uee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([D,I])=>{const F=d.find(z=>z.entityName===D)||{entityName:D,label:I.label};return c.jsxs(vI,{value:D,className:"border-none",children:[c.jsx(wI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:F.label||F.entityName,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:F.label||F.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx(SI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const V=pD(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(pXe,{field:z,context:e,fieldState:V},z.id)})})})]},D)})}),Object.keys(v).length===0&&u.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(v).length===0&&u.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Ko,{orientation:"horizontal"}),c.jsx(Ko,{orientation:"vertical"})]})]})}function dee({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(TXe,{context:e})," "]})}function fee(){const e=Ee(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=cr();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=gI(e),d=(p=e.selectedEntities)==null?void 0:p[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function RXe(){fee();const e=J(l=>l.selectedSheetId),t=J(l=>l.selectedFrameId),n=J(l=>l.dashboard),r=J(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Gt(),{setCard:o}=cr(),i=Ee(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function IXe(){const e=J(n=>n.actions.setShowFilters),{hasEntities:t}=RXe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(FZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(hl,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow",children:c.jsx(NS,{collisionDetection:vS,children:c.jsx(jS,{items:[],strategy:vR,children:c.jsx(dee,{context:"filter"})})})})]})}function AXe(){const e=J(r=>r.dashboard.filters),t=J(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:K("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(aR,{filter:r}),c.jsx(gS,{filter:r})]},r.id))}):null}function PXe(){const e=J(r=>r.showFilters),t=J(r=>r.isVisualEditing),n=J(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:K("",{"max-h-0 overflow-hidden":t,"flex grow overflow-auto":!t}),children:[c.jsxs("section",{className:"flex grow flex-col",children:[n&&c.jsx(AXe,{}),c.jsx(zJ,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex",children:c.jsx(IXe,{})})]})}const OXe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-B69rp7Eg.js"))),FXe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-CRvSRhC4.js"))),$Xe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BJ1c04y3.js"))),LXe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-DToljP14.js")).then(e=>({default:e.ResourceManagementPanel})));function zXe({showControls:e=!1,showFooter:t=!0,...n}){const r=J(m=>m.isDashboardPanelOpen),s=J(m=>m.isVisualEditing),o=J(m=>m.showDashboardJSON),i=J(m=>m.actions.setIsDashboardPanelOpen),a=20,l=20,u=30,d=r,f=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{f.current&&h.current&&(r?(f.current.resize(a),h.current.resize(100-a)):(f.current.resize(0),h.current.resize(100)))},[r]);const{preferences:p}=n;return c.jsx(Dl,{FallbackComponent:iS,children:c.jsxs(E_,{dashboardProps:n,children:[c.jsx(Xue,{}),c.jsx(pI,{children:c.jsxs(BJ,{preferences:p,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx($Xe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(OXe,{})}),c.jsxs(TR,{direction:"horizontal",className:"flex grow overflow-hidden",children:[c.jsx(ib,{ref:f,className:K("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?a:0,minSize:d?l:0,maxSize:d?u:0,children:d&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(LXe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})})}),c.jsx(tX,{className:K("",{"w-0":!d})}),c.jsx(ib,{ref:h,className:"flex min-w-0 flex-1",defaultSize:d?100-a:100,minSize:d?40:100,children:c.jsxs(TD,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(FXe,{})}),c.jsx(PXe,{})]})})]})]})]})})]})})}var BXe=Object.defineProperty,VXe=(e,t,n)=>t in e?BXe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,uy=(e,t,n)=>VXe(e,typeof t!="symbol"?t+"":t,n);const HXe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},UXe={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},WXe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},qXe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},YXe={stringify:e=>e,parse:e=>e},W2={string:YXe,number:qXe,boolean:HXe,function:UXe,json:WXe};function GXe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const dy=Symbol.for("r2wc.render"),fy=Symbol.for("r2wc.connected"),gu=Symbol.for("r2wc.context"),za=Symbol.for("r2wc.props");function ZXe(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=GXe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),uy(this,o,!0),uy(this,s),uy(this,r,{}),uy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[za].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?W2[x]:null;y!=null&&y.parse&&b&&(this[za][m]=y.parse(b,g,this))}for(const m of a)this[za][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[fy]=!0,this[dy]()}disconnectedCallback(){this[fy]=!1,this[gu]&&n.unmount(this[gu]),delete this[gu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?W2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[za][x]=v.parse(b,m,this),this[dy]())}[(o=fy,s=gu,r=za,dy)](){this[fy]&&(this[gu]?n.update(this[gu],this[za]):this[gu]=n.mount(this.container,e,this[za]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[za][p]},set(b){this[za][p]=b;const x=g?W2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[dy]()}})}return h}function KXe(e,t,n){const r=sj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function XXe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function QXe({root:e}){e.unmount()}function JXe(e,t={}){return ZXe(e,t,{mount:KXe,update:XXe,unmount:QXe})}const eQe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},tQe=JXe(VJ,{props:eQe});function nQe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function eL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function tL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?eL(Object(n),!0).forEach(function(r){nQe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):eL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function rQe(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function sQe(e,t){if(e==null)return{};var n=rQe(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function oQe(e,t){return iQe(e)||aQe(e,t)||lQe(e,t)||cQe()}function iQe(e){if(Array.isArray(e))return e}function aQe(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function lQe(e,t){if(e){if(typeof e=="string")return nL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return nL(e,t)}}function nL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function cQe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
1067
1067
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function uQe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function sL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?rL(Object(n),!0).forEach(function(r){uQe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):rL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function dQe(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(s,o){return o(s)},r)}}function zm(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function Rw(e){return{}.toString.call(e).includes("Object")}function fQe(e){return!Object.keys(e).length}function gb(e){return typeof e=="function"}function hQe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pQe(e,t){return Rw(t)||xc("changeType"),Object.keys(t).some(function(n){return!hQe(e,n)})&&xc("changeField"),t}function mQe(e){gb(e)||xc("selectorType")}function gQe(e){gb(e)||Rw(e)||xc("handlerType"),Rw(e)&&Object.values(e).some(function(t){return!gb(t)})&&xc("handlersType")}function bQe(e){e||xc("initialIsRequired"),Rw(e)||xc("initialType"),fQe(e)&&xc("initialContent")}function xQe(e,t){throw new Error(e[t]||e.default)}var yQe={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},xc=zm(xQe)(yQe),hy={changes:pQe,selector:mQe,handler:gQe,initial:bQe};function vQe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};hy.initial(e),hy.handler(t);var n={current:e},r=zm(CQe)(n,t),s=zm(SQe)(n),o=zm(hy.changes)(e),i=zm(wQe)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return hy.selector(u),u(n.current)}function l(u){dQe(r,s,o,i)(u)}return[a,l]}function wQe(e,t){return gb(t)?t(e.current):t}function SQe(e,t){return e.current=sL(sL({},e.current),t),t}function CQe(e,t,n){return gb(t)?t(e.current):Object.keys(n).forEach(function(r){var s;return(s=t[r])===null||s===void 0?void 0:s.call(t,e.current[r])}),n}var NQe={create:vQe},jQe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function kQe(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function EQe(e){return{}.toString.call(e).includes("Object")}function _Qe(e){return e||oL("configIsRequired"),EQe(e)||oL("configType"),e.urls?(MQe(),{paths:{vs:e.urls.monacoBase}}):e}function MQe(){console.warn(hee.deprecation)}function DQe(e,t){throw new Error(e[t]||e.default)}var hee={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
1068
1068
  You are using deprecated way of configuration.
1069
1069
 
@@ -112369,10 +112369,10 @@ function wXe() {
112369
112369
  }
112370
112370
  );
112371
112371
  }
112372
- const SXe = Lw(() => import("./dashboard-controls-BOWrupBW.js")), CXe = Lw(
112373
- () => import("./edit-dashboard-visual-D7Ic8u1b.js")
112374
- ), NXe = Lw(() => import("./dashboard-json-BHLhFEdC.js")), kXe = Lw(
112375
- () => import("./resource-management-panel-DpASGkNn.js").then(
112372
+ const SXe = Lw(() => import("./dashboard-controls-BcI9OPvx.js")), CXe = Lw(
112373
+ () => import("./edit-dashboard-visual-C2PPgPSf.js")
112374
+ ), NXe = Lw(() => import("./dashboard-json-DsxHtR1h.js")), kXe = Lw(
112375
+ () => import("./resource-management-panel-k_ZQIBfh.js").then(
112376
112376
  (e) => ({ default: e.ResourceManagementPanel })
112377
112377
  )
112378
112378
  );
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-DUJ50AjE.js"),m=require("react"),ae=require("./use-visual-utils-CFuV8lsO.js"),le=require("./use-click-outside-B9T3lmcw.js");/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-BYjv54tY.js"),m=require("react"),ae=require("./use-visual-utils-CMaqO2nT.js"),le=require("./use-click-outside-B9T3lmcw.js");/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -1,7 +1,7 @@
1
1
  import { jsx as e, jsxs as t, Fragment as ve } from "react/jsx-runtime";
2
- import { b as Ce, aM as pe, u as de, aa as Ge, ak as J, aN as Ke, aO as We, aP as ye, c as q, aQ as Se, aR as ce, B as j, aS as xe, aC as Ye, aD as qe, aT as Qe, aF as Xe, aG as G, aU as ue, ac as k, aV as Ze, aW as be, aX as fe, aY as $e, aZ as Je, I as ke, a_ as Ve, a$ as ee, b0 as Ee, b1 as et, v as Le, R as Te, b2 as Oe, b3 as Ae, b4 as Pe, b5 as Ue, b6 as Re, b7 as Ie, b8 as Me, b9 as je, ba as Fe, bb as tt, bc as st, bd as at, aA as $, aj as nt, be as it, bf as ze, bg as rt, ao as ot, ap as lt, aq as dt, ar as ct, as as ut, at as we, au as he, ax as ht, bh as mt, bi as pt, bj as ft, bk as gt, bl as Dt, bm as Nt, bn as xt, bo as bt } from "./index-CGyjzIO0.js";
2
+ import { b as Ce, aM as pe, u as de, aa as Ge, ak as J, aN as Ke, aO as We, aP as ye, c as q, aQ as Se, aR as ce, B as j, aS as xe, aC as Ye, aD as qe, aT as Qe, aF as Xe, aG as G, aU as ue, ac as k, aV as Ze, aW as be, aX as fe, aY as $e, aZ as Je, I as ke, a_ as Ve, a$ as ee, b0 as Ee, b1 as et, v as Le, R as Te, b2 as Oe, b3 as Ae, b4 as Pe, b5 as Ue, b6 as Re, b7 as Ie, b8 as Me, b9 as je, ba as Fe, bb as tt, bc as st, bd as at, aA as $, aj as nt, be as it, bf as ze, bg as rt, ao as ot, ap as lt, aq as dt, ar as ct, as as ut, at as we, au as he, ax as ht, bh as mt, bi as pt, bj as ft, bk as gt, bl as Dt, bm as Nt, bn as xt, bo as bt } from "./index-DLEb3N-R.js";
3
3
  import wt, { useState as D, useEffect as me } from "react";
4
- import { a as Be } from "./use-visual-utils-CfCFNHJ6.js";
4
+ import { a as Be } from "./use-visual-utils-Btxew3Er.js";
5
5
  import { u as vt } from "./use-click-outside-CMeO_QFI.js";
6
6
  /**
7
7
  * @license lucide-react v0.453.0 - ISC
@@ -1,8 +1,8 @@
1
1
  import { jsx as e, jsxs as r, Fragment as E } from "react/jsx-runtime";
2
- import { b as W, ao as _, ap as $, aq as G, ar as J, as as K, at as M, au as R, av as X, aw as T, ax as Q, B as k, ac as Y, aa as N, ae as Z, u as g, ak as ee, a8 as q, ay as ae, az as B, ah as w, aA as se, aB as te, c as y, aC as O, aD as P, aE as L, aF as z, aG as j, ab as ne, aH as de, aI as le, aJ as re, I as ie, aK as oe, aL as ce } from "./index-CGyjzIO0.js";
3
- import { E as he, V as ue, a as me, b as ve, S as U, c as pe } from "./editor-action-buttons-DpbEl7Rx.js";
2
+ import { b as W, ao as _, ap as $, aq as G, ar as J, as as K, at as M, au as R, av as X, aw as T, ax as Q, B as k, ac as Y, aa as N, ae as Z, u as g, ak as ee, a8 as q, ay as ae, az as B, ah as w, aA as se, aB as te, c as y, aC as O, aD as P, aE as L, aF as z, aG as j, ab as ne, aH as de, aI as le, aJ as re, I as ie, aK as oe, aL as ce } from "./index-DLEb3N-R.js";
3
+ import { E as he, V as ue, a as me, b as ve, S as U, c as pe } from "./editor-action-buttons-D74G-fOO.js";
4
4
  import fe, { useState as C, useContext as be } from "react";
5
- import { a as H } from "./use-visual-utils-CfCFNHJ6.js";
5
+ import { a as H } from "./use-visual-utils-Btxew3Er.js";
6
6
  /**
7
7
  * @license lucide-react v0.453.0 - ISC
8
8
  *
@@ -144,7 +144,7 @@ function Ce() {
144
144
  (l) => l.actions.setIsDashboardPanelOpen
145
145
  ), { getUpdatedFrame: D } = H(), { selectVisual: b } = ee(), { addFrame: S, setSelectedFrameId: I, setIsVisualEditing: A } = q(), m = !!(i != null && i.visualId), F = (() => {
146
146
  var l, p;
147
- return c != null && c.title ? c.title : ((l = i == null ? void 0 : i.cards) == null ? void 0 : l.length) === 1 && ((p = i.cards[0]) != null && p.title) ? i.cards[0].title : (n == null ? void 0 : n.title) || "Untitled Visual";
147
+ return ((l = i == null ? void 0 : i.cards) == null ? void 0 : l.length) === 1 && ((p = i.cards[0]) != null && p.title) ? i.cards[0].title : c != null && c.title ? c.title : (n == null ? void 0 : n.title) || "Untitled Visual";
148
148
  })(), h = ae((l) => {
149
149
  if (l != null && l.id) {
150
150
  if (b(l), s && o && v) {
@@ -0,0 +1,6 @@
1
+ "use strict";const s=require("react/jsx-runtime"),e=require("./index-BYjv54tY.js"),f=require("./editor-action-buttons-18dPoIIF.js"),p=require("react"),y=require("./use-visual-utils-CMaqO2nT.js");/**
2
+ * @license lucide-react v0.453.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const k=e.createLucideIcon("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);function F({open:a,onOpenChange:r,isLibraryVisual:t,currentVisualName:n,isSaving:l=!1,onConfirm:h}){const[i,d]=p.useState(t&&n?`Copy of ${n}`:n||""),[c,v]=p.useState(""),[b,D]=p.useState(!t),[j,S]=p.useState(!0);p.useEffect(()=>{a&&(d(t&&n?`Copy of ${n}`:n||""),v(""),D(!t),S(!0))},[a,t,n]);const C=()=>{i.trim()&&(!b&&!j||h({name:i.trim(),description:c.trim()||void 0,saveToLibrary:b,saveToCurrentDashboard:j}))},g=i.trim()&&(b||j);return s.jsx(e.Dialog,{open:a,onOpenChange:r,children:s.jsxs(e.DialogContent,{className:"sm:max-w-[425px]",children:[s.jsxs(e.DialogHeader,{children:[s.jsx(e.DialogTitle,{children:"Save Visual As"}),s.jsx(e.DialogDescription,{children:t?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),s.jsxs("div",{className:"grid gap-4 py-4",children:[s.jsxs("div",{className:"grid gap-2",children:[s.jsx(e.Label,{htmlFor:"name",children:"Name"}),s.jsx(e.Input,{id:"name",value:i,onChange:m=>d(m.target.value),placeholder:"Enter visual name",disabled:l})]}),s.jsxs("div",{className:"grid gap-2",children:[s.jsx(e.Label,{htmlFor:"description",children:"Description (optional)"}),s.jsx(e.Textarea,{id:"description",value:c,onChange:m=>v(m.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsx(e.Label,{children:"Save to:"}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(e.Checkbox,{id:"save-to-dashboard",checked:j,onCheckedChange:m=>S(!!m),disabled:l}),s.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",s.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:t?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(e.Checkbox,{id:"save-to-library",checked:b,onCheckedChange:m=>D(!!m),disabled:l}),s.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",s.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:t?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!b&&!j&&s.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),s.jsxs(e.DialogFooter,{children:[s.jsx(e.Button,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancel"}),s.jsxs(e.Button,{onClick:C,disabled:!g||l,children:[l&&s.jsx(e.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function N(){const[a,r]=p.useState(!1),[t,n]=p.useState(!1),[l,h]=p.useState(null),i=e.useEditorStore(o=>o.frame),d=e.useEditorStore(o=>o.card),c=e.useSelectedVisual(),v=e.useDashboardStore(o=>o.selectedSheetId),b=e.useDashboardStore(o=>o.actions.setIsDashboardPanelOpen),{getUpdatedFrame:D}=y.useVisualUtils(),{selectVisual:j}=e.useManagementActions(),{addFrame:S,setSelectedFrameId:C,setIsVisualEditing:g}=e.useDashboardActions(),m=!!(i!=null&&i.visualId),w=(()=>{var o,x;return((o=i==null?void 0:i.cards)==null?void 0:o.length)===1&&((x=i.cards[0])!=null&&x.title)?i.cards[0].title:c!=null&&c.title?c.title:(d==null?void 0:d.title)||"Untitled Visual"})(),u=e.useCreateVisualWithFrame(o=>{if(o!=null&&o.id){if(j(o),t&&l&&v){const x={...l,id:e.v4(),visualId:o.id};S(v,x,"end"),C(x.id),n(!1),h(null),g(!1)}b(!0),r(!1)}});return{saveAsDialogOpen:a,setSaveAsDialogOpen:r,handleSaveAs:async o=>{if(!v){e.ue.error("No sheet selected");return}const x=D(),I=x.cards.length===1?{...x,cards:x.cards.map(A=>({...A,title:o.name}))}:x;if(o.saveToLibrary){n(o.saveToCurrentDashboard),h(I);const A={title:o.name,description:o.description,frameObject:I,isPrivate:!1};u.mutate(A)}else if(o.saveToCurrentDashboard){const A={...I,id:e.v4(),visualId:void 0};S(v,A,"end"),C(A.id),e.ue.success("Visual saved to dashboard"),r(!1),g(!1)}},isLibraryVisual:m,currentVisualName:w,isSaving:u.isPending}}function V({className:a}){const r=e.useEditorStore(u=>u.frame),t=e.useEditorStore(u=>u.card),n=e.useManagementStore(u=>u.selectedVisual),l=e.useDashboardStore(u=>u.selectedFrameId),h=e.useDashboardStore(u=>u.selectedSheetId),{setIsVisualEditing:i}=e.useDashboardActions(),d=!!(r!=null&&r.visualId||n!=null&&n.id),c=!!(r!=null&&r.visualId&&l),v=d&&!c,{saveAsDialogOpen:b,setSaveAsDialogOpen:D,handleSaveAs:j,isLibraryVisual:S,currentVisualName:C,isSaving:g}=N(),{handleAddLibraryVisual:m}=y.useVisualUtils(),w=async()=>{if(!h){e.ue.error("No dashboard sheet selected");return}if(!n){e.ue.error("No visual selected");return}const u=await m(n);u.success?(e.ue.success("Visual added to dashboard"),i(!1)):e.ue.error(u.error||"Failed to add visual to dashboard")};return s.jsxs(s.Fragment,{children:[!d&&s.jsx(f.EditorAcceptButton,{className:a,variant:"default"}),d&&s.jsxs(s.Fragment,{children:[c&&s.jsx(f.VisualApplyLocalButton,{className:a}),v&&h&&t&&(t.sql||e.hasValidCardConfig(t.config))&&s.jsxs(e.Button,{onClick:w,className:e.cn(a),size:"sm",variant:"outline",children:[s.jsx(k,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),v&&s.jsx(f.VisualSaveButton,{className:a,variant:"default"}),c&&s.jsx(f.VisualSaveAndApplyButton,{className:a}),s.jsxs(e.DropdownMenu,{modal:!1,children:[s.jsx(e.DropdownMenuTrigger,{asChild:!0,children:s.jsx(e.Button,{variant:"outline",size:"sm",className:e.cn(a,"w-8 p-0"),children:s.jsx(e.EllipsisVertical,{className:"h-4 w-4"})})}),s.jsx(e.DropdownMenuContent,{align:"end",children:s.jsxs(e.DropdownMenuItem,{onClick:u=>{u.stopPropagation(),D(!0)},children:[s.jsx(f.Save,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!d&&s.jsxs(e.DropdownMenu,{modal:!1,children:[s.jsx(e.DropdownMenuTrigger,{asChild:!0,children:s.jsx(e.Button,{variant:"outline",size:"sm",className:e.cn(a,"w-8 p-0"),children:s.jsx(e.EllipsisVertical,{className:"h-4 w-4"})})}),s.jsx(e.DropdownMenuContent,{align:"end",children:s.jsxs(e.DropdownMenuItem,{onClick:()=>D(!0),children:[s.jsx(f.Save,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),s.jsx(f.EditorCancelButton,{className:a}),s.jsx(F,{open:b,onOpenChange:u=>{g||D(u)},isLibraryVisual:S,currentVisualName:C,isSaving:g,onConfirm:j})]})}function E({className:a,switchClassName:r}){const t=e.useEditorStore(d=>d.isDevMode),n=e.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:l}=e.useEditorActions(),{config:h}=p.useContext(e.SemaphorContext).tokenProps,i=(h==null?void 0:h.showAdvancedMode)!==!1;return!n||!i?null:s.jsxs("div",{className:e.cn("flex items-center space-x-2",a),children:[s.jsx(e.DevModeSwitch,{className:e.cn("",r),checked:t,onCheckedChange:()=>l(!t),id:"advanced-mode",icon:s.jsx(e.CodeXml,{className:"h-4 w-4"}),tooltip:t?"Standard Mode":"Advanced Mode"}),s.jsx("label",{htmlFor:"advanced-mode",className:"sr-only",children:"Advanced Mode"})]})}function T(a){var r;return{...a,sheets:(r=a==null?void 0:a.sheets)==null?void 0:r.map(t=>{var n;return{...t,frames:(n=t.frames)==null?void 0:n.map(l=>{var h;return{...l,cards:(h=l.cards)==null?void 0:h.map(i=>M(i))}})}})}}function M(a){return{...a,customCfg:B(a.customCfg),data:[]}}function B(a){var r,t;return a?{...a,data:{...a==null?void 0:a.data,labels:[],datasets:(t=(r=a==null?void 0:a.data)==null?void 0:r.datasets)==null?void 0:t.map(n=>({...n,data:[]}))}}:null}function O({triggerButtonClassName:a}){const[r,t]=p.useState(!1),n=e.useDashboardStore(d=>{var c;return(c=d.dashboard)==null?void 0:c.id}),l=e.useDashboardStore(d=>{var c;return(c=d.dashboard)==null?void 0:c.title}),h=e.useDashboardStore(d=>{var c;return(c=d.dashboard)==null?void 0:c.sheets}),i=e.useDashboardStore(d=>d.selectedSheetId);return h==null||h.find(d=>d.id===i),n?s.jsxs(s.Fragment,{children:[s.jsx(e.IconButton,{tooltip:"Schedule Dashboard",className:e.cn("h-7 p-2",a),onClick:()=>t(!0),children:s.jsx(e.Clock,{className:"size-4"})}),s.jsx(e.EmailScheduleDialog,{open:r,onOpenChange:t,dashboardId:n,dashboardName:l})]}):null}exports.AdvancedModeToggle=E;exports.ScheduleDashboard=O;exports.VisualEditingControls=V;exports.cleanCard=M;exports.getDashbaordStateWithoutData=T;
@@ -1,4 +1,4 @@
1
- import { ai as G, aj as z, ad as Y, ae as J, ak as K, ab as _, a8 as X, u as U, al as Z, am as q, ah as v, an as ee, aa as h } from "./index-CGyjzIO0.js";
1
+ import { ai as G, aj as z, ad as Y, ae as J, ak as K, ab as _, a8 as X, u as U, al as Z, am as q, ah as v, an as ee, aa as h } from "./index-DLEb3N-R.js";
2
2
  import { useState as T, useEffect as te, useCallback as V } from "react";
3
3
  function re(e) {
4
4
  const a = e.toUpperCase().indexOf("WHERE"), r = e.toUpperCase().indexOf("GROUP BY"), t = e.toUpperCase().indexOf("LIMIT"), i = e.toUpperCase().indexOf("ORDER BY");
@@ -1 +1 @@
1
- "use strict";const o=require("./index-DUJ50AjE.js"),b=require("react");function _(e){const a=e.toUpperCase().indexOf("WHERE"),r=e.toUpperCase().indexOf("GROUP BY"),t=e.toUpperCase().indexOf("LIMIT"),d=e.toUpperCase().indexOf("ORDER BY");let c=e.length;if(d!==-1&&(c=d),t!==-1&&t<c&&(c=t),a!==-1){const n=e.substring(0,a),s=e.substring(a);return`${n} {{ filters | where }} AND ${s.substring(6)}`}else if(r!==-1){const n=e.substring(0,r),s=e.substring(r);return`${n} {{ filters | where }} ${s}`}else{const n=e.substring(0,c),s=e.substring(c);return console.log("beforeClause",n),console.log("afterClause",s),s?`${n} {{ filters | where }} ${s}`:`${n.replace(/;$/,"")} {{ filters | where }}`}}function B(e){const[a,r]=b.useState(null),[t,d]=b.useState(null),c=o.useEnsureReactGlobals();return b.useEffect(()=>{if(!e||e.trim()===""){r(null),d(null);return}if(!c)return;(async()=>{try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error(`Invalid URL format: ${e}`);try{new URL(e)}catch{throw new Error(`Invalid URL: ${e}`)}const l=`${e.endsWith("/")?e:`${e}/`}index.js`;try{if(!(await fetch(l,{method:"HEAD"})).ok)throw new Error(`Module not found at ${l}`)}catch{}const m=await import(l);if(typeof m.useChartStore!="function")throw new Error("useChartStore is not a function");r(()=>m.useChartStore),d(null)}catch(s){const l=s instanceof Error?s.message:"Unknown error";console.error("Failed to load remote chart store:",l),d(l),r(null)}})()},[e,c]),a}function H(e,a){if(e.length===0)return"";if(a){const r=e.find(t=>t.id===a);if(r){const t=r.tabTitle;if(t=="All__Header")return e[0].id;if(t&&t.endsWith("__Header")){const c=t.split("__")[0],n=e.find(s=>s.tabTitle===c);return n?n.id:e[0].id}return a}}return e[0].id}async function j(e,a,r,t){if(!a||!r)throw new Error("Missing auth token or visual ID");const d=["resource-by-id","visual",r],c=t.getQueryData(d);if(c)return console.log("Using cached visual data for:",r),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",r);const n=o.ue.loading("Loading visual...",{position:"top-center"});try{const s=await fetch(`${e}/management/v1/visuals/${r}`,{headers:{Authorization:`Bearer ${a}`}});if(!s.ok)throw new Error("Failed to load visual");const l=await s.json();return t.setQueryData(d,l),o.ue.dismiss(n),{data:l,fromCache:!1}}catch(s){throw o.ue.dismiss(n),s}}function T(e){if(typeof e=="string")return JSON.parse(e);if(typeof e=="object")return e;throw new Error("Invalid frame object format")}function Q(e,a){var c,n;const r=(e==null?void 0:e.frameObject)??((c=e==null?void 0:e.visual)==null?void 0:c.frameObject);if(!r)return!1;const t=T(r);if(!(t!=null&&t.cards)||t.cards.length===0)return!1;const d=(n=t.cards)==null?void 0:n.find(s=>s.id===t.activeCardId);return d?(o.setupEditorWithCard({...a,frame:t,card:d,visualId:(e==null?void 0:e.id)||t.visualId}),!0):!1}function G(){var g;const{setCardSql:e}=o.useEditorActions(),a=o.useEditorStore(i=>i.frame),r=o.useEditorStore(i=>i.card),t=B(((g=r.customCardPreferences)==null?void 0:g.url)||""),d=o.useEditorStore(i=>i.selectedSchemaName),c=o.useEditorStore(i=>i.selectedDatamodelId),n=o.useEditorStore(i=>i.selectedDatabaseName),s=o.useEditorStore(i=>i.selectedTableName),l=o.useEditorStore(i=>i.selectedConnectionId),m=o.useEditorStore(i=>i.isShowingVisual),f=r.sql;return{getUpdatedFrame:b.useCallback(()=>{var E;let i=f;f&&!f.includes("{{")&&(i=_(f),e(i));const C=(E=t==null?void 0:t.getState())==null?void 0:E.settings,U={...r,dataSource:r.dataSource||{mode:"directSource"},lastSelectedSchema:d,lastSelectedDatamodelId:c,lastSelectedDatabase:n,lastSelectedTable:s,connectionId:l,sql:i,customCfg:m?r.customCfg:null,preferences:r.preferences,...C&&{customCardPreferences:{...r.customCardPreferences,settings:C}}},w=a.cards.map(S=>S.id===r.id?U:S);return{...a,cards:w,activeCardId:H(w,a.activeCardId)}},[r,a,m,d,c,n,s,l,e,t,f])}}function z(){const{authToken:e,tokenProps:a}=o.useSemaphorContext(),r=o.useQueryClient(),t=o.useSelectedVisual(),{selectVisual:d}=o.useManagementActions(),{setFrame:c,setCard:n,setIsDevMode:s,setActiveTabCardId:l,updateDataSource:m,setQueryResultColumns:f,setSelectedConnectionId:V,setSelectedDatabaseName:g,setSelectedSchemaName:i,setSelectedTableName:C,setSelectedDatamodelId:U,setFilterValues:w,setApplyFilters:E}=o.useEditorActions(),{setIsDashboardEditing:S,setIsVisualEditing:$,setSelectedFrameId:v,clearSelectedFrameId:A,addFrame:N,setIsDashboardPanelOpen:R}=o.useDashboardActions(),I=o.useDashboardStore(u=>u.selectedSheetId),D=o.useDashboardStore(u=>u.selectedFrameId),O=o.useDashboardStore(u=>u.dashboard),x=o.useDashboardStore(u=>u.filterValues),y=o.useVisualById((t==null?void 0:t.id)||"",{enabled:!!(t!=null&&t.id)&&!!(e!=null&&e.accessToken)}),M=b.useCallback(async u=>{try{d(u),A();const{data:p,fromCache:h}=await j(a.apiServiceUrl,(e==null?void 0:e.accessToken)||"",u.id,r);if(!Q(p,{setFrame:c,setCard:n,setIsDevMode:s,setActiveTabCardId:l,updateDataSource:m,setQueryResultColumns:f,setSelectedConnectionId:V,setSelectedDatabaseName:g,setSelectedSchemaName:i,setSelectedTableName:C,setSelectedDatamodelId:U,setFilterValues:w,setApplyFilters:E,setIsDashboardEditing:S,setIsVisualEditing:$,dashboard:O,selectedSheetId:I,selectedFrameId:D,filterValues:x}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:h}}catch(p){return console.error("Error editing visual:",p),{success:!1,error:"Failed to load visual for editing"}}},[e==null?void 0:e.accessToken,a.apiServiceUrl,r,d,c,n,S,$,s,l,m,f,V,g,i,C,U,w,E,A,O,I,D,x]),k=b.useCallback(async u=>{var p;try{if(d(u),!I)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:h,fromCache:W}=await j(a.apiServiceUrl,(e==null?void 0:e.accessToken)||"",u.id,r),L=(h==null?void 0:h.frameObject)??((p=h==null?void 0:h.visual)==null?void 0:p.frameObject);if(!L)return{success:!1,error:"Visual has no frame data"};const F=T(L);if(!(F!=null&&F.cards)||F.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const P={...o.cloneFrameWithNewIds(F),visualId:u.id};return N(I,P,"end"),S(!0),v(P.id),R(!1),{success:!0,fromCache:W}}catch(h){return console.error("Error adding visual:",h),{success:!1,error:"Failed to add visual to dashboard"}}},[e==null?void 0:e.accessToken,a.apiServiceUrl,r,d,I,N,S,v,R]);return{visual:y.data,isLoading:y.isLoading,isError:y.isError,error:y.error,handleEditLibraryVisual:M,handleAddLibraryVisual:k,getUpdatedFrame:G().getUpdatedFrame,refetch:y.refetch}}exports.useRemoteChartStore=B;exports.useVisualUtils=z;
1
+ "use strict";const o=require("./index-BYjv54tY.js"),b=require("react");function _(e){const a=e.toUpperCase().indexOf("WHERE"),r=e.toUpperCase().indexOf("GROUP BY"),t=e.toUpperCase().indexOf("LIMIT"),d=e.toUpperCase().indexOf("ORDER BY");let c=e.length;if(d!==-1&&(c=d),t!==-1&&t<c&&(c=t),a!==-1){const n=e.substring(0,a),s=e.substring(a);return`${n} {{ filters | where }} AND ${s.substring(6)}`}else if(r!==-1){const n=e.substring(0,r),s=e.substring(r);return`${n} {{ filters | where }} ${s}`}else{const n=e.substring(0,c),s=e.substring(c);return console.log("beforeClause",n),console.log("afterClause",s),s?`${n} {{ filters | where }} ${s}`:`${n.replace(/;$/,"")} {{ filters | where }}`}}function B(e){const[a,r]=b.useState(null),[t,d]=b.useState(null),c=o.useEnsureReactGlobals();return b.useEffect(()=>{if(!e||e.trim()===""){r(null),d(null);return}if(!c)return;(async()=>{try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error(`Invalid URL format: ${e}`);try{new URL(e)}catch{throw new Error(`Invalid URL: ${e}`)}const l=`${e.endsWith("/")?e:`${e}/`}index.js`;try{if(!(await fetch(l,{method:"HEAD"})).ok)throw new Error(`Module not found at ${l}`)}catch{}const m=await import(l);if(typeof m.useChartStore!="function")throw new Error("useChartStore is not a function");r(()=>m.useChartStore),d(null)}catch(s){const l=s instanceof Error?s.message:"Unknown error";console.error("Failed to load remote chart store:",l),d(l),r(null)}})()},[e,c]),a}function H(e,a){if(e.length===0)return"";if(a){const r=e.find(t=>t.id===a);if(r){const t=r.tabTitle;if(t=="All__Header")return e[0].id;if(t&&t.endsWith("__Header")){const c=t.split("__")[0],n=e.find(s=>s.tabTitle===c);return n?n.id:e[0].id}return a}}return e[0].id}async function j(e,a,r,t){if(!a||!r)throw new Error("Missing auth token or visual ID");const d=["resource-by-id","visual",r],c=t.getQueryData(d);if(c)return console.log("Using cached visual data for:",r),{data:c,fromCache:!0};console.log("Fetching visual data from network for:",r);const n=o.ue.loading("Loading visual...",{position:"top-center"});try{const s=await fetch(`${e}/management/v1/visuals/${r}`,{headers:{Authorization:`Bearer ${a}`}});if(!s.ok)throw new Error("Failed to load visual");const l=await s.json();return t.setQueryData(d,l),o.ue.dismiss(n),{data:l,fromCache:!1}}catch(s){throw o.ue.dismiss(n),s}}function T(e){if(typeof e=="string")return JSON.parse(e);if(typeof e=="object")return e;throw new Error("Invalid frame object format")}function Q(e,a){var c,n;const r=(e==null?void 0:e.frameObject)??((c=e==null?void 0:e.visual)==null?void 0:c.frameObject);if(!r)return!1;const t=T(r);if(!(t!=null&&t.cards)||t.cards.length===0)return!1;const d=(n=t.cards)==null?void 0:n.find(s=>s.id===t.activeCardId);return d?(o.setupEditorWithCard({...a,frame:t,card:d,visualId:(e==null?void 0:e.id)||t.visualId}),!0):!1}function G(){var g;const{setCardSql:e}=o.useEditorActions(),a=o.useEditorStore(i=>i.frame),r=o.useEditorStore(i=>i.card),t=B(((g=r.customCardPreferences)==null?void 0:g.url)||""),d=o.useEditorStore(i=>i.selectedSchemaName),c=o.useEditorStore(i=>i.selectedDatamodelId),n=o.useEditorStore(i=>i.selectedDatabaseName),s=o.useEditorStore(i=>i.selectedTableName),l=o.useEditorStore(i=>i.selectedConnectionId),m=o.useEditorStore(i=>i.isShowingVisual),f=r.sql;return{getUpdatedFrame:b.useCallback(()=>{var E;let i=f;f&&!f.includes("{{")&&(i=_(f),e(i));const C=(E=t==null?void 0:t.getState())==null?void 0:E.settings,U={...r,dataSource:r.dataSource||{mode:"directSource"},lastSelectedSchema:d,lastSelectedDatamodelId:c,lastSelectedDatabase:n,lastSelectedTable:s,connectionId:l,sql:i,customCfg:m?r.customCfg:null,preferences:r.preferences,...C&&{customCardPreferences:{...r.customCardPreferences,settings:C}}},w=a.cards.map(S=>S.id===r.id?U:S);return{...a,cards:w,activeCardId:H(w,a.activeCardId)}},[r,a,m,d,c,n,s,l,e,t,f])}}function z(){const{authToken:e,tokenProps:a}=o.useSemaphorContext(),r=o.useQueryClient(),t=o.useSelectedVisual(),{selectVisual:d}=o.useManagementActions(),{setFrame:c,setCard:n,setIsDevMode:s,setActiveTabCardId:l,updateDataSource:m,setQueryResultColumns:f,setSelectedConnectionId:V,setSelectedDatabaseName:g,setSelectedSchemaName:i,setSelectedTableName:C,setSelectedDatamodelId:U,setFilterValues:w,setApplyFilters:E}=o.useEditorActions(),{setIsDashboardEditing:S,setIsVisualEditing:$,setSelectedFrameId:v,clearSelectedFrameId:A,addFrame:N,setIsDashboardPanelOpen:R}=o.useDashboardActions(),I=o.useDashboardStore(u=>u.selectedSheetId),D=o.useDashboardStore(u=>u.selectedFrameId),O=o.useDashboardStore(u=>u.dashboard),x=o.useDashboardStore(u=>u.filterValues),y=o.useVisualById((t==null?void 0:t.id)||"",{enabled:!!(t!=null&&t.id)&&!!(e!=null&&e.accessToken)}),M=b.useCallback(async u=>{try{d(u),A();const{data:p,fromCache:h}=await j(a.apiServiceUrl,(e==null?void 0:e.accessToken)||"",u.id,r);if(!Q(p,{setFrame:c,setCard:n,setIsDevMode:s,setActiveTabCardId:l,updateDataSource:m,setQueryResultColumns:f,setSelectedConnectionId:V,setSelectedDatabaseName:g,setSelectedSchemaName:i,setSelectedTableName:C,setSelectedDatamodelId:U,setFilterValues:w,setApplyFilters:E,setIsDashboardEditing:S,setIsVisualEditing:$,dashboard:O,selectedSheetId:I,selectedFrameId:D,filterValues:x}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:h}}catch(p){return console.error("Error editing visual:",p),{success:!1,error:"Failed to load visual for editing"}}},[e==null?void 0:e.accessToken,a.apiServiceUrl,r,d,c,n,S,$,s,l,m,f,V,g,i,C,U,w,E,A,O,I,D,x]),k=b.useCallback(async u=>{var p;try{if(d(u),!I)return{success:!1,error:"No sheet selected. Please select a sheet first."};const{data:h,fromCache:W}=await j(a.apiServiceUrl,(e==null?void 0:e.accessToken)||"",u.id,r),L=(h==null?void 0:h.frameObject)??((p=h==null?void 0:h.visual)==null?void 0:p.frameObject);if(!L)return{success:!1,error:"Visual has no frame data"};const F=T(L);if(!(F!=null&&F.cards)||F.cards.length===0)return{success:!1,error:"Visual frame is malformed"};const P={...o.cloneFrameWithNewIds(F),visualId:u.id};return N(I,P,"end"),S(!0),v(P.id),R(!1),{success:!0,fromCache:W}}catch(h){return console.error("Error adding visual:",h),{success:!1,error:"Failed to add visual to dashboard"}}},[e==null?void 0:e.accessToken,a.apiServiceUrl,r,d,I,N,S,v,R]);return{visual:y.data,isLoading:y.isLoading,isError:y.isError,error:y.error,handleEditLibraryVisual:M,handleAddLibraryVisual:k,getUpdatedFrame:G().getUpdatedFrame,refetch:y.refetch}}exports.useRemoteChartStore=B;exports.useVisualUtils=z;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../chunks/index-DUJ50AjE.js"),r=require("../types/index.cjs");exports.Dashboard=e.Dashboard;exports.EMPTY_SELECTION=r.EMPTY_SELECTION;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../chunks/index-BYjv54tY.js"),r=require("../types/index.cjs");exports.Dashboard=e.Dashboard;exports.EMPTY_SELECTION=r.EMPTY_SELECTION;
@@ -1,4 +1,4 @@
1
- import { D as a } from "../chunks/index-CGyjzIO0.js";
1
+ import { D as a } from "../chunks/index-DLEb3N-R.js";
2
2
  import { EMPTY_SELECTION as e } from "../types/index.js";
3
3
  export {
4
4
  a as Dashboard,
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/index-DUJ50AjE.js"),j=require("./types/index.cjs"),a=require("react/jsx-runtime"),g=require("react"),E=require("./chunks/resource-management-panel-Ddyzqha7.js"),h=require("./chunks/schedule-dashboard-Dy7czCFY.js");require("react-dom");function N(t){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:()=>t[n]})}}return r.default=t,Object.freeze(r)}const p=N(g);/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/index-BYjv54tY.js"),j=require("./types/index.cjs"),a=require("react/jsx-runtime"),g=require("react"),E=require("./chunks/resource-management-panel-DToljP14.js"),h=require("./chunks/schedule-dashboard-vZXqGP-q.js");require("react-dom");function N(t){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:()=>t[n]})}}return r.default=t,Object.freeze(r)}const p=N(g);/**
2
2
  * @license lucide-react v0.453.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import { b as S, E as D, F as w, S as P, U as M, e as k, C as A, u as F, f as g, g as L, P as R, h as I, B as V, c as v, i as _, j as W, k as B, l as j, I as q, m as O, n as z, o as G, p as H, q as Q } from "./chunks/index-CGyjzIO0.js";
2
- import { G as oa, H as ta, D as na, x as ia, M as la, R as da, t as ca, t as ua, v as ha, a as pa, a9 as fa, Y as ma, z as Ca, N as va, _ as ya, Z as ba, a1 as ga, a2 as Da, W as xa, y as Ea, V as Na, K as Ta, L as Sa, J as wa, $ as Pa, T as Ma, Q as ka, O as Aa, a3 as Fa, a0 as La, w as Ra, a5 as Ia, a7 as Va, a6 as _a, a8 as Wa, A as Ba, r as ja, ab as qa, a4 as Oa, aa as za, s as Ga } from "./chunks/index-CGyjzIO0.js";
1
+ import { b as S, E as D, F as w, S as P, U as M, e as k, C as A, u as F, f as g, g as L, P as R, h as I, B as V, c as v, i as _, j as W, k as B, l as j, I as q, m as O, n as z, o as G, p as H, q as Q } from "./chunks/index-DLEb3N-R.js";
2
+ import { G as oa, H as ta, D as na, x as ia, M as la, R as da, t as ca, t as ua, v as ha, a as pa, a9 as fa, Y as ma, z as Ca, N as va, _ as ya, Z as ba, a1 as ga, a2 as Da, W as xa, y as Ea, V as Na, K as Ta, L as Sa, J as wa, $ as Pa, T as Ma, Q as ka, O as Aa, a3 as Fa, a0 as La, w as Ra, a5 as Ia, a7 as Va, a6 as _a, a8 as Wa, A as Ba, r as ja, ab as qa, a4 as Oa, aa as za, s as Ga } from "./chunks/index-DLEb3N-R.js";
3
3
  import { EMPTY_SELECTION as Qa } from "./types/index.js";
4
4
  import { jsx as a, jsxs as l } from "react/jsx-runtime";
5
5
  import * as p from "react";
6
6
  import { useMemo as U } from "react";
7
- import { ResourceManagementPanel as Ka } from "./chunks/resource-management-panel-DpASGkNn.js";
8
- import { A as $a, S as Ja, V as Xa, c as Za, g as ae } from "./chunks/schedule-dashboard-e0SVfJ6s.js";
7
+ import { ResourceManagementPanel as Ka } from "./chunks/resource-management-panel-k_ZQIBfh.js";
8
+ import { A as $a, S as Ja, V as Xa, c as Za, g as ae } from "./chunks/schedule-dashboard-fjtSpUVj.js";
9
9
  import "react-dom";
10
10
  /**
11
11
  * @license lucide-react v0.453.0 - ISC
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../chunks/index-DUJ50AjE.js"),r=require("../types/index.cjs");exports.Surfboard=e.DashboardPlus;exports.EMPTY_SELECTION=r.EMPTY_SELECTION;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../chunks/index-BYjv54tY.js"),r=require("../types/index.cjs");exports.Surfboard=e.DashboardPlus;exports.EMPTY_SELECTION=r.EMPTY_SELECTION;
@@ -1,4 +1,4 @@
1
- import { a } from "../chunks/index-CGyjzIO0.js";
1
+ import { a } from "../chunks/index-DLEb3N-R.js";
2
2
  import { EMPTY_SELECTION as E } from "../types/index.js";
3
3
  export {
4
4
  E as EMPTY_SELECTION,
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "email": "support@semaphor.cloud"
6
6
  },
7
7
  "license": "MIT",
8
- "version": "0.1.101",
8
+ "version": "0.1.102",
9
9
  "description": "Fully interactive and customizable dashboards for your apps.",
10
10
  "keywords": [
11
11
  "react",
@@ -1,6 +0,0 @@
1
- "use strict";const s=require("react/jsx-runtime"),e=require("./index-DUJ50AjE.js"),f=require("./editor-action-buttons-DPAlJF2w.js"),p=require("react"),y=require("./use-visual-utils-CFuV8lsO.js");/**
2
- * @license lucide-react v0.453.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const k=e.createLucideIcon("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);function F({open:a,onOpenChange:r,isLibraryVisual:t,currentVisualName:n,isSaving:l=!1,onConfirm:h}){const[i,d]=p.useState(t&&n?`Copy of ${n}`:n||""),[c,v]=p.useState(""),[b,D]=p.useState(!t),[j,S]=p.useState(!0);p.useEffect(()=>{a&&(d(t&&n?`Copy of ${n}`:n||""),v(""),D(!t),S(!0))},[a,t,n]);const C=()=>{i.trim()&&(!b&&!j||h({name:i.trim(),description:c.trim()||void 0,saveToLibrary:b,saveToCurrentDashboard:j}))},g=i.trim()&&(b||j);return s.jsx(e.Dialog,{open:a,onOpenChange:r,children:s.jsxs(e.DialogContent,{className:"sm:max-w-[425px]",children:[s.jsxs(e.DialogHeader,{children:[s.jsx(e.DialogTitle,{children:"Save Visual As"}),s.jsx(e.DialogDescription,{children:t?"Create a copy of this visual with a new name":"Save this visual to make it reusable"})]}),s.jsxs("div",{className:"grid gap-4 py-4",children:[s.jsxs("div",{className:"grid gap-2",children:[s.jsx(e.Label,{htmlFor:"name",children:"Name"}),s.jsx(e.Input,{id:"name",value:i,onChange:m=>d(m.target.value),placeholder:"Enter visual name",disabled:l})]}),s.jsxs("div",{className:"grid gap-2",children:[s.jsx(e.Label,{htmlFor:"description",children:"Description (optional)"}),s.jsx(e.Textarea,{id:"description",value:c,onChange:m=>v(m.target.value),placeholder:"Enter visual description",rows:3,disabled:l})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsx(e.Label,{children:"Save to:"}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(e.Checkbox,{id:"save-to-dashboard",checked:j,onCheckedChange:m=>S(!!m),disabled:l}),s.jsxs("label",{htmlFor:"save-to-dashboard",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Current Dashboard",s.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:t?"(add copy to this dashboard)":"(keep as local visual)"})]})]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(e.Checkbox,{id:"save-to-library",checked:b,onCheckedChange:m=>D(!!m),disabled:l}),s.jsxs("label",{htmlFor:"save-to-library",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:["Visual Library",s.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:t?"(save as new reusable visual)":"(make available to all dashboards)"})]})]})]}),!b&&!j&&s.jsx("p",{className:"text-sm text-destructive",children:"Please select at least one destination"})]})]}),s.jsxs(e.DialogFooter,{children:[s.jsx(e.Button,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancel"}),s.jsxs(e.Button,{onClick:C,disabled:!g||l,children:[l&&s.jsx(e.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Saving...":"Save"]})]})]})})}function N(){const[a,r]=p.useState(!1),[t,n]=p.useState(!1),[l,h]=p.useState(null),i=e.useEditorStore(o=>o.frame),d=e.useEditorStore(o=>o.card),c=e.useSelectedVisual(),v=e.useDashboardStore(o=>o.selectedSheetId),b=e.useDashboardStore(o=>o.actions.setIsDashboardPanelOpen),{getUpdatedFrame:D}=y.useVisualUtils(),{selectVisual:j}=e.useManagementActions(),{addFrame:S,setSelectedFrameId:C,setIsVisualEditing:g}=e.useDashboardActions(),m=!!(i!=null&&i.visualId),w=(()=>{var o,x;return c!=null&&c.title?c.title:((o=i==null?void 0:i.cards)==null?void 0:o.length)===1&&((x=i.cards[0])!=null&&x.title)?i.cards[0].title:(d==null?void 0:d.title)||"Untitled Visual"})(),u=e.useCreateVisualWithFrame(o=>{if(o!=null&&o.id){if(j(o),t&&l&&v){const x={...l,id:e.v4(),visualId:o.id};S(v,x,"end"),C(x.id),n(!1),h(null),g(!1)}b(!0),r(!1)}});return{saveAsDialogOpen:a,setSaveAsDialogOpen:r,handleSaveAs:async o=>{if(!v){e.ue.error("No sheet selected");return}const x=D(),I=x.cards.length===1?{...x,cards:x.cards.map(A=>({...A,title:o.name}))}:x;if(o.saveToLibrary){n(o.saveToCurrentDashboard),h(I);const A={title:o.name,description:o.description,frameObject:I,isPrivate:!1};u.mutate(A)}else if(o.saveToCurrentDashboard){const A={...I,id:e.v4(),visualId:void 0};S(v,A,"end"),C(A.id),e.ue.success("Visual saved to dashboard"),r(!1),g(!1)}},isLibraryVisual:m,currentVisualName:w,isSaving:u.isPending}}function V({className:a}){const r=e.useEditorStore(u=>u.frame),t=e.useEditorStore(u=>u.card),n=e.useManagementStore(u=>u.selectedVisual),l=e.useDashboardStore(u=>u.selectedFrameId),h=e.useDashboardStore(u=>u.selectedSheetId),{setIsVisualEditing:i}=e.useDashboardActions(),d=!!(r!=null&&r.visualId||n!=null&&n.id),c=!!(r!=null&&r.visualId&&l),v=d&&!c,{saveAsDialogOpen:b,setSaveAsDialogOpen:D,handleSaveAs:j,isLibraryVisual:S,currentVisualName:C,isSaving:g}=N(),{handleAddLibraryVisual:m}=y.useVisualUtils(),w=async()=>{if(!h){e.ue.error("No dashboard sheet selected");return}if(!n){e.ue.error("No visual selected");return}const u=await m(n);u.success?(e.ue.success("Visual added to dashboard"),i(!1)):e.ue.error(u.error||"Failed to add visual to dashboard")};return s.jsxs(s.Fragment,{children:[!d&&s.jsx(f.EditorAcceptButton,{className:a,variant:"default"}),d&&s.jsxs(s.Fragment,{children:[c&&s.jsx(f.VisualApplyLocalButton,{className:a}),v&&h&&t&&(t.sql||e.hasValidCardConfig(t.config))&&s.jsxs(e.Button,{onClick:w,className:e.cn(a),size:"sm",variant:"outline",children:[s.jsx(k,{className:"mr-2 size-4 font-bold"}),"Add to Dashboard"]}),v&&s.jsx(f.VisualSaveButton,{className:a,variant:"default"}),c&&s.jsx(f.VisualSaveAndApplyButton,{className:a}),s.jsxs(e.DropdownMenu,{modal:!1,children:[s.jsx(e.DropdownMenuTrigger,{asChild:!0,children:s.jsx(e.Button,{variant:"outline",size:"sm",className:e.cn(a,"w-8 p-0"),children:s.jsx(e.EllipsisVertical,{className:"h-4 w-4"})})}),s.jsx(e.DropdownMenuContent,{align:"end",children:s.jsxs(e.DropdownMenuItem,{onClick:u=>{u.stopPropagation(),D(!0)},children:[s.jsx(f.Save,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]})]}),!d&&s.jsxs(e.DropdownMenu,{modal:!1,children:[s.jsx(e.DropdownMenuTrigger,{asChild:!0,children:s.jsx(e.Button,{variant:"outline",size:"sm",className:e.cn(a,"w-8 p-0"),children:s.jsx(e.EllipsisVertical,{className:"h-4 w-4"})})}),s.jsx(e.DropdownMenuContent,{align:"end",children:s.jsxs(e.DropdownMenuItem,{onClick:()=>D(!0),children:[s.jsx(f.Save,{className:"mr-2 h-4 w-4"}),"Save As..."]})})]}),s.jsx(f.EditorCancelButton,{className:a}),s.jsx(F,{open:b,onOpenChange:u=>{g||D(u)},isLibraryVisual:S,currentVisualName:C,isSaving:g,onConfirm:j})]})}function E({className:a,switchClassName:r}){const t=e.useEditorStore(d=>d.isDevMode),n=e.useDashboardStore(d=>d.isVisualEditing),{setIsDevMode:l}=e.useEditorActions(),{config:h}=p.useContext(e.SemaphorContext).tokenProps,i=(h==null?void 0:h.showAdvancedMode)!==!1;return!n||!i?null:s.jsxs("div",{className:e.cn("flex items-center space-x-2",a),children:[s.jsx(e.DevModeSwitch,{className:e.cn("",r),checked:t,onCheckedChange:()=>l(!t),id:"advanced-mode",icon:s.jsx(e.CodeXml,{className:"h-4 w-4"}),tooltip:t?"Standard Mode":"Advanced Mode"}),s.jsx("label",{htmlFor:"advanced-mode",className:"sr-only",children:"Advanced Mode"})]})}function T(a){var r;return{...a,sheets:(r=a==null?void 0:a.sheets)==null?void 0:r.map(t=>{var n;return{...t,frames:(n=t.frames)==null?void 0:n.map(l=>{var h;return{...l,cards:(h=l.cards)==null?void 0:h.map(i=>M(i))}})}})}}function M(a){return{...a,customCfg:B(a.customCfg),data:[]}}function B(a){var r,t;return a?{...a,data:{...a==null?void 0:a.data,labels:[],datasets:(t=(r=a==null?void 0:a.data)==null?void 0:r.datasets)==null?void 0:t.map(n=>({...n,data:[]}))}}:null}function O({triggerButtonClassName:a}){const[r,t]=p.useState(!1),n=e.useDashboardStore(d=>{var c;return(c=d.dashboard)==null?void 0:c.id}),l=e.useDashboardStore(d=>{var c;return(c=d.dashboard)==null?void 0:c.title}),h=e.useDashboardStore(d=>{var c;return(c=d.dashboard)==null?void 0:c.sheets}),i=e.useDashboardStore(d=>d.selectedSheetId);return h==null||h.find(d=>d.id===i),n?s.jsxs(s.Fragment,{children:[s.jsx(e.IconButton,{tooltip:"Schedule Dashboard",className:e.cn("h-7 p-2",a),onClick:()=>t(!0),children:s.jsx(e.Clock,{className:"size-4"})}),s.jsx(e.EmailScheduleDialog,{open:r,onOpenChange:t,dashboardId:n,dashboardName:l})]}):null}exports.AdvancedModeToggle=E;exports.ScheduleDashboard=O;exports.VisualEditingControls=V;exports.cleanCard=M;exports.getDashbaordStateWithoutData=T;