react-semaphor 0.1.607 → 0.1.609

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 (84) hide show
  1. package/dist/analytics-protocol/index.js +1 -1
  2. package/dist/assistant-context/index.js +1 -1
  3. package/dist/brand-studio/index.js +1 -1
  4. package/dist/briefings/index.js +1 -1
  5. package/dist/chunks/{appearance-provider-C4lPZcaN.js → appearance-provider-BW022_Qu.js} +106 -106
  6. package/dist/chunks/{assistant-chat-B7Fngg8U.js → assistant-chat-DAmFZEnD.js} +8 -8
  7. package/dist/chunks/attachment-filter-line-ClTS4GvQ.js +1 -0
  8. package/dist/chunks/{bookmark-impact-DjrrJomS.js → bookmark-impact-BEVaXjug.js} +1 -1
  9. package/dist/chunks/{bookmark-state-x9hJS83D.js → bookmark-state-DnkzIsyw.js} +1 -1
  10. package/dist/chunks/{brand-DgFcvKJI.js → brand-BjC1mPjw.js} +1 -1
  11. package/dist/chunks/card-filter-builder-BGIVEHmJ.js +11 -0
  12. package/dist/chunks/{visual-contract-DQPKg5QW.js → check-input-qgwboKei.js} +13 -5
  13. package/dist/chunks/{comparison-window-caption-zUZDe4tL.js → comparison-window-caption-WzGsqv4n.js} +1 -1
  14. package/dist/chunks/{currency-presentation-binding-w9WDUk3b.js → currency-presentation-binding-ClrH_6Tq.js} +1 -1
  15. package/dist/chunks/{custom-visual-inputs-D8U98aBz.js → custom-visual-inputs-CoAs_73N.js} +1 -1
  16. package/dist/chunks/custom-visual-write-BWApKrHe.js +1 -0
  17. package/dist/chunks/{dashboard-BEd6i29E.js → dashboard-DbBgEesz.js} +1 -1
  18. package/dist/chunks/{dashboard-briefing-launcher-DMDYM9IA.js → dashboard-briefing-launcher-DadG4ES9.js} +14 -9
  19. package/dist/chunks/{dashboard-controls-5B2vCIjJ.js → dashboard-controls-CyQg_GC1.js} +3 -3
  20. package/dist/chunks/{dashboard-json-C6r30x-5.js → dashboard-json-ZSAQQkcR.js} +1 -1
  21. package/dist/chunks/{dashboard-temporal-snapshot-Wki-YACw.js → dashboard-temporal-snapshot-BSTfqT29.js} +1 -1
  22. package/dist/chunks/edit-dashboard-visual-DIF1fllI.js +103 -0
  23. package/dist/chunks/{filter-line-COFQaF4_.js → filter-line-W-qQAjke.js} +1 -1
  24. package/dist/chunks/{filter-reach-preview-BWRGfSmb.js → filter-reach-preview-CfbwaLf4.js} +1 -1
  25. package/dist/chunks/filter-value-text-DQwYZHz0.js +1 -0
  26. package/dist/chunks/kpi-trend-rule-B4ebKzNj.js +1 -0
  27. package/dist/chunks/{layout-grid-DahW4ClC.js → layout-grid-Cs350bW-.js} +1 -1
  28. package/dist/chunks/{matrix-analytical-definition-Bd-dXB8q.js → matrix-analytical-definition-jn075ooo.js} +1 -1
  29. package/dist/chunks/{matrix-member-presentation-CfvxPV-i.js → matrix-member-presentation-Chz6uGYz.js} +1 -1
  30. package/dist/chunks/{matrix-operation-contract-Cw7U53Ao.js → matrix-operation-contract-DceN49RX.js} +1 -1
  31. package/dist/chunks/{metric-formatting-QDqXfQGY.js → metric-formatting-toJrRqu4.js} +1 -1
  32. package/dist/chunks/{numeric-range-options-s6i_nDXg.js → numeric-range-options-Drc1EZ6H.js} +1 -1
  33. package/dist/chunks/{palette-CYvJHSqP.js → palette-DpLPXjUd.js} +1 -1
  34. package/dist/chunks/{pivot-result-contract-expectations-BX5gLcze.js → pivot-result-contract-expectations-D_ane7I2.js} +1 -1
  35. package/dist/chunks/{pivot-result-identity-DOISzHU4.js → pivot-result-identity-DRhVJMsF.js} +1 -1
  36. package/dist/chunks/{raw-temporal-value-Cssny3RJ.js → raw-temporal-value-B4Md6Xfb.js} +1 -1
  37. package/dist/chunks/{report-preferences-dialog-BNpB9byP.js → report-preferences-dialog-DEfUYExu.js} +1 -1
  38. package/dist/chunks/{report-runtime-context-B8HuY0bu.js → report-runtime-context-CkxgMKr6.js} +1 -1
  39. package/dist/chunks/resolve-dashboard-input-context-Dm4PD8Gx.js +8 -0
  40. package/dist/chunks/{sandbox-host-Drf58_oU.js → sandbox-host-BqcLSoTV.js} +1 -1
  41. package/dist/chunks/{saved-dashboard-context-dbdbQ5bB.js → saved-dashboard-context-GjEJuDjj.js} +1 -1
  42. package/dist/chunks/{selection-filter-compiler-DK8KkS9g.js → selection-filter-compiler-BxtEEB6Z.js} +1 -1
  43. package/dist/chunks/semaphor-ready-indicator-BViyPq5k.js +622 -0
  44. package/dist/chunks/set-q-2M4nis.js +1 -0
  45. package/dist/chunks/slider-C2nbml5r.js +599 -0
  46. package/dist/chunks/{stored-dashboard-DmgJQcyZ.js → stored-dashboard-CTwrNvBy.js} +1 -1
  47. package/dist/chunks/{table-cell-text-2x6r_oHO.js → table-cell-text-DJe6I1G3.js} +1 -1
  48. package/dist/chunks/{table-export-sheet-CWqKiQu4.js → table-export-sheet-CthBUHu4.js} +1 -1
  49. package/dist/chunks/{token-types-BSyWn2pb.js → token-types-BM0mpZce.js} +1 -1
  50. package/dist/chunks/{validators-BPGmPz8-.js → validators-U8IL8djK.js} +1 -1
  51. package/dist/chunks/variable-draft-DAVLIY3l.js +1 -0
  52. package/dist/dashboard/index.js +1 -1
  53. package/dist/dashboard-authoring/index.js +1 -1
  54. package/dist/extensions/index.js +1 -1
  55. package/dist/format-utils/index.js +1 -1
  56. package/dist/index.js +1 -1
  57. package/dist/report-runtime-context/index.js +1 -1
  58. package/dist/style.css +1 -1
  59. package/dist/surfboard/index.js +1 -1
  60. package/dist/types/index.js +1 -1
  61. package/dist/types/lib/dashboard-viewer/table-view.d.ts +6 -1
  62. package/dist/types/lib/types/explorer-types.d.ts +12 -0
  63. package/dist/types/shared/dashboard-authoring/card-settings/custom-visual-write.d.ts +6 -0
  64. package/dist/types/shared/dashboard-authoring/card-sort-comparison.d.ts +13 -0
  65. package/dist/types/shared/dashboard-authoring/changes/card-query-part.d.ts +1 -0
  66. package/dist/types/shared/dashboard-authoring/changes/dashboard-change.d.ts +12 -0
  67. package/dist/types/shared/dashboard-authoring/index.d.ts +1 -0
  68. package/dist/types/shared/dashboard-authoring/table-sheet-shape.d.ts +8 -0
  69. package/dist/types/shared/dashboard-authoring/variable-draft.d.ts +1 -0
  70. package/dist/types/shared/dashboard-viewer/table-settings.d.ts +8 -0
  71. package/dist/types/shared/extensions/visual-contract.d.ts +3 -1
  72. package/dist/types/shared/usage-events/envelope.d.ts +2 -2
  73. package/package.json +1 -1
  74. package/dist/chunks/attachment-filter-line-wJRB0GSP.js +0 -1
  75. package/dist/chunks/card-filter-builder-CvxygmsE.js +0 -16
  76. package/dist/chunks/check-input-7DVPUuco.js +0 -1
  77. package/dist/chunks/edit-dashboard-visual-F2w7v4iB.js +0 -83
  78. package/dist/chunks/filter-value-text-BSAMEgve.js +0 -1
  79. package/dist/chunks/kpi-trend-rule-BcnKbY7d.js +0 -1
  80. package/dist/chunks/resolve-dashboard-input-context-B-0tONJg.js +0 -8
  81. package/dist/chunks/semaphor-ready-indicator-BSFsqsBJ.js +0 -617
  82. package/dist/chunks/set-oJDaJdtI.js +0 -1
  83. package/dist/chunks/slider-DAvAdfMC.js +0 -599
  84. package/dist/chunks/variable-draft-DGA22H2g.js +0 -1
@@ -1 +1 @@
1
- import{r as Ri,bW as Ce,bX as qs,be as Oi,bY as Ei,bZ as Ni,b_ as Xe,b$ as Ls,c0 as Pi,c1 as Ms,c2 as qi,c3 as Le,c4 as na,c5 as Li,c6 as Vs,c7 as Mi,c8 as is,c9 as qt,ca as ga,cb as ae,cc as te,cd as ze,ce as Vi,cf as Bi,cg as ba,ch as ji,ci as Ki,cj as Wi,ai as Ui,ck as Gi,cl as Qi,cm as Hi,cn as Bs,b7 as Yi,co as Ji,cp as zi,cq as Xi,cr as Zi,cs as eo,ct as to,cu as ao,cv as so,cw as Kt,cx as io,u as js,cy as oo,cz as no,cA as ro,cB as os,cC as lo,cD as co,a5 as ya,cE as qe,cF as Me,cG as Ve,cH as De,cI as uo,bN as Ks,cJ as va,cK as Rt,cL as St,cM as ht,cN as fo,cO as ho,cP as mo,cQ as po,cR as go,cS as ra,cT as Ot,cU as bo,cV as yo,cW as Ws,cX as $a,cY as da,cZ as vo,c_ as $o,c$ as wo,bT as he,d0 as Us,d1 as Io,d2 as _o,d3 as Wt,al as Ut,d4 as xt,d5 as kt,d6 as Co,d7 as So,d8 as Gs,bf as ns,d9 as xo,da as rs,db as ko,dc as ds,dd as ls,de as cs,df as lt,dg as To,dh as Tt,di as Qs,dj as Fo,dk as Ao,dl as Hs,dm as Do,dn as Ys,dp as Ft,ak as wa,a4 as Ro,dq as Oo,dr as us,ds as Js,dt as Eo,aQ as No,du as zs,dv as Po,dw as qo,dx as Lo,dy as Xs,e as Mo,dz as Vo,dA as Bo,dB as jo,dC as Ko,dD as Wo,dE as Uo,dF as Go,dG as Qo,dH as Ho,dI as Yo,dJ as Jo,dK as zo,dL as fs,am as Xo,dM as Zo,b5 as en,dN as tn,dO as an,dP as sn,dQ as on,dR as nn,dS as rn,dT as dn,aa as ln,dU as cn,ag as un,dV as fn}from"../chunks/resolve-dashboard-input-context-B-0tONJg.js";import{gt as Kl,ef as Wl,ek as Ul,a$ as Gl,a_ as Ql,gZ as Hl,gl as Yl,aK as Jl,hW as zl,gk as Xl,iW as Zl,gf as ec,hG as tc,gm as ac,gn as sc,gP as ic,fL as oc,fM as nc,fN as rc,fI as dc,fJ as lc,fK as cc,fE as uc,fF as fc,fH as hc,fG as mc,aB as pc,fO as gc,gJ as bc,g8 as yc,eR as vc,hi as $c,i9 as wc,hh as Ic,gT as _c,g_ as Cc,eQ as Sc,g0 as xc,gv as kc,e_ as Tc,hI as Fc,eC as Ac,ip as Dc,e9 as Rc,gM as Oc,gy as Ec,g$ as Nc,iu as Pc,iG as qc,fh as Lc,fi as Mc,iA as Vc,gi as Bc,gj as jc,eX as Kc,hT as Wc,hR as Uc,hS as Gc,e6 as Qc,im as Hc,aC as Yc,ey as Jc,gx as zc,f1 as Xc,ir as Zc,gE as eu,eW as tu,iK as au,iL as su,ht as iu,ed as ou,jl as nu,jq as ru,gw as du,fS as lu,jp as cu,ic as uu,iQ as fu,fu as hu,bg as mu,ge as pu,eY as gu,fa as bu,ea as yu,h7 as vu,h8 as $u,jb as wu,bL as Iu,fP as _u,fv as Cu,je as Su,gL as xu,e0 as ku,j6 as Tu,b6 as Fu,jr as Au,gU as Du,gX as Ru,gW as Ou,gV as Eu,i3 as Nu,h_ as Pu,hr as qu,ee as Lu,aV as Mu,ib as Vu,gA as Bu,iV as ju,hX as Ku,hY as Wu,id as Uu,e1 as Gu,jt as Qu,js as Hu,ej as Yu,eB as Ju,h2 as zu,j5 as Xu,aL as Zu,fp as ef,iO as tf,hy as af,hu as sf,gD as of,hK as nf,hs as rf,gO as df,f$ as lf,f_ as cf,jd as uf,jc as ff,eV as hf,gK as mf,hl as pf,hq as gf,eu as bf,j7 as yf,eJ as vf,gI as $f,fb as wf,fy as If,fA as _f,fm as Cf,d_ as Sf,iB as xf,fl as kf,fg as Tf,iF as Ff,hj as Af,hm as Df,hn as Rf,f2 as Of,gS as Ef,gQ as Nf,hd as Pf,e2 as qf,eb as Lf,hv as Mf,io as Vf,ec as Bf,aO as jf,i8 as Kf,gr as Wf,gs as Uf,eI as Gf,eG as Qf,eH as Hf,iR as Yf,iS as Jf,iU as zf,fz as Xf,ev as Zf,ew as eh,ex as th,eZ as ah,i5 as sh,i6 as ih,e$ as oh,aE as nh,iN as rh,hD as dh,g4 as lh,j3 as ch,b4 as uh,g5 as fh,g7 as hh,$ as mh,b1 as ph,eO as gh,f7 as bh,g6 as yh,h as vh,fB as $h,aZ as wh,em as Ih,en as _h,eg as Ch,fT as Sh,ho as xh,gC as kh,eN as Th,h4 as Fh,f3 as Ah,iZ as Dh,j1 as Rh,eF as Oh,ff as Eh,ez as Nh,y as Ph,eS as qh,j4 as Lh,gg as Mh,eT as Vh,eq as Bh,gq as jh,eD as Kh,A as Wh,hU as Uh,iT as Gh,e7 as Qh,fY as Hh,h5 as Yh,fZ as Jh,h9 as zh,aI as Xh,i4 as Zh,hM as em,hL as tm,gF as am,fr as sm,f6 as im,f8 as om,a2 as nm,f9 as rm,ia as dm,i_ as lm,hB as cm,go as um,gB as fm,dW as hm,dX as mm,dY as pm,e3 as gm,iy as bm,iq as ym,ja as vm,gu as $m,j8 as wm,is as Im,j2 as _m,fo as Cm,eU as Sm,fx as xm,fk as km,fj as Tm,gp as Fm,hA as Am,g1 as Dm,aG as Rm,g2 as Om,i2 as Em,el as Nm,aJ as Pm,iP as qm,gz as Lm,aU as Mm,iY as Vm,hw as Bm,hk as jm,g3 as Km,iX as Wm,hp as Um,hQ as Gm,hO as Qm,D as Hm,ix as Ym,fd as Jm,eM as zm,iv as Xm,iC as Zm,iD as ep,gc as tp,fD as ap,ep as sp,ju as ip,gY as op,gR as np,gN as rp,dZ as dp,fs as lp,ft as cp,jo as up,fR as fp,jk as hp,et as mp,ji as pp,jj as gp,eK as bp,eL as yp,g9 as vp,ga as $p,eP as wp,aT as Ip,e4 as _p,es as Cp,fV as Sp,hJ as xp,hF as kp,iE as Tp,fW as Fp,fU as Ap,iH as Dp,eo as Rp,aF as Op,hH as Ep,fq as Np,hE as Pp,fC as qp,jg as Lp,h$ as Mp,aM as Vp,iw as Bp,h6 as jp,hV as Kp,gb as Wp,fn as Up,eE as Gp,gh as Qp,d$ as Hp,er as Yp,gG as Jp,jv as zp,hP as Xp,jm as Zp,hZ as eg,h3 as tg,fw as ag,fX as sg,e8 as ig,iM as og,i0 as ng,gH as rg,iI as dg,eA as lg,h1 as cg,h0 as ug,hC as fg,hN as hg,i$ as mg,j0 as pg,f0 as gg,f5 as bg,e5 as yg,iz as vg,it as $g,jn as wg,iJ as Ig,fQ as _g,fe as Cg,aD as Sg,hx as xg,hg as kg,hz as Tg,gd as Fg,jf as Ag,hf as Dg,i7 as Rg,ig as Og,eh as Eg,i1 as Ng,hc as Pg,ei as qg,jh as Lg,jw as Mg,he as Vg,f4 as Bg,ha as jg,hb as Kg,ie as Wg,ih as Ug,ii as Gg,ij as Qg,fc as Hg,ik as Yg,j9 as Jg,il as zg,b8 as Xg,b9 as Zg}from"../chunks/resolve-dashboard-input-context-B-0tONJg.js";import{Q as Ia,R as hn,M as _a,S as mn,T as pn,U as Ca,W as Zs,J as _e,X as ei,Y as gn,Z as bn,F as yn,N as vn}from"../chunks/bookmark-state-x9hJS83D.js";import{ak as tb,aD as ab,a3 as sb,a4 as ib,ae as ob,ai as nb,af as rb,ag as db,ah as lb,al as cb,aB as ub,av as fb,K as hb,az as mb,L as pb,a7 as gb,G as bb,aC as yb,aa as vb,ab as $b,ax as wb,aj as Ib,a8 as _b,au as Cb,ay as Sb,aA as xb,O as kb,aw as Tb,I as Fb,a5 as Ab,an as Db,as as Rb,$ as Ob,a0 as Eb,_ as Nb,a1 as Pb,a9 as qb,at as Lb,aE as Mb,ao as Vb,am as Bb,ap as jb,aq as Kb,ar as Wb,ad as Ub,ac as Gb,a2 as Qb,a6 as Hb}from"../chunks/bookmark-state-x9hJS83D.js";import{L as Jb,B as zb,C as Xb,e as Zb,A as ey,j as ty,b as ay,y as sy,o as iy,q as oy,z as ny,x as ry,k as dy,n as ly,p as cy,w as uy,D as fy,s as hy,u as my,t as py,v as gy}from"../chunks/stored-dashboard-DmgJQcyZ.js";import{aX as ti,r as $n,ad as hs}from"../chunks/pivot-result-contract-expectations-BX5gLcze.js";import{aZ as yy,aY as vy,aQ as $y,aJ as wy,a_ as Iy,aK as _y}from"../chunks/pivot-result-contract-expectations-BX5gLcze.js";import{d as ai}from"../chunks/set-oJDaJdtI.js";import{a as Sy,C as xy,b as ky,o as Ty,i as Fy,f as Ay,g as Dy,l as Ry,H as Oy,I as Ey,A as Ny,t as Py,v as qy,z as Ly,G as My,B as Vy,x as By,F as jy,D as Ky,E as Wy,y as Uy,h as Gy,k as Qy,m as Hy,j as Yy,n as Jy,e as zy,p as Xy,c as Zy,P as ev,M as tv,N as av,w as sv,J as iv,r as ov,O as nv,s as rv,q as dv,K as lv,u as cv,L as uv}from"../chunks/set-oJDaJdtI.js";import{g as si,C as $t,D as wn,l as Lt,S as In,m as ii,k as mt,n as ms,o as _n,p as Cn,q as Sn,s as xn,t as kn,u as Tn,v as Fn,e as An}from"../chunks/filter-reach-preview-BWRGfSmb.js";import{N as hv,a4 as mv,X as pv,z as gv,F as bv,H as yv,G as vv,J as $v,y as wv,I as Iv,E as _v,w as Cv,P as Sv,b as xv,a5 as kv,R as Tv,T as Fv,a3 as Av,K as Dv,a0 as Rv,A as Ov,Y as Ev,U as Nv,a2 as Pv,a1 as qv,Q as Lv,M as Mv,O as Vv,x as Bv,_ as jv,Z as Kv,W as Wv,$ as Uv,V as Gv,B as Qv,L as Hv}from"../chunks/filter-reach-preview-BWRGfSmb.js";import{w as Dn,m as ps,c as Rn,b as On,f as oi}from"../chunks/kpi-trend-rule-BcnKbY7d.js";import{K as Jv,a as zv,d as Xv}from"../chunks/kpi-trend-rule-BcnKbY7d.js";import{P as gs,C as En,U as Nn}from"../chunks/matrix-analytical-definition-Bd-dXB8q.js";import{l as Sa,D as bs,r as Pn}from"../chunks/matrix-operation-contract-Cw7U53Ao.js";import{f as la,d as qn}from"../chunks/raw-temporal-value-Cssny3RJ.js";import{a9 as Mt,l as xa,aQ as Ln,b1 as Be,aO as Vt,aP as ni,k as Mn,aH as ri,aT as Vn,aN as Bn,j as jn}from"../chunks/validators-BPGmPz8-.js";import{C as pt,D as ut,B as Kn,T as Wn,z as ka,t as gt,c as Un}from"../chunks/analytics-base-schemas-DMFrDqn_.js";import"../value-format-preferences/index.js";import"zod";import"../chunks/schema-O1Y3WTGF.js";import{r as Gn}from"../chunks/index-DViPGDFj.js";import"../chunks/context-Cwj8Axgd.js";import{f as Qn}from"../chunks/selection-filter-compiler-DK8KkS9g.js";import{v as At,a as Hn,i as ys,o as Gt,d as Yn,b as Jn,c as zn}from"../chunks/variable-draft-DGA22H2g.js";import{S as e$,f as t$,g as a$,e as s$,n as i$}from"../chunks/variable-draft-DGA22H2g.js";import{b as n$,d as r$}from"../chunks/bookmark-impact-DjrrJomS.js";import{r as Ze,b as Xn,a as Zn,s as er}from"../chunks/resolver-CjsW8Rz0.js";import{n as tr,r as ar}from"../chunks/index-bkP6SnYu.js";import{e as l$}from"../chunks/brand-DgFcvKJI.js";const Qt=["#14b8a6","#5eead4","#374151","#6b7280","#d1d5db"],sr=["spacing","canvasPadding","canvas","cardCorners","chartColors"],di=["light","dark"];function Rl(e){const t=[],a=Yt(e.globalStyle)?e.globalStyle:{},s=Yt(a.default)?a.default:{},i=Yt(a.dark)?a.dark:{},n=b=>Ze(i,b)??Ze(s,b),d={},c=n(["gridLayout","margin"]);Array.isArray(c)&&typeof c[1]=="number"&&(d.spacing=ct("spacing",c[1],t),d.canvasPadding=ct("canvasPadding",c[1],t));const u=n(["cardBorderRadius"]);typeof u=="number"&&(d.cardCorners=ct("cardCorners",u,t));const r=n(["controlInputRadius"]);typeof r=="number"&&(d.controlCorners=ct("controlCorners",r,t));const m=n(["chart","options","borderRadius"]);typeof m=="number"&&(d.barCorners=ct("barCorners",m,t));for(const b of di){const $=b==="light"?Ze(s,["canvasTheme"]):n(["canvasTheme"]),g=nr($,t);g!==void 0&&(d.canvas={...d.canvas,[b]:g});const S=or(s,i,b);if(S){const x=S.filter(si).map(A=>A.toLowerCase());x.length<S.length&&t.push({field:"chartColors",kind:"dropped_colour",detail:`${b}: ${S.length-x.length} colours that aren't hex`}),x.length>=$t.min&&(d.chartColors={...d.chartColors,[b]:x.slice(0,$t.max)}),x.length>$t.max&&t.push({field:"chartColors",kind:"clamped",detail:`${b}: kept the first ${$t.max} colours`});}}return{style:ir(d,e.organizationAppearance,t),notes:t};}function ir(e,t,a){const s=Xn({organizationAppearance:t?tr(t).spec:null}),i={...e};for(const n of Object.keys(e)){const d=Zn[n],c=n==="canvas"||n==="chartColors";for(const u of di){const r=er(i,n,u);if(r===void 0)continue;const m=sr.includes(n)&&Ze(ar(t,u),d)!==void 0,b=JSON.stringify(Ze(s.schemes[u],d))===JSON.stringify(r);if(!(!m&&!b))if((c||u==="light")&&a.push({field:n,kind:m?"brand_wins":"equal_to_inherited",detail:c?u:`${JSON.stringify(r)}`}),c){const $={...i[n]};delete $[u],Object.keys($).length>0?i[n]=$:delete i[n];}else u==="light"&&delete i[n];}}return Object.keys(i).length>0?i:void 0;}function or(e,t,a){const s=Ze(e,["chart","dataset","backgroundColor"]),i=Ze(t,["chart","dataset","backgroundColor"]),n=Ht(Qt,s);if(a==="light")return Array.isArray(s)?n:void 0;const d=Ht(n,Ht(Qt,i));if(!(!Array.isArray(i)&&JSON.stringify(d)===JSON.stringify(Qt)))return Array.isArray(s)||Array.isArray(i)?d:void 0;}function Ht(e,t){if(!Array.isArray(t))return[...e];const a=Math.max(e.length,t.length);return Array.from({length:a},(s,i)=>t[i]!==void 0?String(t[i]):e[i]);}function nr(e,t){if(!(e==null||e==="")){if(e==="muted")return"muted";if(e==="clear")return"background";if(si(e))return e.toLowerCase();t.push({field:"canvas",kind:"dropped_colour",detail:String(e)});}}function ct(e,t,a){const{min:s,max:i}=wn[e],n=Math.min(i,Math.max(s,Math.round(t)));return n!==t&&a.push({field:e,kind:"clamped",detail:`${t} → ${n}`}),n;}function Yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e);}const Jt={spacing:(e,t)=>t.spacing=e,canvasPadding:(e,t)=>t.canvasPadding=e,canvas:(e,t)=>t.canvas=e,cardBorder:(e,t)=>t.border=e,cardShadow:(e,t)=>t.shadow=e,cardCorners:(e,t)=>t.corners={...t.corners,cards:e},controlCorners:(e,t)=>t.corners={...t.corners,controls:e},chartColors:(e,t)=>t.chartColors=e,barCorners:(e,t)=>t.barCorners=e};function rr(e){var a;const t={};for(const[s,i]of Object.entries(e??{}))i!==void 0&&((a=Jt[s])==null||a.call(Jt,i,t));return t;}function vs(e){var d;const{card:t,stated:a,path:s}=e;let i;if(a.slots){i={};for(const[c,u]of Object.entries(a.slots)){if(u===null){i[c]=null;continue;}const r=dr(t,u,e.sqlColumns);if(!r.ok)return{ok:!1,problem:{code:"invalid_change",message:`The card has no field "${u}" for the slot "${c}"${r.fields.length?`; its fields are ${r.fields.join(", ")}`:""}.`,path:`${s}.slots.${c}`,fix:"Name one of the card's query fields, or add the field to the query.",...(r.fields.length?{allowed:r.fields}:{})}};i[c]=r.ref;}}const n=Dn(t,{...(a.html!==void 0?{html:a.html}:{}),...(i?{slots:i}:{}),...(a.settings?{settings:a.settings}:{})},{manifest:e.manifest});if(!n.ok)return{ok:!1,problem:{...n.problem,path:n.problem.path?`${s}.${n.problem.path}`:s}};for(const[c,u]of Object.entries(i??{})){const r=(d=n.manifest)==null?void 0:d.slots.find(b=>b.id===c),m=u?lr(t,u):void 0;if(r&&m&&m!==r.kind)return{ok:!1,problem:{code:"invalid_change",message:`The slot "${c}" (${r.label}) takes a ${r.kind}, and "${a.slots[c]}" is a ${m}.`,path:`${s}.slots.${c}`,fix:`Name a ${r.kind} of the card's query for it.`}};}return{ok:!0,card:n.card,wording:cr(t.customVisual,n.card.customVisual,n.manifest,n.card,a)};}function li(e){var s,i;const t=(i=(s=e.customVisual)==null?void 0:s.draft)==null?void 0:i.html;if(t===void 0)return;const a=Ri(t,{kind:"visual"});return a.ok?a.manifest:void 0;}function dr(e,t,a){var d,c,u;const s=t.trim().toLowerCase();if((d=e.sql)!=null&&d.trim()){if(!a)return{ok:!0,ref:{column:t}};const r=a.find(m=>m.toLowerCase()===s);return r?{ok:!0,ref:{column:r}}:{ok:!1,fields:[...a]};}const i=[...(((c=e.config)==null?void 0:c.groupByColumns)??[]),...(((u=e.config)==null?void 0:u.metricColumns)??[])],n=i.find(r=>{var m;return((m=r.label)==null?void 0:m.toLowerCase())===s;})??i.find(r=>{var m;return((m=r.name)==null?void 0:m.toLowerCase())===s;});return n!=null&&n.id?{ok:!0,ref:{fieldId:n.id}}:{ok:!1,fields:i.map(r=>r.label||r.name||"").filter(Boolean)};}function lr(e,t){var a,s;if("fieldId"in t){if((((a=e.config)==null?void 0:a.groupByColumns)??[]).some(i=>i.id===t.fieldId))return"dimension";if((((s=e.config)==null?void 0:s.metricColumns)??[]).some(i=>i.id===t.fieldId))return"measure";}}function ci(e,t,a="label"){var n,d;if(!t)return null;if("column"in t)return t.column;const i=[...(((n=e.config)==null?void 0:n.groupByColumns)??[]),...(((d=e.config)==null?void 0:d.metricColumns)??[])].find(c=>c.id===t.fieldId);return(a==="name"?(i==null?void 0:i.name)||(i==null?void 0:i.label):(i==null?void 0:i.label)||(i==null?void 0:i.name))||t.fieldId;}function cr(e,t,a,s,i){var d;const n={};if(t!=null&&t.draft&&t.draft.html!==((d=e==null?void 0:e.draft)==null?void 0:d.html)&&(n.code=(a==null?void 0:a.name)??"the visual"),i.settings&&a){const c=Object.keys(i.settings).filter(u=>{var r,m;return((r=e==null?void 0:e.settings)==null?void 0:r[u])!==((m=t==null?void 0:t.settings)==null?void 0:m[u]);}).map(u=>{var $,g,S;const r=($=a.settings)==null?void 0:$[u],m=((g=t==null?void 0:t.settings)==null?void 0:g[u])??(r==null?void 0:r.default),b=(r==null?void 0:r.type)==="select"?((S=r.options.find(x=>x.value===m))==null?void 0:S.label)??String(m):(r==null?void 0:r.type)==="boolean"?m?"on":"off":String(m);return{label:(r==null?void 0:r.label)??u,value:b};});c.length&&(n.settings=c);}if(i.slots&&a){const c=Object.keys(i.slots).filter(u=>{var r,m;return JSON.stringify((r=e==null?void 0:e.slots)==null?void 0:r[u])!==JSON.stringify((m=t==null?void 0:t.slots)==null?void 0:m[u]);}).map(u=>{var r,m;return{label:((r=a.slots.find(b=>b.id===u))==null?void 0:r.label)??u,field:ci(s,(m=t==null?void 0:t.slots)==null?void 0:m[u])};});c.length&&(n.slots=c);}return n;}function $s(e,t){var n;const a=e.customVisual??{},s=((n=li(e))==null?void 0:n.name)??(a.extensionId?t==null?void 0:t[a.extensionId]:void 0),i=Object.fromEntries(Object.entries(a.slots??{}).map(([d,c])=>[d,ci(e,c,"name")??""]));return{...(s?{name:s}:{}),...(a.extensionId?{extensionId:a.extensionId}:{}),...(a.version?{version:a.version}:{}),...(a.draft?{unsaved:!0}:{}),...(Object.keys(i).length?{slots:i}:{}),...(a.settings&&Object.keys(a.settings).length?{settings:{...a.settings}}:{})};}function ur(e,t,a){var n;const s=[],i=Ce(e);for(const[d,c]of t){const u=i.findFilterInput({inputId:d});if(!u)continue;const r=(n=qs(e.defaultInputValues??{},u.input,{}))==null?void 0:n.comparisonSelection;if((r==null?void 0:r.mode)!=="period")continue;const m=Sa(r.spec);if(m.kind!=="shift")continue;const b=Lt({dashboard:e,target:{kind:"dashboardInput",input:u.input,scope:{}},calendar:a}).value,$=Oi(b,a);if(!$||!la(m,$))continue;const g=ti(m,$);s.push({code:"invalid_change",message:`"${u.input.label}"'s default comparison: ${g.message}`,path:`changes[${c.changeIndex}]${c.statedComparison?".defaultComparison":""}`,fix:c.statedComparison?g.fix:`${g.fix} Or keep this default and set defaultComparison to one that clears it.`});}return s;}function ws(e){return Ia(e).map(t=>t.kind==="variable"?{id:t.id,title:`the variable ${t.variable.name}`,card:t.card}:{id:t.id,title:t.card.title||"Untitled",card:t.card});}const Is=e=>Ei(e).flatMap((t,a)=>(t==null?void 0:t.kind)==="shift"?[{index:a,spec:t}]:[]);async function fr(e){const t=[],a=new Map(ws(e.before).map(s=>[s.id,s]));for(const s of ws(e.after)){const i=Is(s.card);if(!i.length)continue;const n=(await e.readComparisonDates({card:s.card,dashboard:e.after})).window;if(!n)continue;const d=i.filter(m=>la(m.spec,n));if(!d.length)continue;const c=a.get(s.id),u=c?(await e.readComparisonDates({card:c.card,dashboard:e.before})).window:void 0,r=c?Is(c.card):[];for(const m of d){const b=r.find(S=>S.index===m.index);if(b&&u&&JSON.stringify(b.spec)===JSON.stringify(m.spec)&&la(b.spec,u))continue;const g=ti(m.spec,n);t.push({code:"comparison_overlaps_date_window",message:`"${s.title}": ${g.message}`,path:`changes[${e.changeIndexOf(s.id)}]`,fix:`${g.fix} Or keep it: it shows when a viewer picks a range it clears.`,details:{measureIndex:m.index}});}}return t;}function hr(e){const[t]=Ni({inputs:[{id:`reach-${e.id}`,kind:"filter",label:e.title||e.column,variableName:"reach",scope:{kind:"allSheets"},runtimeScope:"shared",filter:e,definitionOrigin:"embedded"}],dashboardFilters:[]});return t;}function mr(e,t,a){const s=Xe(e,t,a);return{...s,reached:Ls(s.reach)};}const pr={global_date:"The date filter for the whole report can't be changed through the MCP. Change it in the editor; removing or excluding it works.",not_semantic:"This filter reads a database table, not a dataset, so it can't be changed through the MCP. Change it in the editor; removing or excluding it works.",scope_not_expressible:"This filter applies to chosen cards rather than whole sheets, so it can't be changed through the MCP. Change it in the editor; removing or excluding it works."};function gr(e,t,a={}){var c;const s=Ce(e),i=hn(t.scope),n=new Set(Ia(e).map(u=>u.id)),d={reaches:[],excluded:[.../* @__PURE__ */new Set([...(((c=t.application)==null?void 0:c.cards)??[]).filter(u=>u.kind==="excluded").map(u=>u.cardId),...i.filter(u=>n.has(u))])],notReached:[]};if(t.filter.kind==="global-date"){const u=new Set(d.excluded);return d.reaches=[...qi(e,t.filter).filter(({card:r})=>!u.has(r.id)&&Le(r)).map(({card:r})=>r.id),...s.reachedVariables({inputId:t.id}).map(r=>r.variableId).filter(r=>!u.has(r))],d;}for(const u of s.reachedCards({inputId:t.id})){const r=Xe(t,u.card,a),m=r.reach,b=()=>{const $=Le(u.card);return{cardId:u.cardId,title:u.card.title??"",...(($==null?void 0:$.kind)==="semantic"?{datasetName:$.datasetName}:{})};};if(Ls(m)){d.reaches.push(u.cardId);continue;}switch(m){case"blocked":case"ambiguous":(d.blocked??(d.blocked=[])).push({cardId:u.cardId,title:u.card.title??"",reason:m});break;case"relationship":(d.relationshipPending??(d.relationshipPending=[])).push(b());break;case"sqlTemplate":(d.sqlPending??(d.sqlPending=[])).push({cardId:u.cardId,title:u.card.title??""});break;case"excluded":break;case"notApplicable":Le(u.card)&&d.notReached.push({...b(),...(r.reason?{reason:r.reason}:{})});break;default:{const $=m;throw new Error(`Unhandled filter reach ${String($)}`);}}}for(const u of s.reachedVariables({inputId:t.id})){const r=_a(e,u.variableId);if((r==null?void 0:r.kind)!=="variable")continue;const m=Xe(t,r.card,a),b=Le(r.card),$={cardId:r.id,title:r.variable.name,...((b==null?void 0:b.kind)==="semantic"?{datasetName:b.datasetName}:{})};switch(m.reach){case"bound":case"automatic":case"sql":case"relationshipApplied":d.reaches.push(r.id);break;case"blocked":case"ambiguous":(d.blocked??(d.blocked=[])).push({cardId:r.id,title:r.variable.name,reason:m.reach});break;case"relationship":(d.relationshipPending??(d.relationshipPending=[])).push($);break;case"sqlTemplate":(d.sqlPending??(d.sqlPending=[])).push({cardId:r.id,title:r.variable.name});break;case"excluded":break;case"notApplicable":d.notReached.push({...$,...(m.reason?{reason:m.reason}:{})});break;}}return d;}function br(e,t){var i;const a=t.scope;if(a.kind==="allSheets"){if((i=a.sheetKinds)!=null&&i.length&&!a.sheetKinds.includes("dashboard"))return;const n=mn(a);return{sheetIds:"all",...(n.length?{exceptSheetIds:[...n]}:{}),...(pn(a)?{includesDocumentSheets:!0}:{})};}if(a.kind!=="sheets")return;const s=[...Ca(e).values()].filter(n=>Zs(t,n));return{sheetIds:s.filter(n=>n.sheetKind==="dashboard").map(n=>n.sheetId),...(s.some(n=>n.sheetKind==="document")?{includesDocumentSheets:!0}:{})};}function Et(e,t){return e??{tz:"UTC",weekStart:1,anchor:{iso:t??"1970-01-01T00:00:00.000Z"}};}function ui(e,t,a,s){var g,S,x;const{input:i}=t,n=gr(e,i,s),d=(A,I)=>({filterId:i.id,label:i.label,editable:!1,kind:I,notEditable:{reason:A,message:pr[A]},reaches:n.reaches,excluded:n.excluded,...(n.blocked?{blocked:n.blocked}:{}),...(n.relationshipPending?{relationshipPending:n.relationshipPending}:{}),...(n.sqlPending?{sqlPending:n.sqlPending}:{})});if(i.filter.kind==="global-date")return d("global_date","global_date");const c=Pi(i.filter).filter(A=>A.kind==="semantic");if(c.length!==1||c[0].kind!=="semantic")return d("not_semantic","field");const u=br(e,i);if(!u||t.origin!=="embeddedInput")return d("scope_not_expressible","field");const r=((g=i.filter.fieldMeta)==null?void 0:g.name)??((S=i.filter.column)==null?void 0:S.split(".").pop())??"",m=Lt({dashboard:e,target:{kind:"dashboardInput",input:i,scope:{}},calendar:Et(a,void 0)}).value,b=fi(i.filter,m),$=(x=qs(e.defaultInputValues??{},i,{}))==null?void 0:x.comparisonSelection;return{filterId:i.id,label:i.label,editable:!0,domainId:c[0].domainId,datasetName:c[0].datasetName,field:r,...b,...(($==null?void 0:$.mode)==="period"?{defaultComparison:Sa($.spec)}:{}),...u,...n};}function fi(e,t){var r;const a=Mt(e.dataType),s=na(e),i=s==="range"&&t&&Li(t.operation)?{operation:t.operation,values:(t.values??[]).map(Number)}:void 0,n=a||(r=t==null?void 0:t.values)==null?void 0:r.filter(m=>["string","number","boolean"].includes(typeof m)),d=xa(t&&"relativeMeta"in t?t.relativeMeta:void 0),c=a?d:void 0,u=c?vr(t==null?void 0:t.operation,c)??Ln(c,{use:"filterDefault",columnHasTime:Vs(e)==="datetime"},"defaultPeriod"):void 0;return{selection:e.type==="single"?"single":"multiple",...(s?{showAs:s}:{}),...((s!=="range"||!i)&&n!=null&&n.length?{defaultValues:n}:{}),...(i?{defaultCondition:Mi(i)}:{}),...(c?{defaultPeriod:c}:{}),...(u?{defaultPeriodReadOnly:u}:{}),...(a?{datePicker:e.dateSelectionMode==="day"?"day":e.dateSelectionMode==="months"?"month":"range"}:{})};}function yr(e,t){return(e.inlineFilters??[]).map(a=>{var s,i,n;return{filterId:a.id,label:a.title,field:((s=a.fieldMeta)==null?void 0:s.name)??((i=a.column)==null?void 0:i.split(".").pop())??"",...((n=a.fieldMeta)!=null&&n.entityName?{datasetName:a.fieldMeta.entityName}:{}),...fi(a,Ms(a,Et(t,void 0)))};});}function vr(e,t){const a=typeof e=="string"?qn(e,t):void 0;return a?{reason:"point_default",message:`The default is "${a}", a condition set in the editor. It stays while defaultPeriod is left out.`,fix:"Send a range window as defaultPeriod to replace it.",suggestions:[]}:void 0;}function Ta(e,t,a){return Ce(e).inputs.map(s=>ui(e,s,t,a));}function je(e,t,a,s){const i=Ce(e).findFilterInput({inputId:t});return i?ui(e,i,a,s):void 0;}const Fa=e=>`${e.domainId}\0${e.datasetName}`;function hi(e,t){var s;if(((s=e.source)==null?void 0:s.kind)==="semantic")return{domainId:e.source.domainId,datasetName:e.source.datasetName};if(!t)return;const a=ga(e);return{domainId:t.domainId,datasetName:a||t.datasetName};}function mi(e){const t=Le(e);return(t==null?void 0:t.kind)==="semantic"?{domainId:t.domainId,datasetName:t.datasetName}:void 0;}function pi(e){const t=e.config,a=t==null?void 0:t.matrix;return a?[...[...a.spec.rows,...a.spec.columns].map(s=>({ref:{kind:"matrixLevel",levelId:s.id},field:s.field})),...a.spec.measures.flatMap(s=>s.kind==="aggregate"?[{ref:{kind:"matrixMeasure",measureId:s.id},field:s.field}]:[])]:[...((t==null?void 0:t.groupByColumns)??[]),...((t==null?void 0:t.metricColumns)??[]),...((t==null?void 0:t.detailColumns)??[])].map(s=>({ref:{kind:"field",fieldId:s.id},field:s}));}function $r(e){const t=mi(e),a=/* @__PURE__ */new Map();for(const{field:s}of pi(e)){const i=hi(s,t);i&&a.set(Fa(i),i);}return[...a.values()];}function wr(e,t,a){if(!a)return;const s=is(t),i=pi(e).find(c=>is(c.ref)===s);if(!i)return;const n=hi(i.field,mi(e)),d=n?a[Fa(n)]:void 0;return d?qt(d,i.field.name,n.datasetName):void 0;}const ca=["orientation","stack","donut","columnOrder","totals","dataLabels","legend","axes","comparisonDisplay","trend","trendGrain","seeRecords","columnFilters","tableSearch"],gi=[...ca,"inheritComparison"],Ir={orientation:"orientation",stack:"stacking",donut:"donut hole",columnOrder:"column order",totals:"total row",dataLabels:"data labels",legend:"legend",axes:"axes",comparisonDisplay:"comparison display",trend:"trend under its value",trendGrain:"trend grain",seeRecords:"records to see",columnFilters:"column filters",tableSearch:"search"},_r={x:"xAxisConfig",y:"yAxisConfig"},zt={x:"horizontal",y:"vertical"};function Cr(e){const t=`${e.sql?"SQL ":""}${Qi(e.type)}`;return`${/^[aeiou]/i.test(t)?"an":"a"} ${t}`;}function bi(e,t,a){const s=Object.fromEntries(Object.entries(t).filter(([i,n])=>n!==void 0&&!a.includes(i)));return Object.keys(s).length?{op:"card.update",cardId:e.cardRef,...s}:void 0;}const Sr="Set comparison on each measure in query.measures: { kind: 'inherit' } follows the Date filter, { kind: 'off' } shows none, a shift or target is the measure's own.";function xr(e){var a;const t=[];return e.inheritComparison!==void 0&&t.push({path:"inheritComparison",message:"Whether a measure follows the Date filter is its own comparison now, not a card setting."}),((a=e.comparisonDisplay)==null?void 0:a.show)!==void 0&&t.push({path:"comparisonDisplay.show",message:"Whether a measure shows a comparison is its own comparison now, not a card setting."}),t;}function kr(e,t){const{inheritComparison:a,comparisonDisplay:s,...i}=t,{show:n,...d}=s??{},c=Object.keys(d).length?{...i,comparisonDisplay:d}:i;return bi(e,c,[]);}function Tr(e,t,a,s,i){var S,x,A,I,F,y,M,R,O,Y,D,E,B,W;const n=xr(a);for(const{path:N,message:J}of n)i.push(ae("invalid_change",{message:`${J} (${te(e.title)})`,path:`${s.path}.${N}`,fix:Sr,suggestedChange:kr(s,a)}));if(n.length)return{};const d=ca.filter(N=>a[N]!==void 0);if(!d.length)return{};const c=ca.filter(N=>t.settings.has(N)),u=d.filter(N=>!t.settings.has(N));for(const N of u)i.push(ae("setting_not_for_card",{message:`${te(e.title)} is ${Cr(t)}, which has no ${Ir[N]}.`,path:`${s.path}.${N}`,fix:c.length?`Leave out ${N}; this card takes ${c.join(", ")}.`:`Leave out ${N}.`,allowed:c,suggestedChange:bi(s,a,u)}));if(u.length)return{};const r={},m=((S=ze(e))==null?void 0:S.properties)??{},b={...m,...(a.orientation!==void 0?{orientation:a.orientation}:{}),...(a.stack!==void 0?{stack:a.stack}:{}),...(a.donut!==void 0?{donut:a.donut}:{})};["orientation","stack","donut"].some(N=>b[N]!==m[N])&&(r.variant=Vi(t.type,b));const $=r.variant?Bi(e,r.variant):e,g=ba($);if(a.columnOrder){const N=ji(e,t,a.columnOrder,s,i);N&&(r.columnOrder=N);}if(a.totals){const N=Ki(e,t,a.totals,((x=g.totals)==null?void 0:x.row)??!1,s,i);N&&(r.totals=N);}if(a.dataLabels){const N={};a.dataLabels.show!==Wi($)&&(N.show=a.dataLabels.show);const J=a.dataLabels.format;if(J===null&&(A=g.dataLabels)!=null&&A.format&&(N.format=null),J){const P=Fr(e,t,J,`${s.path}.dataLabels.format`,i);P&&!Be(P,(I=g.dataLabels)==null?void 0:I.format)&&(N.format=P);}Object.keys(N).length&&(r.dataLabels=N);}if(a.legend){const N={};a.legend.show!==((F=g.legend)==null?void 0:F.show)&&(N.show=a.legend.show),a.legend.position!==void 0&&a.legend.position!==((y=g.legend)==null?void 0:y.position)&&(N.position=a.legend.position),Object.keys(N).length&&(r.legend=N);}if(a.axes){const N=Ui($.type,$.preferences),J={};for(const P of["x","y"]){const k=a.axes[P];if(!k)continue;const V=Ar(e,P,k,((M=g.axes)==null?void 0:M[P])??{},P===N,`${s.path}.axes.${P}`,i);V&&(J[_r[P]]=V);}Object.keys(J).length&&(r.axes=J);}if(a.comparisonDisplay){const N=(R=e.preferences)==null?void 0:R.comparisonPresentation,J={},{mode:P,precision:k}=a.comparisonDisplay;P!==void 0&&P!==((N==null?void 0:N.displayMode)??"difference")&&(J.mode=P),k!==void 0&&k!==((N==null?void 0:N.precision)??null)&&(J.precision=k),Object.keys(J).length&&(r.comparisonDisplay=J);}if(a.seeRecords!==void 0&&a.seeRecords!==(e.seeRecords!==!1)&&(r.seeRecords=a.seeRecords),a.columnFilters!==void 0&&a.columnFilters!==(((Y=(O=e.preferences)==null?void 0:O.tablePrefs)==null?void 0:Y.allowViewerColumnFilters)!==!1)&&(r.columnFilters=a.columnFilters),a.tableSearch!==void 0&&a.tableSearch!==(((E=(D=e.preferences)==null?void 0:D.tablePrefs)==null?void 0:E.allowViewerSearch)!==!1)&&(r.tableSearch=a.tableSearch),a.trend!==void 0&&a.trend!==(((B=e.config)==null?void 0:B.kpiBand)==="trend")&&(r.trend=a.trend),a.trendGrain!==void 0){const N=Gi(e.config);N?i.push(ae("value_invalid",{message:`${te(e.title)} draws its trend by its Trend By${N.granularity?`, by ${N.granularity}`:""}, so it takes no grain of its own.`,path:`${s.path}.trendGrain`,fix:"Change the Trend By's timeGrain in its query, or remove the Trend By to set a grain here.",allowed:[]})):a.trendGrain!==(((W=e.config)==null?void 0:W.kpiTrendGrain)??"automatic")&&(r.trendGrain=a.trendGrain==="automatic"?null:a.trendGrain);}return r;}function Fr(e,t,a,s,i){const n=String(a.type),d=Hi("cartesian","number"),c=pt(n),u=c==null?void 0:c.safeParse(a);if(!d.includes(n)||!(u!=null&&u.success)){const m=u&&!u.success?u.error.issues[0]:void 0;i.push(ae("format_invalid",{message:d.includes(n)?`That format for the values on ${te(e.title)} isn't valid: ${(m==null?void 0:m.message)??"invalid"}.`:`The values on ${te(e.title)} are numbers, so they can't take a ${n.replace("_"," ")} format.`,path:s,fix:"Send a whole number, currency, percent, scientific or duration format.",allowed:d.includes(n)?ut(n):[...d]}));return;}const r=Bs({surface:t.type==="pie"?"pie":"cartesian",value:"number",rawValueKinds:[]},u.data);if(!r.ok){i.push(ae("format_invalid",{message:`${te(e.title)} can't draw that format on its values: ${r.reason}.`,path:s}));return;}return u.data;}function Ar(e,t,a,s,i,n,d){const c={};a.title!==void 0&&(a.title!==null&&!a.title.trim()?d.push(ae("value_invalid",{message:"An axis title can't be empty.",path:`${n}.title`,fix:"Send a title, or null for none."})):(a.title??void 0)!==s.title&&(c.title=a.title));const u=["min","max"].filter(r=>a[r]!==void 0&&a[r]!==null);if(!i&&u.length){const r=zt[t==="x"?"y":"x"];d.push(ae("setting_not_for_card",{message:`${te(e.title)}'s ${zt[t]} axis lists categories; set a range on its ${r} axis.`,path:`${n}.${u[0]}`,allowed:["title"]}));return;}if(i){for(const b of["min","max"]){const $=a[b];if($!==void 0){if($!==null&&!Number.isFinite($)){d.push(ae("value_invalid",{message:`An axis ${b} must be a number.`,path:`${n}.${b}`}));return;}($??void 0)!==s[b]&&(c[b]=$);}}const r=a.min!==void 0?a.min:s.min,m=a.max!==void 0?a.max:s.max;if(typeof r=="number"&&typeof m=="number"&&r>m){d.push(ae("value_invalid",{message:`The ${zt[t]} axis of ${te(e.title)} can't start at ${r} and end at ${m}.`,path:n,fix:"Send a min no greater than the max."}));return;}}return Object.keys(c).length?c:void 0;}function _s(e,t,a,s,i){const n=i==="date"&&s.role==="dimension";return ae("setting_not_for_card",{message:i==="text"?`${t} on ${te(e.title)} shows its text as it is; text formats apply on a Matrix only.`:i==="category"?`${t} labels the categories of ${te(e.title)}, which a chart shows as the query returns them; format it on a table or a Matrix.`:`${te(e.title)} shows ${t}, ${yi(s)}, without a format of its own; this card type doesn't apply one.`,path:a,...(n?{fix:`Group ${t} by day, week, month, quarter or year to format its dates.`}:{})});}const yi=e=>e.granularity?`a date grouped by ${e.granularity}`:e.dataType?`a ${e.dataType.toLowerCase()}`:"this column";function Ke(e,t){return`${e}.columns[${JSON.stringify(t)}]`;}function st(e,t,a,s){const{[s]:i,...n}=a;return Object.keys(n).length?{op:"card.update",cardId:e.cardRef,columns:{[t]:n}}:void 0;}function Dr(e,t,a){const{hidden:s,width:i,...n}=a;return Object.keys(n).length?{op:"card.update",cardId:e.cardRef,columns:{[t]:n}}:void 0;}function wt(e,t,a){return{op:"card.update",cardId:e.cardRef,columns:{[t]:{format:a}}};}function Rr(e,t,a,s,i,n,d){var r;const c=i.label;if(c===void 0||c===a.label)return;const u=`${Ke(n.path,s)}.label`;if(!t.settings.has("columns.label")||!a.labelKey){d.push(ae("setting_not_for_card",{message:t.sql?`${te(e.title)}'s column ${s} takes its header from the query; rename it in the SQL.`:`${s} on ${te(e.title)} takes no header of its own.`,path:u,allowed:["hidden","width","format"].filter(m=>m!=="hidden"||t.settings.has("columns.hidden")),suggestedChange:st(n,s,i,"label")}));return;}if(c===null){const m=((r=wr(e,a.ref,n.catalogs))==null?void 0:r.label)||a.field||a.label;return a.labelInherited&&a.label===m?void 0:{key:a.labelKey,label:m,origin:"semantic"};}if(!c.trim()){d.push(ae("value_invalid",{message:"A column header can't be empty.",path:u,fix:"Send a header, or null to use the model's."}));return;}return{key:a.labelKey,label:c};}function Or(e,t,a,s,i,n,d){var D,E,B;const c=`${Ke(n.path,s)}.format`;if(!t.settings.has("columns.format")){d.push(ae("setting_not_for_card",{message:`${te(e.title)} takes no column formats.`,path:c}));return;}const u=a.ref,r=((D=n.modelFormats)==null?void 0:D.status)==="read"?n.modelFormats.formats:void 0,m=u.kind==="matrixLevel"?r==null?void 0:r[u.levelId]:u.kind==="matrixMeasure"?r==null?void 0:r[u.measureId]:void 0,b=$n({card:e,column:u,...(r?{modelFormats:r}:{}),...(m?{catalogFormat:m}:{})}),$=b.source==="override"?b.format:void 0;if(i===null)return $?null:void 0;if($&&Be(i,$))return;const g=eo(e,t,a,n.sqlResultColumns),S=g.value,x=to(g);if(x.length===0){d.push(_s(e,s,c,a,S));return;}const A=!("type"in i)||i.type===void 0;if(A&&!b.format){const W=x[0];d.push(ae("format_invalid",{message:((E=n.modelFormats)==null?void 0:E.status)==="unavailable"?`${s} on ${te(e.title)} may follow its model's format, which couldn't be read; state the whole format with its type.`:`${s} on ${te(e.title)} has no format to change; state the whole format with its type.`,path:c,fix:"Add `type` to the format.",allowed:ut(W),suggestedChange:wt(n,s,{type:W,...i})}));return;}const I=A?{...b.format,...i}:i,F=String(I.type);if(!x.includes(F)){d.push(F==="string"?_s(e,s,`${c}.type`,a,"text"):ae("format_invalid",{message:S==="result"?`${s} on ${te(e.title)} comes straight from the query, so it can't take a ${F.replace("_"," ")} format.`:`${s} on ${te(e.title)} is ${yi(a)}, so it can't take a ${F.replace("_"," ")} format.`,path:`${c}.type`,allowed:[...x]}));return;}const y=pt(F),M=y==null?void 0:y.safeParse(I);if(!y||!(M!=null&&M.success)){const W=M&&!M.success?M.error.issues[0]:void 0;d.push(ae("format_invalid",{message:y?(W==null?void 0:W.code)==="unrecognized_keys"?`A ${F} format has no ${W.keys.join(", ")}.`:`That format for ${s} isn't valid: ${(W==null?void 0:W.message)??"invalid"}.`:`${JSON.stringify(F)} isn't a format type.`,path:c,fix:Mr(F),allowed:y?ut(F):[...Kn],...(b.format?{suggestedChange:wt(n,s,b.format)}:{})}));return;}const R=M.data;if(R.type==="temporal_bucket"&&a.granularity){const W=a.granularity,N=hs(R,W);if(!N.ok){const J=ao(W)?so(W).map(P=>({type:"temporal_bucket",presentation:{mode:"pattern",pattern:P}})):Wn.map(P=>({type:"temporal_bucket",presentation:{mode:"preset",preset:P}})).filter(P=>hs(P,W).ok);d.push(ae("date_finer_than_grain",{message:`${s} on ${te(e.title)} is grouped by ${a.granularity}, which that date format doesn't fit: ${N.message}`,path:c,allowed:J.map(({presentation:P})=>P.mode==="pattern"?P.pattern:P.mode==="preset"?P.preset:"auto"),...(J[0]?{suggestedChange:wt(n,s,J[0])}:{})}));return;}}if(R.type==="date"){const W=i,N=b.format??{},J=Object.keys(W).filter(P=>!Kt.includes(P)&&!Be(W[P],N[P]));if(J.length){const P=Object.fromEntries(Object.entries(R).filter(([k])=>!J.includes(k)));d.push(ae("format_invalid",{message:`A date format set here takes a pattern or a preset; it doesn't set ${J.join(", ")}.`,path:c,fix:`Leave out ${J.join(", ")}.`,allowed:Kt.filter(k=>k!=="type"),suggestedChange:wt(n,s,P)}));return;}}const O=R.type==="date"&&g.surface==="detail_table"&&g.value==="date"?io(a,R,(B=e.dataSource)==null?void 0:B.connectionType):void 0;if(O){d.push(ae("format_invalid",O.reason==="connection"?{message:`${te(e.title)} can't show ${s} that way: ${O.message}`,path:c,fix:"Write the pattern in uppercase letters (YYYY MM DD HH mm ss) with no dialect, for example 'DD MMM YYYY' or 'HH:mm'.",allowed:Kt.filter(W=>W!=="type")}:{message:`${te(e.title)} can't draw that format on ${s}: ${O.message}.`,path:c,fix:"Change the format to one the column can show.",allowed:ut(F)}));return;}const Y=Bs(g,R);if(!Y.ok){d.push(ae("format_invalid",{message:`${te(e.title)} can't draw that format on ${s}: ${Y.reason}.`,path:c,fix:"Change the format to one the column can show.",allowed:ut(F)}));return;}return $&&Be($,R)?void 0:R;}function Er(e,t,a,s,i,n,d){var x,A;const c=i.polarity;if(c===void 0)return;const u=`${Ke(n.path,s)}.polarity`,r=a.ref;if(!(t.settings.has("columns.polarity")&&(r.kind==="sqlKpiValue"||r.kind==="field"&&a.role==="measure"))){d.push(ae("setting_not_for_card",{message:a.role==="measure"||a.role==="value"?`${te(e.title)} shows no comparison, so ${s} has no favorable direction.`:`${s} on ${te(e.title)} isn't a measure, so it has no favorable direction.`,path:u,fix:"Leave out polarity.",suggestedChange:st(n,s,i,"polarity")}));return;}const b=r.kind==="field"?(A=(x=e.config)==null?void 0:x.metricColumns)==null?void 0:A.find(I=>I.id===r.fieldId):void 0,$=r.kind==="sqlKpiValue"?js(e):void 0,g=r.kind==="sqlKpiValue"?($==null?void 0:$.source)==="sql"&&$.polarity!==bs?$.polarity:void 0:b==null?void 0:b.comparisonPolarity,S=b==null?void 0:b.semanticComparisonPolarity;if(c===null)return g?null:void 0;if(S&&c!==S){d.push(ae("polarity_set_by_model",{message:`The model says ${s} is ${S.replace(/_/g," ")}; a card can't say otherwise.`,path:u,fix:"Change it in the model, or leave polarity out.",allowed:[S],suggestedChange:st(n,s,i,"polarity")}));return;}return c===(S??g??bs)?void 0:c;}function Nr(e,t,a,s,i,n,d,c){if(i.pinned===void 0||i.pinned===((n==null?void 0:n.pinned)===!0))return;const u=t.pivoted&&a.role!=="dimension";if(!t.settings.has("columns.pinned")||a.columnId===void 0||u){c.push(ae("setting_not_for_card",{message:u?`${te(e.title)} has pivot columns, so only its row columns can be pinned; ${s} isn't one.`:`${te(e.title)} pins no columns; pinned columns are for tables and detail tables.`,path:`${Ke(d.path,s)}.pinned`,suggestedChange:st(d,s,i,"pinned")}));return;}return i.pinned;}function Pr(e,t,a,s,i,n,d,c,u){const r=i.display;if(r===void 0)return;const m=`${Ke(c.path,s)}.display`;if(!t.settings.has("columns.display")||a.resultKey===void 0){u.push(ae("setting_not_for_card",{message:`${te(e.title)} has no Display as; it is for table and detail table columns.`,path:m,suggestedChange:st(c,s,i,"display")}));return;}if(r===null)return d===void 0?void 0:null;if(!(d!==void 0&&Be(Xt(r),d))){if(!oo(a.role)){u.push(ae("setting_not_for_card",{message:`Display as is for text columns; ${s} is a measure, which shows as a number.`,path:`${m}.as`,suggestedChange:st(c,s,i,"display")}));return;}if(r.as==="monospace"&&r.lines!==void 0&&!no.includes(r.lines)){u.push(ae("value_invalid",{message:`${s} can show 2, 3 or 5 lines of monospace, or all of them.`,path:`${m}.lines`,fix:'Send lines: 2, 3, 5 or "all".'}));return;}if(r.as==="status"){const b=Object.entries(r.colors??{}).find(([,$])=>!In.includes($));if(b||r.shape!==void 0&&r.shape!=="pill"&&r.shape!=="dot"){u.push(ae("value_invalid",{message:b?`${b[0]} in ${s} can be green, red, amber, blue or grey.`:`${s} shows its status as a pill or a dot.`,path:b?`${m}.colors`:`${m}.shape`,fix:b?"Send one of green, red, amber, blue or grey for each value.":'Send shape "pill" or "dot".'}));return;}}if(r.as==="link"){if(typeof r.address!="string"||!r.address.trim()){u.push(ae("invalid_change",{message:`A link in ${s} needs an address.`,path:`${m}.address`,fix:"Send an address, such as https://example.com/runs/{value}."}));return;}const b=A=>{var I;return(I=n.find(F=>F.resultKey===A||F.name===A))==null?void 0:I.resultKey;},$=r.label&&r.label!=="value"&&"column"in r.label?r.label.column:void 0,g=[...ro(r.address),...($!==void 0?[$]:[])].find(A=>b(A)===void 0);if(g!==void 0){u.push(ae("column_not_found",{message:`${te(e.title)} has no column ${g} for the link in ${s}.`,path:$===g?`${m}.label.column`:`${m}.address`,allowed:n.flatMap(A=>A.resultKey!==void 0?[A.name]:[])}));return;}const S=r.address.replace(/{([^}]+)}/g,(A,I)=>I==="value"?A:`{${b(I)}}`),x={...r,address:S,...($!==void 0?{label:{column:b($)}}:{})};return Be(Xt(x),d)?void 0:x;}return Be(Xt(r),d)?void 0:r;}}function Xt(e){return lo(co(void 0,e));}function qr(e,t,a,s,i,n,d,c){var m,b,$;if(i.hidden===void 0&&i.width===void 0)return{};const u=Ke(d.path,s);if(!t.settings.has("columns.hidden")||a.resultKey===void 0){const g=t.pivoted&&a.role==="measure";return c.push(ae("setting_not_for_card",{message:g?`${s} on ${te(e.title)} has a column for each pivot value; hide or size them in the editor.`:`${te(e.title)} has no hidden columns or column widths; those are for tables.`,path:`${u}.${i.hidden!==void 0?"hidden":"width"}`,allowed:g?["label","format"]:["label","format"].filter(S=>t.settings.has(`columns.${S}`)),suggestedChange:Dr(d,s,i)})),{};}const r={};if(i.hidden!==void 0&&i.hidden!==((n==null?void 0:n.hidden)===!0)&&(r.hidden=i.hidden),i.width!==void 0&&i.width!==((n==null?void 0:n.width)??null)){const{minSize:g,maxSize:S}=Zi(($=(b=(m=e.preferences)==null?void 0:m.tablePrefs)==null?void 0:b.columnSettingsMap)==null?void 0:$[a.resultKey]);i.width!==null&&(!Number.isFinite(i.width)||i.width<g||i.width>S)?c.push(ae("value_invalid",{message:`${s} on ${te(e.title)} can be ${g} to ${S} pixels wide.`,path:`${u}.width`,fix:`Send a width from ${g} to ${S} pixels, or null for automatic.`})):r.width=i.width;}return r;}function Lr(e,t,a){var A,I,F,y,M;const{columns:s={},...i}=t.settings??{},n=[],d=gi.some(R=>i[R]!==void 0),c=!!((I=(A=t.highlights)==null?void 0:A.add)!=null&&I.length||(y=(F=t.highlights)==null?void 0:F.remove)!=null&&y.length);if(!Object.keys(s).length&&!d&&!c)return{ok:!0,labels:[],settings:null,warnings:[]};const u=Yi(e);if(!u)return{ok:!1,problems:[ae("setting_not_for_card",{message:`${te(e.title)} takes no card settings through this tool.`,path:a.path})]};const r=Tr(e,u,i,a,n),m=Ji(e,u,a.sqlResultColumns),b=c?zi(e,u,m,t.highlights,a,n):void 0,$=ba(e),g=[],S=[];for(const[R,O]of Object.entries(s)){const Y=Xi(m,R,{path:Ke(a.path,R),cardTitle:te(e.title)});if(!Y.ok){n.push(Y.problem);continue;}const D=Y.column;if(D.sqlName==="inferred"){n.push(ae("columns_unavailable",{message:`${te(e.title)}'s columns weren't read from its query, so ${R} can't be checked.`,path:Ke(a.path,R),fix:"Check that the card runs and returns rows, then propose again."}));continue;}const E=Rr(e,u,D,R,O,a,n);E&&g.push(E);const B=qr(e,u,D,R,O,$.columns[D.name],a,n),W=O.format!==void 0?Or(e,u,D,R,O.format,a,n):void 0,N=Er(e,u,D,R,O,a,n),J=Nr(e,u,D,R,O,$.columns[D.name],a,n),P=Pr(e,u,D,R,O,m,(M=$.columns[D.name])==null?void 0:M.display,a,n),k={column:D.ref,...B,...(J!==void 0?{pinned:J}:{}),...(P!==void 0?{display:P}:{}),...(W!==void 0?{format:W}:{}),...(N!==void 0?{polarity:N}:{})};Object.keys(k).length>1&&S.push(k);}if(n.length)return{ok:!1,problems:n};const x={...r,...(S.length?{columns:S}:{}),...(b?{highlights:b}:{})};return{ok:!0,labels:g,settings:Object.keys(x).length?x:null,warnings:[]};}function Mr(e){const t=pt(e),a=t&&t===pt("number")?os.number:e==="temporal_bucket"||e==="date"?os[e]:void 0;return a?`Send a stored format: ${a}.`:"Send the format in the stored shape the outline shows.";}const Vr=/* @__PURE__ */new Set([">",">=","<","<=","between"]),We=e=>JSON.stringify([...(e??[])].map(t=>JSON.stringify(t)).sort()),Cs=e=>e.charAt(0).toLowerCase()+e.slice(1);function Br(e){var a,s,i;const t=e.type==="matrixTable"?(s=(a=e.config)==null?void 0:a.matrix)==null?void 0:s.spec.filters:(i=e.config)==null?void 0:i.filters;return(t==null?void 0:t.conditions)??[];}function Zt(e){var u,r,m;const t=Ve(e,{sql:!0});if(!t.editable)return{readable:!1,editorOnly:!0,held:[],signatures:[]};if("sql"in t.query)return{readable:!1,held:[],signatures:[]};const a=t.query,s=a.datasetName,i=Br(e),n=[],d=[];for(const b of a.filters??[]){const $=De(b.field,s),g=b.operator==="="?"in":b.operator;d.push(`${$}|${g}|${b.scope??"row"}|${We(b.values)}`);const S=(u=i.find(I=>I.id===b.id))==null?void 0:u.field;if(!S||b.scope==="aggregate"||b.field==="__count"||Mt(S.dataType))continue;const x=S.label||S.name,A=b.values??[];if((b.operator==="="||b.operator==="in")&&A.length)n.push({kind:"values",values:A,fieldKey:$,field:S,fieldLabel:x,valueWords:A.map(String).join(" or ")});else if(Vr.has(b.operator)&&A.length&&A.every(I=>typeof I=="number")){const I=Cs(((r=uo(b.operator))==null?void 0:r.label)??b.operator);n.push({kind:"number",operator:b.operator,values:A,fieldKey:$,field:S,fieldLabel:x,valueWords:b.operator==="between"?`between ${A[0]} and ${A[1]}`:`${I} ${A[0]}`});}}let c;if(a.timeWindow&&a.dateField){const b=De(a.dateField,s),$=a.timeWindow;c={key:b,window:$};const g=(m=i.find(x=>x.relativeMeta))==null?void 0:m.field,S=g&&ni($,{use:"filterDefault",columnHasTime:Ks(g)}).ok;g&&S&&n.push({kind:"window",window:$,fieldKey:b,field:g,fieldLabel:g.label||g.name,valueWords:Cs(Mn($).label)});}return{readable:!0,held:n,signatures:d,...(c?{window:c}:{})};}function ea(e,t){return e.fieldKey!==t.fieldKey||e.kind!==t.kind?!1:e.kind==="values"&&t.kind==="values"?We(e.values)===We(t.values):e.kind==="number"&&t.kind==="number"?e.operator===t.operator&&JSON.stringify(e.values)===JSON.stringify(t.values):e.kind==="window"&&t.kind==="window"?Vt(e.window,t.window):!1;}function jr(e){return e.kind==="window"?`${e.fieldKey}|window|${JSON.stringify(e.window)}`:e.kind==="number"?`${e.fieldKey}|${e.operator}|${JSON.stringify(e.values)}`:`${e.fieldKey}|values|${We(e.values)}`;}function Kr(e,t){const a=[...e.signatures].sort(),s=[...t.signatures].sort();return a.length!==s.length||a.some((i,n)=>i!==s[n])||!!e.window!=!!t.window?!1:!e.window||e.window.key===t.window.key&&Vt(e.window.window,t.window.window);}function Ss(e,t){var a,s,i;return t.kind==="window"?!!e.defaultPeriod&&Vt(e.defaultPeriod,t.window):t.kind==="values"?(a=e.defaultValues)!=null&&a.length?We(e.defaultValues)===We(t.values):t.values.length===1&&((s=e.defaultCondition)==null?void 0:s.operator)==="="&&JSON.stringify(e.defaultCondition.values)===JSON.stringify(t.values):((i=e.defaultCondition)==null?void 0:i.operator)===t.operator&&JSON.stringify(e.defaultCondition.values??[])===JSON.stringify(t.values);}function xs(e,t,a){var u;const s=je(e,t,void 0,a);if(!s)return;const i=s.editable?[s.defaultValues,s.defaultCondition,s.defaultPeriod]:[],n=(u=Ce(e).findFilterInput({inputId:t}))==null?void 0:u.input,d=new Map(_e(e).map(r=>[r.cardId,r.card])),c=[...s.reaches].sort().map(r=>{const m=d.get(r);if(!n||!m)return r;const b=va(n,m),$=(b.status==="bound"||b.status==="automatic")&&b.target.kind==="field"?b.target.field:void 0;return`${r}:${b.status}:${$?Rt({name:$.name,source:$.source}):""}`;});return JSON.stringify([i,c]);}function Wr({before:e,after:t,operations:a,context:s,reachOptions:i}){var P;const n=(t.sheets??[]).filter(k=>!ya(k)),d=k=>{var V,U;return((U=(V=t.sheets)==null?void 0:V.find(j=>j.id===k))==null?void 0:U.title)||"this sheet";},c=/* @__PURE__ */new Map();for(const k of _e(t))c.set(k.cardId,{cardId:k.cardId,sheetId:k.sheetId,card:k.card});const u=new Map(_e(e).map(k=>[k.cardId,k.card])),r=/* @__PURE__ */new Map(),m=k=>{let V=r.get(k);return V||(V=Zt(c.get(k).card),r.set(k,V)),V;},b=/* @__PURE__ */new Map(),$=(k,V)=>{V!==void 0&&!b.has(k)&&b.set(k,V);},g=/* @__PURE__ */new Set();for(const k of a){const V=k.op==="card.add"?(P=k.frame.cards[0])==null?void 0:P.id:k.op==="card.update"?k.cardId:void 0;if(!V||!c.has(V))continue;const U=u.get(V);(!U||!Kr(Zt(U),m(V)))&&(g.add(V),$(V,k.changeIndex));}const S=/* @__PURE__ */new Map();for(const k of a){const V=k.op==="filter.add"?k.input.id:k.op==="filter.update"||k.op==="filter.bind"||k.op==="filter.exclude"?k.filterId:void 0;V&&!S.has(V)&&S.set(V,k.changeIndex);}for(const[k,V]of S){const U=je(t,k,void 0,i);if(!(!U||xs(t,k,i)===xs(e,k,i)))for(const j of U.reaches)c.has(j)&&(g.add(j),$(j,V));}if(!g.size)return[];const x=Ta(t,void 0,i),A=Ce(t),I=(k,V,U)=>{var be,Te,$e,we;const j=(be=A.findFilterInput({inputId:k.filterId}))==null?void 0:be.input,ne=(Te=c.get(U))==null?void 0:Te.card;if(j&&ne){const Fe=va(j,ne);if((Fe.status==="bound"||Fe.status==="automatic")&&Fe.target.kind==="field"){const{name:re,source:Ue}=Fe.target.field;return Rt({name:re,source:Ue})===V.fieldKey;}}if(k.editable)return Rt({name:k.field,source:{kind:"semantic",domainId:k.domainId,datasetName:k.datasetName}})===V.fieldKey;if(k.kind!=="field")return!1;const X=($e=A.findFilterInput({inputId:k.filterId}))==null?void 0:$e.input.filter;if(!X)return!1;const ge={name:X.column??((we=X.fieldMeta)==null?void 0:we.name)??"",fieldMeta:X.fieldMeta};return Qn(ge,{name:V.field.name,qualifiedFieldName:V.field.qualifiedFieldName});},F=(k,V,U)=>{var ge,be;let j=0;const ne=ii({field:V.field,dataSource:U.dataSource,connectionId:((ge=U.dataSource)==null?void 0:ge.connectionId)??U.connectionId,connectionType:(be=U.dataSource)==null?void 0:be.connectionType,scope:{kind:"sheets",sheetIds:[k]},dashboard:t,createId:()=>`shared-condition-reach-${++j}`,label:V.fieldLabel}),X=mt(t,[{op:"filter.add",input:ne}],s);return X.ok?je(X.dashboard,ne.id,void 0,i):void 0;},y=new Set(x.filter(k=>!k.editable&&k.kind==="global_date").flatMap(k=>k.reaches)),M=k=>y.has(k)?m(k).held.filter(V=>V.kind!=="window"):m(k).held,R=(k,V)=>{if(V.kind==="number")return!0;const U=A.findFilterInput({inputId:k.filterId});if(!U)return!1;const j={...U.input.filter};V.kind==="window"?Object.assign(j,St(j,V.window)):j.defaultValues=V.values;const ne=mt(t,[{op:"filter.update",filterId:k.filterId,settings:{definition:j,values:{defaultChanged:!0,target:{}}}}],s);if(!ne.ok)return!1;const X=Ce(ne.dashboard).findFilterInput({inputId:k.filterId});if(!X)return!1;const ge=Lt({dashboard:ne.dashboard,target:{kind:"dashboardInput",input:X.input,scope:{}},calendar:s.calendar}).value;if(V.kind==="window"){const be=xa(ge&&"relativeMeta"in ge?ge.relativeMeta:void 0);return!!be&&ri(be,V.window);}return!!ge&&We(ge.values)===We(V.values);},O=k=>Me(k.map(V=>{var U;return qe((U=c.get(V))==null?void 0:U.card.title);})),Y=k=>k===1?"doesn't":"don't",D=(k,V)=>k.reaches.flatMap(U=>{if(c.has(U))return[];const j=_a(t,U);return(j==null?void 0:j.kind)!=="variable"?[]:Zt(j.card).held.some(X=>ea(X,V))?[]:[`the {{${j.variable.name}}} value`];}),E=/* @__PURE__ */new Map(),B=/* @__PURE__ */new Set(),W=[],N=/* @__PURE__ */new Set(),J=/* @__PURE__ */new Set();for(const k of n){const V=[...c.values()].filter(U=>U.sheetId===k.id).map(U=>U.cardId);for(const U of V)if(g.has(U))for(const j of M(U)){const ne=`${k.id}|${j.fieldKey}`;if(J.has(ne))continue;const X=x.find(z=>z.reaches.some(se=>{var xe;return((xe=c.get(se))==null?void 0:xe.sheetId)===k.id&&I(z,j,se);}));if(V.filter(z=>M(z).some(se=>ea(se,j))).length<2)continue;const be=`${ne}|${jr(j)}|${U}`;if(B.has(be))continue;B.add(be);const Te=`${ne}`;!X&&!E.has(Te)&&E.set(Te,F(k.id,j,c.get(U).card));const $e=X??E.get(Te);if(!$e)continue;const we=$e.reaches.filter(z=>{var se;return((se=c.get(z))==null?void 0:se.sheetId)===k.id;}),Fe=z=>!X||I(X,j,z),re=we.filter(z=>Fe(z)&&M(z).some(se=>ea(se,j))),Ue=we.filter(z=>m(z).readable&&!re.includes(z));if(re.length<2||Ue.length||!re.includes(U))continue;J.add(ne);for(const z of re)N.add(`${z}|${j.fieldKey}`);const Se=j.fieldLabel,Ge=`${Se} ${j.kind==="window"?"in":"is"} ${j.valueWords}`,Oe=[...we.filter(z=>!re.includes(z)&&!m(z).editorOnly).map(z=>{var se;return qe((se=c.get(z))==null?void 0:se.card.title);}),...D($e,j)],yt=we.filter(z=>m(z).editorOnly),ot=`changes[${re.map(z=>b.get(z)).find(z=>z!==void 0)??0}]`,nt={cards:re.map(z=>{var se;return{cardId:z,title:((se=c.get(z))==null?void 0:se.card.title)??""};})};if(!X){const z=[...($e.relationshipPending??[]),...($e.sqlPending??[])].map(se=>se.cardId).filter(se=>{var xe;return((xe=c.get(se))==null?void 0:xe.sheetId)===k.id;});W.push({code:"repeated_card_condition",message:[`"${Ge}" is on every card of ${k.title||"this sheet"} that a filter on ${Se} would reach: ${O(re)}.`,...(Oe.length?[`A filter on ${Se} would also narrow ${Me(Oe)}, which ${Y(Oe.length)} have it today.`]:[]),...(z.length?[`It may also narrow ${O(z)}, as their SQL or the domain's relationships decide.`]:[]),...(yt.length?[`It would also narrow ${O(yt)}, which can only be changed in the editor: any condition of their own stays until changed there.`]:[])].join(" "),path:ot,fix:`To let viewers change it in one place, add one filter on ${Se} with that default for ${k.title||"this sheet"} (filter.add with datasetName "${ga(j.field)}" and field "${j.field.name}"), remove it from each card's query, keeping their other conditions (card.update), and exclude the cards that shouldn't change (filter.exclude). Keep it on the cards if each needs its own.`,details:nt});continue;}const ye=X.label,Ee=[...X.reaches.filter(z=>c.has(z)&&!re.includes(z)).map(z=>{const se=c.get(z);return se.sheetId===k.id?qe(se.card.title):`${qe(se.card.title)} (${d(se.sheetId)})`;}),...D(X,j)],Ne=X.editable&&Ss(X,j),rt=X.editable&&X.datePicker!=="range"?X.datePicker:void 0,dt=X.editable&&!Ne&&j.kind==="number"&&X.showAs==="list"?"range":X.editable&&!Ne&&j.kind==="values"&&X.showAs==="range"?"list":void 0,Bt=X.editable?dt==="range"?`show the "${ye}" filter as a range with that default (filter.update with showAs "range" and defaultCondition), so viewers pick a condition instead of ticking values, and remove it from each card's query, keeping their other conditions (card.update).`:dt==="list"?`show the "${ye}" filter as a list with that default (filter.update with showAs "list" and defaultValues), so viewers tick values instead of picking a condition, and remove it from each card's query, keeping their other conditions (card.update).`:!Ne&&!R(X,j)?rt&&j.kind==="window"?`ask the user to make the "${ye}" filter a date range in the editor and give it that default (its ${rt==="day"?"date picker takes one day":"month picker takes one whole month"}); then remove it from each card's query, keeping their other conditions (card.update).`:`ask the user to set the "${ye}" filter's default in the editor (it wouldn't load with that default as it is); then remove it from each card's query, keeping their other conditions (card.update).`:Ne?`remove it from each card's query, keeping their other conditions (card.update): "${ye}" already has it as its default.`:`set the "${ye}" filter's default to it (filter.update) and remove it from each card's query, keeping their other conditions (card.update).`:`ask the user to set the "${ye}" filter's default in the editor; then remove it from each card's query, keeping their other conditions (card.update).`,Qe=[...(X.relationshipPending??[]),...(X.sqlPending??[])].filter(z=>!re.includes(z.cardId)).map(z=>{const se=c.get(z.cardId);return se&&se.sheetId!==k.id?`${qe(z.title)} (${d(se.sheetId)})`:qe(z.title);}),tt=!Ne&&(Ee.length>0||Qe.length>0);W.push({code:"repeated_card_condition",message:[`"${Ge}" is on every card of ${k.title||"this sheet"} that the dashboard's "${ye}" filter reaches: ${O(re)}.`,...(tt&&Ee.length?[`"${ye}" also reaches ${Me(Ee)}, which ${Y(Ee.length)} have it: a new default changes what ${Ee.length===1?"it shows":"they show"} by default.`]:[]),...(tt&&Qe.length?[`A new default may also change what ${Me(Qe)} ${Qe.length===1?"shows":"show"}, as ${Qe.length===1?"its":"their"} SQL or the domain's relationships decide.`]:[])].join(" "),path:ot,fix:[`To let viewers change it in one place, ${Bt}`,tt?`Keeping it on the cards is valid when the user didn't ask to change what the other cards show; excluding a card from "${ye}" (filter.exclude) stops it following the viewer's choice, so it doesn't keep the card as it was.`:"Keep it on the cards if each needs its own."].join(" "),details:nt});}}for(const k of g){const V=c.get(k);if(!(!V||!n.some(U=>U.id===V.sheetId))){for(const U of M(k))if(!N.has(`${k}|${U.fieldKey}`))for(const j of x){if(!j.editable||!j.reaches.includes(k)||!I(j,U,k)||!Ss(j,U))continue;const ne=V.card.title||"Untitled",X=U.kind==="window"?`window (${U.valueWords})`:`condition (${U.fieldLabel} is ${U.valueWords})`;W.push({code:"card_condition_repeats_filter_default",message:`"${ne}" keeps its own ${X}, the default of the dashboard's "${j.label}" filter, so it won't follow the filter when a viewer changes it.`,path:`changes[${b.get(k)??0}]`,fix:`To follow the filter, remove it from the card's query (card.update): the card shows what the viewer picks. To keep both, change nothing: the card shows only what both its own condition and "${j.label}" allow, and nothing when they don't overlap. To make the card independent, exclude it from "${j.label}" (filter.exclude): it always shows ${U.valueWords}.`,details:{cards:[{cardId:k,title:V.card.title??""}],filterId:j.filterId}});}}}return W;}function Ur(e,t,a,s,i,n,d=[]){var y,M,R,O,Y,D;const c=n??Ve(e,{sql:!0,calculations:!1,calculatedFields:d});if(!c.editable)return[c.message];const u=c.query,r=t;if("sql"in t)return r.sql===u.sql&&r.connectionId===u.connectionId?[]:["the SQL"];const m=(s==null?void 0:s.source.kind)==="semantic"?Ve({id:e.id,title:e.title,type:s.type,dataSource:s.source.dataSource,connectionId:s.source.connectionId,config:s.config},{sql:!0,calculations:!1,calculatedFields:d}):void 0;if(m&&!m.editable)return["the compiled query"];const b=m!=null&&m.editable?m.query:void 0,$=String(r.datasetName??""),g=[],S=E=>De(E,$),x=(E,B,W)=>{const N=B??[],J=W??[];(N.length!==J.length||N.some((P,k)=>S(P)!==S(J[k])))&&g.push(E);};for(const E of["domainId","datasetName"])r[E]!==u[E]&&g.push(E);if(x("measures",r.measures,u.measures),x("columns",r.columns,u.columns),a||c.matrix){const E=W=>new Set(((W==null?void 0:W.columns)??[]).map(S)),B=(W,N)=>(W??[]).filter(J=>!E(N).has(S(J)));x("dimensions",B(r.dimensions,a),B(u.dimensions,c.matrix)),x("matrix.columns",a==null?void 0:a.columns,(y=c.matrix)==null?void 0:y.columns);}else x("dimensions",r.dimensions,u.dimensions);const A=r.timeWindow!==void 0&&!r.timeGrain,I=A&&u.timeWindow===void 0?void 0:A&&r.dateField===void 0?b==null?void 0:b.dateField:r.dateField;I!==void 0&&(u.dateField===void 0||S(I)!==S(u.dateField))&&g.push("dateField"),r.timeGrain!==void 0&&r.timeGrain!==u.timeGrain&&g.push("timeGrain");const F=(M=e.config)!=null&&M.matrix?e.config.matrix.spec.measures.map(E=>E.kind==="aggregate"?{aggregate:E.aggregate}:{}):((R=e.config)==null?void 0:R.metricColumns)??[];(r.measures??[]).forEach((E,B)=>{const W=E&&typeof E=="object"?E.aggregate:void 0;W&&gs(F[B]??{})!==W&&g.push(`the aggregate of measures[${B}]`);});for(const{key:E,label:B}of ht(t))fo(e,E)!==B&&g.push(`the label "${B}"`);if(!i||i.aspects.includes("filters")){const E=r.filters??[];let B=u.filters??[];const W=r.timeWindow,N=u.timeWindow,J=(P,k)=>{const V=U=>JSON.stringify((U??[]).map(String));return S(P.field)===S(k.field)&&P.operator===k.operator&&(P.scope??"row")===(k.scope??"row")&&(typeof P.field=="object"?P.field.aggregate:void 0)===(typeof k.field=="object"?k.field.aggregate:void 0)&&(P.values===void 0||V(P.values)===V(k.values));};if(W&&!N){const P=((b==null?void 0:b.filters)??[]).filter(k=>!(b!=null&&b.timeWindow)&&!E.some(V=>J(V,k)));(!P.length||P.some(k=>!B.some(V=>J(k,V))))&&g.push("timeWindow"),B=B.filter(k=>!P.some(V=>J(V,k)));}else W?Vt(r.timeWindow,u.timeWindow)||g.push("timeWindow"):N&&g.push("timeWindow");(E.length!==B.length||E.some((P,k)=>!J(P,B[k])))&&g.push("filters");}if(r.orderBy!==void 0){const E=r.orderBy,B=(Y=(O=e.config)==null?void 0:O.sortByColumns)==null?void 0:Y[0],W=B&&ho(e.config??{},B),N=E.field&&typeof E.field=="object"?E.field.aggregate:void 0;(!B||!W||B.direction!==E.direction||S(E.field)!==mo(W.name,ga(W))||N!==void 0&&gs(W)!==N)&&g.push("orderBy");}return r.limit!==void 0&&((D=e.config)==null?void 0:D.rowLimit)!==r.limit&&g.push("limit"),g;}function ua(e){const t=Ia({variables:[e]})[0];return t?Le(t.card):void 0;}function vi(e,t){const a=ua(e);return(a==null?void 0:a.kind)==="sql"?t.sql?{editable:!0,source:a}:{editable:!1,reason:"needs_sql_access",message:`${e.name} is written in SQL, which needs SQL access.`,source:a}:(a==null?void 0:a.kind)==="physical"?{editable:!1,reason:"table_source",message:`${e.name} reads a table or view, so it is changed in the editor.`,source:a}:{editable:!0,source:a};}const $i=e=>typeof e=="string"?{kind:e}:e;function Dt(e,t){const a=e.variables??[];return a.find(s=>s.name===t)??a.find(s=>s.id===t);}function Gr(e,t,a,s){var d;const i=Dt(e,t);i||s.problem(wi(e,t,a));const n=vi(i,{sql:!0});return((d=n.source)==null?void 0:d.kind)==="sql"&&s.need(a),n.editable||s.problem({code:"variable_not_editable",message:n.message,path:a,fix:"Tell the user to change it in the editor; removing it works.",details:{reason:n.reason}}),i;}function wi(e,t,a){const s=(e.variables??[]).map(i=>i.name);return{code:"variable_unknown",message:`No variable named ${t} on this dashboard.`,path:a,fix:`Add one with variable.add${s.length?`, or use one of: ${s.join(", ")}`:""}.`,details:{available:s}};}function Ii(e,t){return e.map(a=>({code:a.code==="nameTaken"||a.code==="nameReserved"?"variable_name_taken":a.code==="inUse"?"variable_in_use":"invalid_change",message:a.message,path:a.path?`${t}.${a.path.split(".")[0]}`:t,fix:a.fix,...(a.places?{details:{places:a.places}}:{})}));}async function ks(e,t,a){var y,M;const{problem:s,need:i,services:n}=a,{path:d,query:c}=e,u=$i(e.get),r={id:e.id,name:e.name,...(e.label?{label:e.label}:{}),...(e.presentation?{presentation:e.presentation}:{}),...(e.emptyText?{emptyText:e.emptyText}:{}),sortDirection:"asc",sql:""};if("sql"in c)return i(`${d}.query`),u.kind!=="only"&&u.kind!=="first"&&s({code:"invalid_change",message:"A SQL variable takes the only row or the first row of its result.",path:`${d}.get`,fix:'Send get: "only" or "first", or write the aggregate or the list in the SQL itself.'}),F(At({...r,mode:"sql",connectionId:c.connectionId,sql:c.sql,get:u.kind},t));const m=await n.loadCardSource({domainId:c.domainId,datasetName:c.datasetName});m!=null&&m.dataSource||s({code:"variable_source_unreachable",message:`The dataset ${c.datasetName} isn't in the domain ${c.domainId} or in this project.`,path:`${d}.query.datasetName`,fix:"List the domain's datasets with semaphor_list_datasets and name one of them."});const b=m.fields;for(const R of Ws({...c,measures:c.measures??[]}))s({...R,path:`${d}.${R.path}`});const $=(R,O)=>{const Y=da(R),D=vo(R,c.datasetName);D.toLowerCase()!==c.datasetName.toLowerCase()&&s({code:"field_not_found",message:`A variable reads one dataset: "${Y}" names ${D}, not ${c.datasetName}.`,path:O,fix:`Name a field of ${c.datasetName}, or set datasetName to ${D} and read its field.`});const E=qt(b,Y,c.datasetName);return E||s({code:"field_not_found",message:`"${Y}" isn't a field of ${c.datasetName}.`,path:O,fix:"Use one of details.available, or read semaphor_get_dataset_schema.",details:{available:b.slice(0,20).map(B=>B.name)}}),E;},g=c.measures??[],S=c.dimensions??[],x={...r,mode:"data",dataSource:m.dataSource,connectionId:m.connectionId,get:"only",...((y=c.filters)!=null&&y.length?{conditions:await Hr(c,n,d,a.refuseAll)}:{})};if(u.kind==="aggregate"){(g.length!==1||S.length)&&s({code:"invalid_change",message:"An aggregate reads one measure and no dimension.",path:`${d}.query`,fix:`Send measures: [{ name, aggregate }] alone; for one field's value use get: "only", "first" or "list" with dimensions: [field].`}),c.orderBy&&s({code:"invalid_change",message:"An aggregate is one value, so it has no order.",path:`${d}.query.orderBy`,fix:"Leave out orderBy."});const R=$(g[0],`${d}.query.measures[0]`),O=typeof g[0]=="string"?void 0:g[0].aggregate,Y=Hn(R).filter(B=>ys(B.value)),D=O??(Gt(R)?"calculation":Yn(R));if(!ys(D)||!Y.some(B=>B.value===D)){const B=Y.map(W=>W.value);s({code:"invalid_change",message:O?`${O} isn't an aggregate ${R.label||R.name} takes.`:`${R.label||R.name} needs its aggregate.`,path:`${d}.query.measures[0]`,fix:Gt(R)?`${R.label||R.name} aggregates itself: send it without an aggregate.`:`Send { name: "${R.name}", aggregate } with one of: ${B.join(", ")}.`,allowed:B});}const E=Qr(g[0],{...x,field:R,get:D},`${d}.query.measures[0].comparison`,s);return F(At({...x,field:R,get:D,...(E?{comparison:E}:{})},t));}(S.length!==1||g.length)&&s({code:"invalid_change",message:`The ${u.kind==="only"?"only value":u.kind==="first"?"first value":"list"} reads one dimension; a measure's one value is get: "aggregate".`,path:`${d}.query`,fix:"Send dimensions: [field] and no measures; order the first value or the list with orderBy."});const A=$(S[0],`${d}.query.dimensions[0]`);Gt(A)&&s({code:"invalid_change",message:`${A.label||A.name} is an aggregate calculation, so it has one value, not rows.`,path:`${d}.query.dimensions[0]`,fix:`Send get: "aggregate" with measures: ["${A.name}"].`}),u.kind==="only"&&c.orderBy&&s({code:"invalid_change",message:"The only value has no order: it shows when exactly one row matches.",path:`${d}.query.orderBy`,fix:'Leave out orderBy, or send get: "first" to take the first by this order.'});let I;if(c.orderBy&&u.kind!=="only"){const R=c.orderBy.field;typeof R!="string"&&R.aggregate&&s({code:"invalid_change",message:"The order names a field, not an aggregate: the first value is ordered by the latest (desc) or earliest (asc) of that field per value.",path:`${d}.query.orderBy.field`,fix:'Send orderBy: { field: "<field>", direction }.'}),I=$(R,`${d}.query.orderBy.field`);}return F(At({...x,field:A,get:u.kind,...(I?{sortField:I}:{}),sortDirection:((M=c.orderBy)==null?void 0:M.direction)??"asc",...(u.kind==="list"&&u.limit?{listLimit:u.limit}:{}),...(u.kind==="list"&&u.separator!==void 0?{listSeparator:u.separator}:{})},t));function F(R){const O={...R,name:e.name},Y=$a(O,t);return Y.length&&a.refuseAll(Ii(Y,d)),O;}}function Qr(e,t,a,s){var n,d;const i=typeof e=="string"?void 0:e.comparison;if(!(!i||i.kind==="off"))return(i.kind==="inherit"||i.kind==="target"||i.kind==="metric")&&s({code:"invalid_change",message:i.kind==="inherit"?"A variable doesn't follow the Date filter's comparison; it names its own.":`A variable compares with an earlier period, not ${i.kind==="target"?"a target":"another metric"}.`,path:a,fix:"Send comparison: { kind: 'shift', unit: 'period' } (the period before) or { kind: 'shift', unit: 'year' } (last year); put a target in the words, or on a KPI card."}),zn(t)||s({code:"invalid_change",message:`${((n=t.field)==null?void 0:n.label)||((d=t.field)==null?void 0:d.name)} with ${String(t.get)} isn't a number, so it has no comparison.`,path:a,fix:"Compare a count, or a numeric field's total, average, lowest or highest; leave comparison out here."}),$o(i);}async function Hr(e,t,a,s){var n;const i=await t.compileCardQuery({query:{domainId:e.domainId,datasetName:e.datasetName,measures:["__count"],filters:e.filters},chartType:"table"});return i.ok?((n=i.part.config)==null?void 0:n.filters)??null:s(i.problems.map(d=>({...d,path:d.path?`${a}.query.${d.path}`:`${a}.query.filters`})));}function Yr(e,t,a,s,i){const n=$i(t),d=Jn(e);n.kind==="aggregate"&&e.get.kind!=="aggregate"&&s.problem({code:"invalid_change",message:`${e.name} reads a field's rows; an aggregate needs its measure.`,path:`${i}.get`,fix:'Send query with measures: [{ name, aggregate }] and get: "aggregate".'}),n.kind!=="aggregate"&&e.get.kind==="aggregate"&&s.problem({code:"invalid_change",message:`${e.name} is an aggregate; a value, the first or a list reads a dimension.`,path:`${i}.get`,fix:"Send query with dimensions: [field] and the get."}),d.mode==="sql"&&n.kind!=="only"&&n.kind!=="first"&&s.problem({code:"invalid_change",message:"A SQL variable takes the only row or the first row of its result.",path:`${i}.get`,fix:'Send get: "only" or "first", or write the list in the SQL itself.'});const c=At({...d,...(n.kind==="aggregate"?{}:{get:n.kind}),...(n.kind==="list"?{listLimit:n.limit??d.listLimit,listSeparator:n.separator??d.listSeparator}:{listLimit:void 0,listSeparator:void 0})},a);return{query:c.query,get:c.get};}function Jr(e,t){const a=ei(e).filter(({ref:d})=>d.source==="data"&&d.variableId===t),s=d=>{var c;return`"${((c=(e.sheets??[]).find(u=>u.id===d))==null?void 0:c.title)??d}"`;},i=_e(e);return{words:[...new Set(a.map(({place:d,where:c})=>{var u;return c.kind==="card"?`the card "${((u=i.find(r=>r.cardId===c.cardId))==null?void 0:u.card.title)??c.cardId}"`:c.kind==="section"?`a text section of ${s(d.sheetId)}`:`the ${c.kind} of ${s(d.sheetId)}`;}))].join(", "),places:a};}function zr(e,t,a,s,i){const{problem:n}=i;(!ya(a)||!a.document)&&n({code:"invalid_change",message:`"${a.title??a.id}" is not a Document sheet.`,path:`${s}.sheetId`,fix:"Name a Document sheet; a grid sheet's words are its text cards (card.update with text)."}),e.text===void 0&&e.style===void 0&&n({code:"invalid_change",message:"This document.text.update has neither text nor style.",path:s,fix:"Send text (the words), style ({ size, align }) or both."});const d=a.document,c=e.target;let u,r;if("sectionId"in c){const x=d.sections.find(A=>A.id===c.sectionId);x||n({code:"invalid_change",message:`No section ${c.sectionId} on "${a.title}".`,path:`${s}.target.sectionId`,fix:"Use a section id from the outline's textSections."}),x.type!=="text"&&n({code:"invalid_change",message:`Section ${c.sectionId} is a ${x.type} section, not text.`,path:`${s}.target.sectionId`,fix:"Name one of the outline's textSections."}),u=x.content,r=x.style;}else{const{region:x,role:A}=c;ms[x].includes(A)||n({code:"invalid_change",message:`The ${x} has ${x==="header"?"a title and a metadata line":"a note and a page info line"}, not a ${A} line.`,path:`${s}.target.role`,fix:`Send role: ${ms[x].map(F=>`"${F}"`).join(" or ")}.`}),e.style!==void 0&&!po(A)&&n({code:"invalid_change",message:`The footer's ${A==="pageInfo"?"page info":A} line has no size or alignment; only the header's title and metadata lines and text sections do.`,path:`${s}.style`,fix:"Leave style out for a footer line."});const I=d[x]?_n(d[x].blocks,A):void 0;u=(I==null?void 0:I.content)??[],r=I==null?void 0:I.style;}const m=e.style!==void 0?go(e.style):void 0,b=!m||Object.entries(m).every(([x,A])=>(r==null?void 0:r[x])===A);let $;if(e.text!==void 0){const x={kind:"document",sheetId:a.id},A={catalog:ra({dashboard:t,place:x}),inputs:t.inputs,variables:t.variables},I=JSON.stringify(Ot(u,A));if(JSON.stringify(bo(e.text))!==I){const F=yo(e.text,u,{dashboard:t,place:x,path:`${s}.text`,links:!0});F.ok||i.refuseAll(F.problems);const y=F.content;JSON.stringify(Ot(y,A))!==I&&($=y);}}const g={...($!==void 0?{content:$}:{}),...(m!==void 0&&!b?{style:m}:{})};return{edit:"sectionId"in c?{type:"updateText",sectionId:c.sectionId,...g}:{type:"updateRegionText",region:c.region,role:c.role,...g},unchanged:$===void 0&&b};}const Xr={matrix:"A Matrix",pie:"A pie chart",detail_table:"A detail table",text:"A text card"};class Ae extends Error{}const Ts="A text card takes title, description and text.",ta=e=>e.cards.some(t=>{var a,s;return((a=t.customCardPreferences)==null?void 0:a.visualType)==="multiple"||!!((s=t.customCardPreferences)!=null&&s.dataInputCardIds);}),fa=e=>(e??"").trim().toLowerCase(),bt=To,ha={measures:Lo,records:qo,sql:Po},It={measures:"a measures query (measures, with optional dimensions)",records:"a records query (columns)",sql:"a SQL query"};function _i(e,t){return t.path.reduce((a,s)=>typeof s=="number"?`${a}[${s}]`:`${a}.${s}`,e);}const Zr={max:zo,what:"A proposal",fix:"Split the changes into several proposals."},ed=e=>e==="needs_sql_access"?"Ask for SQL access.":e==="empty"?"Send a complete query: domainId, datasetName and measures (or columns), or connectionId and sql.":e==="not_expressible"||e==="type_not_supported"?Ys:"Tell the user to change it in the editor.",td=/* @__PURE__ */new Set(["op","cardId","title","description","customVisual"]);function ad(e,t){var i;if(t===((i=ze(e))==null?void 0:i.type))return!0;const a=kt(t);if(a===e.type)return!0;const s=Gs(e,a,{catalogLoading:!0});return s.status==="unchanged"||s.status==="changed"&&s.queryKept;}function sd(e){const t=Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null)),a=bt(t);return!!(a&&ha[a].safeParse(t).success);}const id=["string","number","boolean","date","datetime"],od=e=>id.find(t=>t===e);function Fs(e){return!e.description||e.description.trim()===`Calculated field: ${(e.label??e.name).trim()}`;}async function Ol(e,t,a){return Ci(e,t,a,{limit:Zr});}async function Ci(e,t,a,s){var Pa,qa,La,Ma,Va,Ba,ja,Ka,Wa,Ua,Ga,Qa,Ha,Ya,Ja,za,Xa,Za,es;const i=[],n=[],d=[],c=[],u=/* @__PURE__ */new Set(),r=[],m=/* @__PURE__ */new Map(),b={calendar:a.calendar},$=a.relationshipReach?{relationshipReach:a.relationshipReach}:{};let g=e,S,x=0,A=0;const{limit:I}=s;if(t.length>I.max)return{ok:!1,problems:[{code:"too_many_changes",message:`${I.what} takes at most ${I.max} changes; this one has ${t.length}.`,path:"changes",fix:I.fix}]};const F=[];if(t.forEach((l,o)=>{const f=wo.safeParse(l);if(f.success){F.push(f.data);return;}for(const h of f.error.issues){const p=Vn(h.message);i.push({code:"invalid_change",message:(p==null?void 0:p.message)??h.message,path:_i(`changes[${o}]`,h),fix:(p==null?void 0:p.fix)??"Send the change in the shape the tool schema gives."});}}),i.length)return{ok:!1,problems:i};const y=l=>{throw i.push(l),new Ae();},M=l=>{a.capabilities.sql||y({code:"capability_required",message:"This change creates, reads or changes a SQL card or variable, which needs SQL access.",path:l,fix:"Use a measures or records query (a semantic dataset for a variable), or ask an administrator for SQL access."}),u.add("sql");},R=l=>l==="table_sheet_no_card"||l==="table_sheet_extra_card"||l==="table_sheet_card_type"||l==="table_sheet_layout",O=(l,o)=>{const f=mt(g,[l],b);if(f.ok)g=f.dashboard,d.push(l);else{const h=R(f.failedAt.code)?f.failedAt.code:"invalid_change";y({code:h,message:f.failedAt.message,path:o,...(f.failedAt.fix?{fix:f.failedAt.fix}:{})});}},Y=async l=>{var oe,le,de,ie,fe,He;const{cardId:o,index:f,path:h}=l,{settings:p={},highlights:v}=l.request,w=p.columns&&Object.keys(p.columns).length?p.columns:void 0,_=Object.entries(p).some(([ee,ke])=>ee!=="columns"&&ke!==void 0),T=!!((oe=v==null?void 0:v.add)!=null&&oe.length);if(!w&&!_&&!T&&!((le=v==null?void 0:v.remove)!=null&&le.length))return null;const C=he(g,o).card,L=Object.values(w??{}).some(ee=>ee.label===null),K=Object.values(w??{}).some(ee=>ee.format!==void 0&&ee.format!==null),q={};if(L&&!((de=C.sql)!=null&&de.trim()))for(const ee of $r(C)){const ke=await a.loadCardSource(ee);ke&&(q[Fa(ee)]=ke.fields);}let Q;if(K&&!((ie=C.sql)!=null&&ie.trim())){const ee=a.readModelFormats?await a.readModelFormats({card:C}):null;Q=ee?{status:"read",formats:ee}:{status:"unavailable"};}const Z=!!((fe=p.columnOrder)!=null&&fe.length);let G;if((w||T||Z)&&(He=C.sql)!=null&&He.trim()&&C.type!=="kpi"){const ee=a.readSqlResultColumns?await a.readSqlResultColumns({cardId:o,dashboard:g}):null;ee||y({code:"columns_unavailable",message:w||Z?`"${C.title||"Untitled"}" couldn't be run to read its columns, so their names can't be checked.`:`"${C.title||"Untitled"}" couldn't be run to read its columns, so the highlight's column can't be checked.`,path:w?`${h}.columns`:Z?`${h}.columnOrder`:`${h}.column`,fix:"Check that the card runs and returns rows, then propose again."}),G=ee;}const H=Lr(C,{settings:{...p,...(w?{columns:w}:{columns:void 0})},...(v?{highlights:v}:{})},{path:h,cardRef:l.cardRef,catalogs:q,newId:a.newId,...(Q?{modelFormats:Q}:{}),...(G?{sqlResultColumns:G}:{})});if(!H.ok)throw i.push(...H.problems),new Ae();for(const ee of H.labels){const ke=l.queryLabels.find(Pe=>Ft(Pe.key,ee.key)&&Pe.label!==ee.label);ke&&y({code:"value_invalid",message:`Two labels are stated for one column of "${C.title||"Untitled"}": "${ke.label}" in the query and "${ee.label}" in columns.`,path:`${h}.columns`,fix:"State the label once."});}return n.push(...H.warnings),H.labels.length&&ls(C,H.labels).changed.length&&O({op:"card.update",cardId:o,update:{kind:"relabel",labels:H.labels},changeIndex:f},`${h}.columns`),H.settings&&O({op:"card.update",cardId:o,update:{kind:"settings",settings:H.settings},changeIndex:f},w?`${h}.columns`:h),H.settings;},D=/* @__PURE__ */new Set(),E=(l,o,f)=>{var T;const h=he(g,l);h||y({code:"card_not_editable",message:"Cards in Document sections are changed in the editor.",path:`${o}.cardId`,fix:"Tell the user to change it in the editor.",details:{reason:"document_section"}});const p=Ve(h.card,{sql:!0,calculatedFields:g.calculatedFields??[]});((T=p.source)==null?void 0:T.kind)==="sql"&&M(`${o}.cardId`);const v=!p.editable&&(p.reason==="not_expressible"||p.reason==="type_not_supported"),w=v&&(f==null?void 0:f.queryFree)===!0;w&&D.add(l);const _=v&&(f==null?void 0:f.replacesQuery)===!0;return _&&n.push({code:"query_replaced",message:`"${h.card.title}" used ${p.detail??"a query the MCP can't read"}; this change replaces its query.`,path:`${o}.query`,details:{cardIds:[l]}}),!p.editable&&p.reason!=="empty"&&!w&&!_&&y({code:"card_not_editable",message:p.message,path:`${o}.cardId`,fix:ed(p.reason),details:{reason:p.reason,...(p.detail?{detail:p.detail}:{})}}),h.frame.visualId&&n.push({code:"detaches_linked_visual",message:`"${h.card.title}" will stop following its library visual and become local to this dashboard.`,path:o,details:{cardIds:[l]}}),{card:h.card,read:p};},B=/* @__PURE__ */new Map(),W=(l,o,f)=>{var p;const h=Xs("metric",((p=l.config)==null?void 0:p.metricColumns)??[]);return o.map(({index:v,calculations:w})=>({...w,measure:h[v]??{role:"metric",field:"",ordinal:v},path:`${f}.query.measures[${v}]`}));},N=async l=>{const o=he(g,l.cardId).card,f=W(o,l.stated,l.path),h=f.some(w=>{var _;return((_=w.comparison)==null?void 0:_.kind)==="shift";}),p=h&&a.readComparisonDates?await a.readComparisonDates({card:o,dashboard:g}):As(o),v=ns({card:o,stated:f,context:{path:l.path,cardRef:l.cardRef,dates:p}});if(!v.ok)throw i.push(...v.problems),new Ae();return n.push(...v.warnings),h&&B.set(l.cardId,l.path),v.update?(O({op:"card.update",cardId:l.cardId,update:{kind:"calculations",calculations:v.update},changeIndex:l.index},`${l.path}.query`),!0):!1;},J=l=>Object.fromEntries(["columns",...gi].map(o=>[o,l[o]])),P=l=>Object.entries(J(l)).filter(([,o])=>o!==void 0).map(([o])=>o),k=l=>(i.push(...l.slice(0,-1)),y(l[l.length-1])),V=(l,o,f,h)=>{const{card:p}=o,v=[...(l.type?["type"]:[]),...(l.query?["query"]:[]),...(l.matrix?["matrix"]:[]),...P(l)];v.length&&y({code:"invalid_change",message:`"${p.title}" is a text card, so it takes no ${Me(v)}.`,path:h,fix:"Change a card to or from text in the editor, or add a new card and remove this one."});const w=zs(p,{inputs:g.inputs,variables:g.variables});w.editable||y({code:"card_not_editable",message:w.message,path:`${h}.cardId`,fix:"Tell the user to change it in the editor.",details:{reason:"text"}});const _=w.editable&&(w.form==="legacy_html"||w.form==="legacy_runs");_&&l.description!==void 0&&l.text===void 0&&y({code:"invalid_change",message:`"${p.title}" keeps its words in its description, so a description change would replace them.`,path:`${h}.description`,fix:"Send the words in text with it: they are stored as rich text, and the description becomes the subtitle."}),c.push({ref:l.cardId,kind:"card",id:p.id,title:l.title??p.title??"",changeIndex:f});let T=!1,C=!1;if(l.text!==void 0){const q=cs({text:l.text,card:p,context:{dashboard:g,place:{kind:"sheet",sheetId:o.sheet.id,cardId:p.id}},path:`${h}.text`,storeAsRichText:_&&l.description!==void 0});q.ok||k(q.problems),q.ok&&!q.unchanged&&(O({op:"card.update",cardId:p.id,update:{kind:"text",richContent:q.richContent,clearsLegacy:q.clearsLegacy},changeIndex:f},h),T=!0,C=q.clearsLegacy);}const L=l.title!==void 0&&l.title!==p.title,K=l.description!==void 0&&(_?C:(l.description??void 0)!==(p.description??void 0));(L||K)&&(O({op:"card.update",cardId:p.id,update:{kind:"rename",...(L?{title:l.title}:{}),...(K?{description:l.description}:{})},changeIndex:f},h),T=!0),T&&o.frame.visualId&&n.push({code:"detaches_linked_visual",message:`"${p.title}" will stop following its library visual and become local to this dashboard.`,path:h,details:{cardIds:[p.id]}});},U=(l,o)=>{if(l.startsWith("$")){const f=m.get(l);return(!f||f.kind!=="card")&&y({code:"handle_unknown",message:`${l} isn't a card handle defined earlier in this list.`,path:o,fix:"Define the handle with an earlier card.add, or use the card id from the outline."}),f.id;}return _e(g).some(f=>f.cardId===l)||y({code:"card_not_found",message:`There's no card ${l} on this dashboard.`,path:o,fix:"Read the outline again and use its card ids."}),l;},j=(l,o)=>{if(l.startsWith("$")){const h=m.get(l);return(!h||h.kind!=="filter")&&y({code:"handle_unknown",message:`${l} isn't a filter handle defined earlier in this list.`,path:o,fix:"Define the handle with an earlier filter.add, or use the filter id from the outline."}),h.id;}return(Array.isArray(g.inputs)?g.inputs:[]).some(h=>h.id===l&&h.kind==="filter")||y({code:"filter_not_found",message:`There's no filter ${l} on this dashboard.`,path:o,fix:"Read the outline again and use its filter ids."}),l;},ne=(l,o,f)=>{o!==void 0&&(o!=="range"&&o!=="list"&&y({code:"invalid_change",message:`showAs is "range" or "list", not "${o}".`,path:f,fix:'Send showAs: "range" or "list".'}),Wt(l.dataType)||y({code:"invalid_change",message:"Only number fields show as a range or a list.",path:f,fix:"Leave showAs out for this field."}),Object.assign(l,Oo(l,o)),l.defaultValues===void 0&&delete l.defaultValues);},X=(l,o,f)=>{if(o===void 0)return;us(l)||y({code:"invalid_change",message:"defaultCondition is for a number filter shown as a range.",path:f,fix:"Send showAs: 'range' with it; for a list use defaultValues (null clears), for a date filter defaultPeriod."});let h=null;if(o){const p=Js(o);p.ok?h=p.condition:y({code:"invalid_change",message:p.message,path:f,fix:"State the condition with its numbers."});}Object.assign(l,Eo(h)),l.defaultValues===void 0&&delete l.defaultValues;},ge=(l,o,f)=>{o&&us(l)&&y({code:"invalid_change",message:"A range filter's default is a condition, not values to tick.",path:f,fix:"Send defaultCondition, or showAs: 'list' with defaultValues."});},be=()=>_e(g).flatMap(l=>l.kind==="frameCard"?[l.card]:[]),Te=(l,o,f)=>{var w,_;const h=l.startsWith("$")?(w=m.get(l))==null?void 0:w.id:l;if(!h)return;const p=o===void 0?void 0:U(o,`${f}.cardId`),v=oi(be(),h,p);return v.kind==="ambiguous"&&y({code:"invalid_change",message:`The filter ${l} is pinned on ${v.cards.length} cards: ${v.cards.map(T=>`"${T.title}"`).join(", ")}.`,path:`${f}.filterId`,fix:"Send cardId: the card whose pinnedFilters list the filter.",details:{cardIds:v.cards.map(T=>T.id)}}),v.kind==="none"&&p!==void 0&&y({code:"invalid_change",message:`"${((_=he(g,p))==null?void 0:_.card.title)??p}" has no pinned filter ${l}.`,path:`${f}.filterId`,fix:"Use a filterId from that card's pinnedFilters; leave cardId out for a dashboard filter."}),v.kind==="found"?v:void 0;},$e=(l,o,f,h)=>{o.selection&&!l.dateSelectionMode&&(l.type=o.selection);const p=o.showAs??(h&&o.defaultValues&&Wt(l.dataType)?"list":void 0);ne(l,p,`${f}.showAs`),X(l,o.defaultCondition,`${f}.defaultCondition`),o.defaultValues&&ge(l,o.defaultValues,`${f}.defaultValues`),o.defaultValues===null?delete l.defaultValues:o.defaultValues&&(l.defaultValues=o.defaultValues),o.defaultPeriod!==void 0&&(Object.assign(l,St(l,o.defaultPeriod===null?void 0:sa(o.defaultPeriod,{dataType:l.dataType},`${f}.defaultPeriod`,y))),o.defaultPeriod===null&&delete l.defaultDateFilter);},we=(l,o,f,h,p=!1)=>{O({op:"pinnedFilters.set",cardId:l,filters:[...o],...(p?{unpins:!0}:{}),changeIndex:f},h);},Fe=(l,o)=>{const f=l.startsWith("$")?void 0:Dt(g,l);return f?f.id:U(l,o);},re={services:a,problem:y,refuseAll:k,need:M},Ue=()=>(g.sheets??[]).filter(l=>wa(l)),Se=()=>Ue().map(l=>({sheetId:l.id,title:l.title??""})),Ge=(l,o,f)=>{let h=l;if(l.startsWith("$")){const v=m.get(l);(!v||v.kind!=="sheet")&&y({code:"handle_unknown",message:`${l} isn't a sheet handle defined earlier in this list.`,path:o,fix:"Define the handle with an earlier sheet.add, or use the sheet id from the outline."}),h=v.id;}const p=(g.sheets??[]).find(v=>v.id===h);return p||y({code:"sheet_not_found",message:`There's no sheet ${h} on this dashboard.`,path:o,fix:"Read the outline again and use its sheet ids.",details:{sheets:Se()}}),f.grid&&ya(p)&&y({code:"sheet_not_a_grid",message:`"${p.title}" is a Document sheet.`,path:o,fix:"Add the card to a grid sheet; Document sheets are changed in the editor.",details:{sheets:Se()}}),f.cards&&Ut(p)&&y({code:"sheet_holds_one_table",message:`"${p.title}" is a Table sheet: it holds one table, so it takes no other card and has no grid.`,path:o,fix:"Add the card to a dashboard sheet, or change this sheet's table with card.update.",details:{sheets:Se()}}),p;},Oe=(l,o)=>Ge(l,o,{grid:!0,cards:!0}),yt=(l,o)=>Ge(l,o,{grid:!0}),ot=(l,o)=>l.map((f,h)=>yt(f,`${o}.sheetIds[${h}]`).id),nt=async(l,o)=>{(l.text!==void 0||!l.query)&&y({code:"invalid_change",message:l.text!==void 0?`A ${l.type} card takes a query, not text.`:`A ${l.type} card needs a query.`,path:l.text!==void 0?`${o}.text`:`${o}.query`,fix:"Send query; text is for type text."});const f=aa(l.query),h=f.query,p=l.type;Ne(p,h,l.matrix,o);const v=await tt(p,h,l.matrix,o),w={...xn({id:a.newId(),title:l.title,...(l.description?{description:l.description}:{})}),type:v.type},_=ds(w,v);_.ok||y({code:"invalid_change",message:_.message,path:o});const T=_.ok?_.card:w;dt(T,h,l.matrix,o,l.title,v);const C={id:a.newId(),cards:[T],activeCardId:T.id};return{card:T,frame:C,query:h,calculations:f.calculations};},ye=(l,o,f)=>{var v;if(l.type!=="custom_visual")return l.customVisual!==void 0&&y({code:"invalid_change",message:`A ${String(l.type).replace(/_/g," ")} card takes no customVisual.`,path:`${f}.customVisual`,fix:"customVisual is for type custom_visual."}),o;((v=l.customVisual)==null?void 0:v.html)===void 0&&y({code:"invalid_change",message:"A custom_visual card needs its HTML in customVisual.html.",path:`${f}.customVisual.html`,fix:"Call semaphor_get_extension_contract for the contract and the card's fields, write the visual, and send its HTML."});const h=vs({card:o.card,stated:l.customVisual,path:`${f}.customVisual`});if(!h.ok)return y(h.problem);const p=h.card;return{...o,card:p,frame:{...o.frame,cards:o.frame.cards.map(w=>w.id===p.id?p:w)}};},Oa=async l=>{var C,L,K,q,Q,Z;const o=(C=he(g,l.cardId))==null?void 0:C.card;if(!o)return;const f=`${l.path}.customVisual`;if(o.type!=="customVisual"){l.stated&&y({code:"invalid_change",message:`"${o.title}" isn't a custom visual, so it takes no customVisual.`,path:f,fix:"Change its type to custom_visual in the same change, with the HTML."});return;}const h=l.stated??{};if(l.retyped&&h.html===void 0&&!((L=o.customVisual)!=null&&L.draft)&&!((K=o.customVisual)!=null&&K.version)&&y({code:"invalid_change",message:`"${o.title}" needs its visual's HTML to become a custom visual.`,path:`${f}.html`,fix:"Send customVisual.html with the type change (semaphor_get_extension_contract has the contract)."}),!l.stated)return;const p=h.html===void 0&&(Object.keys(h.slots??{}).length||Object.keys(h.settings??{}).length),v=o.customVisual,w=p?li(o)??(v!=null&&v.extensionId&&v.version?(await((q=a.readExtensionManifest)==null?void 0:q.call(a,{extensionId:v.extensionId,version:v.version})))??void 0:void 0):void 0,_=(Q=o.sql)!=null&&Q.trim()&&h.slots?await((Z=a.readSqlResultColumns)==null?void 0:Z.call(a,{cardId:o.id,dashboard:g})):void 0,T=vs({card:o,stated:h,manifest:w,sqlColumns:_,path:f});if(!T.ok)return y(T.problem);T.card!==o&&(O({op:"card.update",cardId:o.id,update:{kind:"customVisual",customVisual:T.card.customVisual,wording:T.wording},changeIndex:l.index},f),r.includes(o.id)||r.push(o.id));},Ee=async(l,o,f,h,p)=>{r.push(l.card.id),await N({cardId:l.card.id,cardRef:f,stated:l.calculations,index:h,path:p}),await Y({cardId:l.card.id,cardRef:f,request:{settings:J(o)},queryLabels:"sql"in l.query?[]:ht(l.query),index:h,path:p});},Ne=(l,o,f,h)=>{var _;for(const T of Ws(o,f))y({...T,path:`${h}.${T.path}`});const p=lt[l],v=bt(o),w=o.dateField;if(w&&typeof w!="string"&&w.label&&!o.timeGrain&&y({code:"invalid_change",message:"A label names a column, and the date field is a column only when the card groups by it.",path:`${h}.query.dateField.label`,fix:"Send timeGrain to group by the date, or leave the label out."}),!p.forms.includes(v)){const T=Object.keys(lt).filter(C=>lt[C].forms.includes(v));y({code:"type_not_supported",message:`A ${l.replace(/_/g," ")} card takes ${p.forms.map(C=>It[C]).join(" or ")}, not ${It[v]}.`,path:`${h}.query`,fix:`Send ${p.forms.map(C=>It[C]).join(" or ")}, or use a type this query fits: ${T.join(", ")}.`});}if(v==="measures"){const T=o,C=T.measures.length;p.measures&&(C<p.measures.min||p.measures.max!==void 0&&C>p.measures.max)&&y({code:"type_not_supported",message:`A ${l.replace(/_/g," ")} card shows exactly ${p.measures.max} measure.`,path:`${h}.query.measures`,fix:"Send one measure, or use a table or chart for several."}),!p.dimensions&&(_=T.dimensions)!=null&&_.length&&y({code:"type_not_supported",message:`A ${l.replace(/_/g," ")} card shows one number, so it has no dimensions.`,path:`${h}.query.dimensions`,fix:"Remove the dimensions, or use a table or chart."}),l==="matrix"&&(T.orderBy||T.limit)&&y({code:"type_not_supported",message:"A Matrix's sorting and top N are set in the editor.",path:`${h}.query`,fix:"Leave out orderBy and limit for a Matrix."});}if(p.matrixColumns&&!f&&y({code:"type_not_supported",message:"A Matrix needs matrix.columns: the query fields that run across the top.",path:`${h}.matrix`,fix:"Send matrix: { columns: [...] } naming dimensions or the date field of the query (an empty list puts nothing across the top)."}),!p.matrixColumns&&f&&y({code:"type_not_supported",message:"matrix.columns is only for Matrix cards.",path:`${h}.matrix`,fix:'Leave out matrix, or use type "matrix".'}),f&&v==="measures"){const T=o,C=T.datasetName,L=[...(T.dimensions??[]),...(T.timeGrain&&T.dateField?[T.dateField]:[])];L.length&&f.columns.length>=L.length&&L.every(q=>f.columns.some(Q=>De(Q,C)===De(q,C)))&&y({code:"type_not_supported",message:"A Matrix needs at least one field down the side.",path:`${h}.matrix.columns`,fix:"Leave one dimension or the date field out of matrix.columns."});const K=new Set([...(T.dimensions??[]),...(T.dateField?[T.dateField]:[])].map(q=>De(q,C)));f.columns.forEach((q,Q)=>{K.has(De(q,C))||y({code:"type_not_supported",message:`"${da(q)}" isn't one of the query's dimensions or its date field.`,path:`${h}.matrix.columns[${Q}]`,fix:"Name dimensions or the date field of the query in matrix.columns."});});}},rt=(l,o)=>y({code:l.code==="query_not_kept"?"card_not_editable":"invalid_change",message:l.message,path:`${o}.query`,fix:l.code==="query_not_kept"?"Tell the user to make this change in the editor.":"Read the outline again and propose again.",details:{reason:"not_expressible",...("parts"in l?{parts:l.parts}:{})}}),dt=(l,o,f,h,p,v,w)=>{const _=Ve(l,{sql:!0,calculations:!1,calculatedFields:g.calculatedFields??[]});_.editable||y({code:"card_not_editable",message:_.message,path:`${h}.query`,fix:_.reason==="needs_sql_access"?"Ask for SQL access.":"Tell the user to change it in the editor.",details:{reason:_.reason,...(_.detail?{detail:_.detail}:{})}});const T=Ur(l,o,f,v,w,_,g.calculatedFields??[]);if(!T.length)return;const C=o;if(T.length===1&&T[0]==="dateField"&&C.dateField&&!C.timeGrain&&!C.timeWindow){y({code:"value_invalid",message:`A dateField on its own doesn't change "${p}": it needs timeGrain to group by the date (a KPI's Trend By) or a timeWindow to filter by it.`,path:`${h}.query.dateField`,fix:'Add timeGrain (for example "month") or a timeWindow, or leave out dateField.'});return;}const L=T.join(", ");y({code:"card_not_editable",message:w?`As changed, "${p}" wouldn't hold ${L} as asked, so make this change in the editor.`:`"${p}" can't be built holding ${L} as asked.`,path:`${h}.query`,fix:w?"Tell the user to make this change in the editor.":`Leave out ${L}; the rest of the card can be added.`,details:{reason:"not_expressible",detail:`doesn't hold: ${L}`}});},Bt=async(l,o,f)=>{var L,K,q;const p=(g.calculatedFields??[]).find(Q=>Q.name.toLowerCase()===l.name.toLowerCase()),v=()=>y({code:"calculated_field_not_found",message:`This dashboard has no calculated field named ${l.name}.`,path:`${f}.name`,fix:"Read the outline's calculatedFields."});if(l.op==="calculation.remove"){p||v();const Q=Tt(p),Z=Qs(g,Q);Fo(Z)&&y({code:"calculated_field_in_use",message:Ao(p,Z),path:`${f}.name`,fix:"Remove it from those cards and filters earlier in this proposal, or keep it.",details:{usedBy:[...Z.cards.map(G=>G.cardId),...Z.filters.map(G=>G.filterId),...Z.fields.map(G=>G.name)]}}),O({op:"calculatedField.remove",key:Q,changeIndex:o},f);return;}l.op==="calculation.update"&&!p&&v();const w=l.op==="calculation.update"?p:void 0,_=w?Hs(w):void 0,T=l.op==="calculation.add"||l.expression!==void 0||l.inputs!==void 0;l.op==="calculation.update"&&!T&&l.label===void 0&&l.description===void 0&&y({code:"invalid_change",message:`calculation.update on ${l.name} changes nothing.`,path:f,fix:"Send label, description or expression."}),l.op==="calculation.add"&&p&&y({code:"calculated_field_name_taken",message:`This dashboard already has a calculated field named ${p.name}.`,path:`${f}.name`,fix:"Name it differently, or change it with calculation.update."});let C;if(T){const Q=l.domainId??((K=(L=w==null?void 0:w.calculatedFormula)==null?void 0:L.inputFields)==null?void 0:K.map(ie=>{var fe;return((fe=ie.source)==null?void 0:fe.kind)==="semantic"?ie.source.domainId:void 0;}).find(Boolean)),Z=l.dataset??(_?(q=Object.values(_.inputs)[0])==null?void 0:q.dataset:void 0);(!Q||!Z)&&y({code:"invalid_change",message:"A dashboard field names its domainId and dataset, as a card query does.",path:f,fix:"Send the dataset's domainId and dataset name."});const G=l.inputs??(l.op==="calculation.update"&&l.expression===void 0?_==null?void 0:_.inputs:void 0);Object.values(G??{}).some(ie=>"metric"in ie||ie.dataset.toLowerCase()!==Z.toLowerCase())&&y({code:"invalid_change",message:"A dashboard field reads one dataset; add it to the domain.",path:`${f}.inputs`,fix:"Write the formula over this dataset's fields, or propose calculation.add to the domain with domainId."});const oe=await a.loadCardSource({domainId:Q,datasetName:Z});oe||y({code:"field_not_found",message:`The dataset "${Z}" isn't available.`,path:`${f}.dataset`,fix:"Find datasets with semaphor_list_datasets."}),l.op==="calculation.add"&&oe.fields.some(ie=>ie.name.toLowerCase()===l.name.toLowerCase())&&y({code:"calculated_field_name_taken",message:`${l.name} is a field of ${Z} already.`,path:`${f}.name`,fix:"Name it differently, or use the field."}),a.compileCalculation||y({code:"invalid_change",message:"Calculated fields can't be compiled here.",path:f,fix:"Change it in the editor."}),w&&!_&&l.expression===void 0&&y({code:"invalid_change",message:`${w.label||w.name} reads another calculated field, so its formula can't be changed in part.`,path:f,fix:"Send its whole formula: expression and inputs, over the dataset's fields."});const le=(w==null?void 0:w.role)==="groupby"?od(w.dataType):void 0,de=await a.compileCalculation({domainId:Q,dataset:Z,name:w?w.id:l.name,...(l.label??(w==null?void 0:w.label)?{label:l.label??(w==null?void 0:w.label)}:{}),...(typeof l.description=="string"?{description:l.description}:{}),expression:l.expression??_.expression,...(G?{inputs:G}:{}),...(l.op==="calculation.add"&&l.use?{use:l.use}:w?{use:w.role==="metric"?"aggregate":"group_or_filter"}:{}),...(l.op==="calculation.add"&&l.dataType?{dataType:l.dataType}:le?{dataType:le}:{})});if(!de.ok)throw i.push(...de.problems.map(ie=>({...ie,path:ie.path?`${f}.${ie.path}`:f}))),new Ae();w&&de.kind==="dimension"!=(w.role==="groupby")&&y({code:"invalid_change",message:`This formula would turn ${w.label||w.name} from a ${w.role==="groupby"?"dimension into a measure":"measure into a dimension"}.`,path:`${f}.expression`,fix:"Add a new field instead."}),C=Do({compiled:de.field,kind:de.kind,stage:de.stage,catalog:oe.fields,name:(w==null?void 0:w.name)??l.name,label:l.label??(w==null?void 0:w.label),description:l.description===null?void 0:l.description??(w&&!Fs(w)?w.description:void 0),id:(w==null?void 0:w.id)??`${de.kind==="dimension"?"calc_dim_":"calc_"}${a.newId().replace(/-/g,"").slice(-10)}`});}else C={...w,...(l.label!==void 0?{label:l.label}:{}),...(l.label!==void 0&&l.description===void 0&&Fs(w)?{description:`Calculated field: ${l.label}`}:{}),...(l.description!==void 0?{description:l.description??void 0}:{})};O(w?{op:"calculatedField.update",key:Tt(w),field:C,changeIndex:o}:{op:"calculatedField.add",field:C,changeIndex:o},f);},Qe=(l,o,f)=>{var T;const h=g.calculatedFields??[];if(!h.length)return[];const p=/* @__PURE__ */new Map(),v=C=>{const L=typeof C=="string"?C:C==null?void 0:C.name,K=typeof C=="object"&&C?C.datasetName:void 0;if(typeof L!="string"||K&&K.toLowerCase()!==l.datasetName.toLowerCase())return;const q=Jo(L,{domainId:l.domainId,datasetName:l.datasetName},h);return q&&p.set(Tt(q),q),q;},w=v(l.dateField);w&&y({code:"invalid_change",message:`${w.label||w.name} is one of this dashboard's calculated fields; a date grouping on one is set in the editor.`,path:`${f}.query.dateField`,fix:"Group by a date field of the dataset, or set it in the editor."});const _=(C,L)=>C==null?void 0:C.forEach((K,q)=>{var G,H;const Q=v(K);!Q||(o==="matrixTable"&&y({code:"calculated_field_not_for_matrix",message:`${Q.label||Q.name} is one of this dashboard's calculated fields; a Matrix takes the domain's.`,path:`${f}.query.${L}[${q}]`,fix:"Use a domain calculation, or build it in the editor."}),(typeof K=="object"?K.aggregate:void 0)&&((G=Q.calculatedFormula)==null?void 0:G.computeStage)!=="row"&&Q.role==="metric"&&y({code:"invalid_change",message:`${Q.label||Q.name} aggregates already.`,path:`${f}.query.${L}[${q}].aggregate`,fix:"Leave out its aggregate."}),L==="measures")||(Q.role==="metric"&&((H=Q.calculatedFormula)==null?void 0:H.computeStage)!=="row"?y({code:"invalid_change",message:`${Q.label||Q.name} is a measure over aggregates; it can't group the card or be one of its columns.`,path:`${f}.query.${L}[${q}]`,fix:"Name it in measures."}):Mt(Q.dataType)&&y({code:"invalid_change",message:`${Q.label||Q.name} is one of this dashboard's calculated fields; a date grouping on one is set in the editor.`,path:`${f}.query.${L}[${q}]`,fix:"Group by a date field of the dataset, or set it in the editor."}));});return"measures"in l?(_(l.measures,"measures"),_(l.dimensions,"dimensions")):_(l.columns,"columns"),v((T=l.orderBy)==null?void 0:T.field),(l.filters??[]).forEach(C=>v(C.field)),[...p.values()];},tt=async(l,o,f,h,p=!1)=>{const v=kt(l);if("sql"in o)return M(`${h}.query`),{type:v,source:{kind:"sql",connectionId:o.connectionId,sql:o.sql}};"measures"in o&&o.timeGrain===Vo&&(Bo({cardType:v,configBacked:!0,shelf:"groupBy",dataType:"date"}).ok||y(l==="kpi"?{code:"type_not_supported",message:"A KPI's query can't group by a grain that follows the dashboard date.",path:`${h}.query.timeGrain`,fix:'For a trend that follows the dashboard date, send trend: true and trendGrain: "automatic" with no Trend By.'}:{code:"type_not_supported",message:`${Xr[l]??`A ${l.replace(/_/g," ")}`} can't group by a grain that follows the dashboard date.`,path:`${h}.query.timeGrain`,fix:'Use a bar, line or area chart or a table, or send a fixed timeGrain such as "month".'}));const w=v==="matrixTable"||v==="detailTable"?"table":v,_=Qe(o,v,h),T=await a.compileCardQuery({query:o,chartType:w,...(_.length?{dashboardFields:_}:{})});if(T.ok&&_.length&&(T.part={...T.part,config:jo(T.part.config??{},_)}),!T.ok)throw i.push(...T.problems.map(q=>({...q,path:q.path?`${h}.query.${q.path}`:`${h}.query`}))),new Ae();n.push(...T.warnings.map(q=>({...q,path:q.path??`${h}.query`})));const C=!p&&"timeWindow"in o&&o.timeWindow?md(T.part.config):void 0;C&&"timeWindow"in o&&o.timeWindow&&xi(o.timeWindow,{use:"cardFilter",columnHasTime:Ks(C)},`${h}.query.timeWindow`,y);let L={...T.part,type:v};const K=L.config??{};if(v==="detailTable"){const q=Ko(Wo("table","detailTable",K))??{};L={...L,config:rd(q)};}return v==="matrixTable"&&(L=await z(L,K,o,f,h)),dd(L,ht(o));},z=async(l,o,f,h,p)=>{var K;const v=await a.loadCardSource({domainId:f.domainId,datasetName:f.datasetName});if(v||y({code:"field_not_found",message:`The dataset "${f.datasetName}" isn't available.`,path:`${p}.query.datasetName`,fix:"Find datasets with semaphor_list_datasets."}),l.source.kind!=="semantic")throw new Ae();const w={id:"scratch",title:"",type:"table",dataSource:l.source.dataSource,config:o},_=Go(w,"matrixTable",{catalog:v.fields,createId:a.newId}),T=_.status==="changed"?(K=_.card.config)==null?void 0:K.matrix:void 0;(_.status!=="changed"||_.leftOut.length||!T)&&y({code:"type_not_supported",message:_.status==="changed"&&_.leftOut.length?`These fields can't run in a Matrix: ${_.leftOut.join(", ")}.`:"This query can't be shown as a Matrix.",path:`${p}.query`,fix:"Use plain dataset fields for a Matrix, or use a table."});let C=T;const L=f.datasetName;for(const[q,Q]of h.columns.entries()){const Z=[...C.spec.rows,...C.spec.columns].find(G=>Rt(G.field)===De(Q,L));Z||y({code:"type_not_supported",message:`"${da(Q)}" isn't a level of this Matrix.`,path:`${p}.matrix.columns[${q}]`,fix:"Name dimensions or the date field of the query in matrix.columns."}),C=Qo(C,Ho(C.spec,Z.id,"columns")).config;}return{...l,config:{matrix:C}};},se=/* @__PURE__ */new Map(),xe=/* @__PURE__ */new Map(),Ea=/* @__PURE__ */new Map(),Na=(l,o,f)=>{o.defaultValues===void 0&&o.defaultPeriod===void 0&&o.defaultCondition===void 0||xe.set(`pinned:${l.cardId}:${l.filterId}`,{pinned:l,values:o.defaultValues,period:o.defaultPeriod,...(o.defaultCondition!==void 0?{condition:o.defaultCondition}:{}),changeIndex:f});};for(const[l,o]of F.entries()){const f=`changes[${l}]`;try{switch(o.op){case"card.add":{const h=o.position&&typeof o.position=="object"?(()=>{const C=U(o.position.after,`${f}.position.after`),L=_e(g).find(K=>K.cardId===C&&K.kind==="frameCard");return!L||L.kind!=="frameCard"?y({code:"card_not_found",message:`${o.position.after} isn't a card on a grid sheet.`,path:`${f}.position.after`,fix:"Use a cardId from semaphor_get_dashboard_details on the same sheet, or a handle from this proposal."}):(o.sheetId&&Oe(o.sheetId,`${f}.sheetId`).id!==L.sheetId&&y({code:"invalid_change",message:`position.after names a card on another sheet than ${o.sheetId}.`,path:`${f}.position.after`,fix:"Leave out sheetId, or name the card's sheet."}),{sheetId:L.sheetId,frameId:L.frameId});})():void 0,p=h?Oe(h.sheetId,`${f}.position.after`):o.sheetId?Oe(o.sheetId,`${f}.sheetId`):(()=>{const C=Ue();return C.length!==1&&y({code:C.length?"sheet_required":"sheet_not_a_grid",message:C.length?"This dashboard has several grid sheets; say which one gets the card.":"This dashboard has no grid sheet to add a card to.",path:`${f}.sheetId`,fix:C.length?"Send sheetId: one of details.sheets.":"Add a sheet with sheet.add earlier in this list.",details:{sheets:Se()}}),C[0];})(),v=h?{after:h.frameId}:typeof o.position=="string"?o.position:void 0,w=v||o.width?{...(v?{position:v}:{}),...(o.width?{width:o.width}:{})}:void 0,_=C=>{const L=o.handle??`$card_${++x}`;return m.has(L)&&y({code:"invalid_change",message:`The handle ${L} is defined twice.`,path:`${f}.handle`,fix:"Give each new card, filter or sheet its own handle."}),m.set(L,{kind:"card",id:C.id,title:o.title}),c.push({ref:L,kind:"card",id:C.id,title:o.title,changeIndex:l}),L;};if(o.type==="text"){const C=[...(o.query?["query"]:[]),...(o.matrix?["matrix"]:[]),...P(o)];C.length&&y({code:"invalid_change",message:`A text card takes no ${Me(C)}.`,path:f,fix:Ts}),o.text===void 0&&y({code:"invalid_change",message:"A text card needs its words in text.",path:`${f}.text`,fix:Ts});const L=cs({text:o.text,context:{dashboard:g,place:{kind:"sheet",sheetId:p.id}},path:`${f}.text`});L.ok||k(L.problems);const K=Sn({id:a.newId(),title:o.title,...(o.description?{description:o.description}:{}),richContent:L.ok&&!L.unchanged?L.richContent:{version:1,blocks:[{type:"paragraph",children:[]}]}});O({op:"card.add",sheetId:p.id,frame:{id:a.newId(),cards:[K],activeCardId:K.id},...(w?{placement:w}:{}),changeIndex:l},f),_(K);break;}const T=ye(o,await nt(o,f),f);O({op:"card.add",sheetId:p.id,frame:T.frame,...(w?{placement:w}:{}),changeIndex:l},f),await Ee(T,o,_(T.card),l,f);break;}case"card.update":{const h=U(o.cardId,`${f}.cardId`),p=he(g,h);if((p==null?void 0:p.card.type)==="text"){V(o,p,l,f);break;}o.text!==void 0&&y({code:"invalid_change",message:`"${(p==null?void 0:p.card.title)??h}" isn't a text card, so it takes no text.`,path:`${f}.text`,fix:"Change its query; text is for text cards."});const v=(Pa=he(g,h))==null?void 0:Pa.card,_=(o.type===void 0||v!==void 0&&ad(v,o.type))&&Object.entries(o).every(([H,oe])=>td.has(H)||H==="type"||oe===void 0),T=o.query!==void 0&&sd(o.query),{card:C,read:L}=E(h,f,{queryFree:_,replacesQuery:T});o.query!==void 0&&o.type===void 0&&!ze(C)&&y({code:"type_not_supported",message:`"${C.title}" is a ${xt(C.type).replace(/_/g," ")} card, whose query is replaced together with a type.`,path:`${f}.type`,fix:"Send type (bar, line, table, kpi, …) with the complete query."});const K=!L.editable&&(L.reason==="empty"||T);let q=!1,Q=[];const Z=o.type&&o.type!==((qa=ze(C))==null?void 0:qa.type)?kt(o.type):void 0;if(Z&&Z!==C.type&&!Co(Z)&&p&&Ut(p.sheet)&&y({code:"table_sheet_card_type",message:`"${C.title}" is the table of the Table sheet "${p.sheet.title}", so it stays a table, a detail table or a Matrix.`,path:`${f}.type`,fix:"Use type table, detail_table or matrix, or add the chart to a dashboard sheet with card.add."}),Z&&Z!==C.type){const H=L.editable?L.source:void 0,oe=So(C,Z),le=oe&&H&&H.kind==="semantic"?(La=await a.loadCardSource({domainId:H.domainId,datasetName:H.datasetName}))==null?void 0:La.fields:oe&&K?[]:void 0,de=[],ie=Gs(C,Z,{...(le?{catalog:le}:{}),...(oe&&!le?{catalogLoading:!0}:{}),createId:()=>{const fe=a.newId();return de.push(fe),fe;}});if(ie.status==="refused"&&y({code:"type_not_supported",message:"The card's dataset fields couldn't be loaded for a change to or from a Matrix.",path:`${f}.type`,fix:"Send a complete query with the type change."}),ie.status==="changed"){const fe=Array.from(/* @__PURE__ */new Set([...ie.leftOut,...ie.droppedFields,...ie.droppedPreferences]));fe.length&&n.push({code:"type_change_drops",message:`Changing "${C.title}" to ${o.type.replace(/_/g," ")} leaves out ${fe.join(", ")}.`,path:`${f}.type`,details:{dropped:fe}}),O({op:"card.update",cardId:h,update:{kind:"retype",type:Z,...(le?{catalog:le}:{}),newIds:de},changeIndex:l},`${f}.type`),q=!0;}}const G=o.query?aa(o.query):void 0;if(o.query||o.matrix){const H=he(g,h).card,oe=Ve(H,{sql:!0,calculations:!1,calculatedFields:g.calculatedFields??[]}),le=oe.editable?aa(oe.query).query:void 0,de=le,ie=fd(de,(G==null?void 0:G.query)??{},`${f}.query`,Ie=>{if(Ie.code==="query_form_mismatch"&&G!=null&&G.calculations.length){const Ye=W(H,G.calculations,f),at=ns({card:H,stated:Ye,context:{path:f,cardRef:o.cardId,dates:As(H)}});if(!at.ok)throw i.push(...at.problems),new Ae();}return y(Ie);});Q=ud((G==null?void 0:G.query)??{},ie);const fe=((Ma=ze(H))==null?void 0:Ma.type)??xt(H.type),He=o.matrix??(oe.editable?oe.matrix:void 0);Ne(fe,ie,He,f);const ee=oe.editable&&le?xo(le,ie,oe.matrix,He):void 0,ke=!ee||ee.aspects.length>0,Pe=ee&&!("sql"in ie)?ht(ie).filter(Ie=>!rs(ee,Ie.key.role)):[],ts=ko(H,ee,Pe.map(Ie=>Ie.key.role));ts&&rt(ts,f);let jt=ie;if(ee&&!("sql"in ie)&&ie.orderBy&&!ee.aspects.includes("order")&&["metric","group_by","detail"].some(Ie=>rs(ee,Ie))){const{orderBy:Ie,...Ye}=ie;jt=Ye;}let as;if(ke){const Ie=!!(de&&Si(de,(G==null?void 0:G.query)??{})&&ee!=null&&ee.keptWindow),Ye=await tt(fe,jt,He,f,Ie),at=Ye.type===kt(fe)?{...Ye,type:H.type}:Ye;as=at;const ss=ee?{...at,change:ee}:at,Je=ds(H,ss);if(Je.ok||rt(Je,f),Je.ok&&Je.droppedBindings.length&&n.push({code:"control_binding_dropped",message:`"${H.title}" loses the controls bound to the levels or measures this change removes; they stop changing this card.`,path:`${f}.query`,fix:"Keep those fields in the query, or tell the user the controls no longer apply to this card.",details:{controlIds:Je.droppedBindings}}),Je.ok)for(const vt of Je.keptLabels)n.push({code:"label_kept_after_change",message:`"${H.title}" keeps the label "${vt.label}" on ${vt.field}, whose aggregate or time grain changed.`,path:`${f}.query`,fix:"State a new label on the field ref if the old one no longer fits.",details:{columns:[{label:vt.label,field:vt.field}]}});O({op:"card.update",cardId:h,update:{kind:"requery",query:ss},changeIndex:l},`${f}.query`),q=!0;}Pe.length&&ls(he(g,h).card,Pe).changed.length&&O({op:"card.update",cardId:h,update:{kind:"relabel",labels:Pe},changeIndex:l},`${f}.query`),(ke||Pe.length)&&dt(he(g,h).card,jt,He,f,H.title??"",as,ee);}(o.query||Z)&&(await N({cardId:h,cardRef:o.cardId,stated:(G==null?void 0:G.calculations)??[],index:l,path:f}))&&(q=!0),(o.title!==void 0||o.description!==void 0)&&O({op:"card.update",cardId:h,update:{kind:"rename",...(o.title!==void 0?{title:o.title}:{}),...(o.description!==void 0?{description:o.description}:{})},changeIndex:l},f),await Y({cardId:h,cardRef:o.cardId,request:{settings:J(o)},queryLabels:Q,index:l,path:f}),await Oa({cardId:h,stated:o.customVisual,retyped:Z==="customVisual",index:l,path:f}),q&&!r.includes(h)&&r.push(h),c.push({ref:o.cardId,kind:"card",id:h,title:C.title??"",changeIndex:l});break;}case"card.remove":{const h=U(o.cardId,`${f}.cardId`),p=he(g,h);p||y({code:"card_not_editable",message:"Cards in Document sections are removed in the editor.",path:`${f}.cardId`,fix:"Tell the user to remove it in the editor.",details:{reason:"document_section"}}),ta(p.frame)&&p.frame.cards.length>1&&y({code:"card_not_editable",message:"This card is an input of a custom visual; remove it in the editor.",path:`${f}.cardId`,fix:"Tell the user to remove it in the editor.",details:{reason:"custom"}}),Ut(p.sheet)&&y({code:"table_sheet_no_card",message:`"${p.card.title}" is the table of the Table sheet "${p.sheet.title}", which can't be left without it.`,path:`${f}.cardId`,fix:"Remove the sheet instead, or change the sheet's table with card.update."}),p.frame.visualId&&p.frame.cards.length>1&&n.push({code:"detaches_linked_visual",message:`Removing "${p.card.title}" makes the rest of its tile local to this dashboard; it stops following its library visual.`,path:f,details:{cardIds:p.frame.cards.filter(v=>v.id!==h).map(v=>v.id)}}),O({op:"card.remove",cardId:h,changeIndex:l},f),c.push({ref:o.cardId,kind:"card",id:h,title:p.card.title??"",changeIndex:l});break;}case"filter.add":{const h=o.cardId;h!==void 0&&o.sheetIds&&y({code:"invalid_change",message:"A filter pinned on a card shows on that card, not on sheets.",path:`${f}.sheetIds`,fix:"Send cardId or sheetIds, not both."}),h===void 0&&o.position!==void 0&&y({code:"invalid_change",message:"position orders a card's pinned filters.",path:`${f}.position`,fix:"Send it with cardId, or leave it out."});const p=await a.loadCardSource({domainId:o.domainId,datasetName:o.datasetName});p||y({code:"field_not_found",message:`The dataset "${o.datasetName}" isn't available in this domain.`,path:`${f}.datasetName`,fix:"Find datasets with semaphor_list_datasets."});const v=qt(p.fields,o.field,o.datasetName);if(v||y({code:"field_not_found",message:`"${o.field}" isn't a field of ${o.datasetName}.`,path:`${f}.field`,fix:"Use one of details.available, or read semaphor_get_dataset_schema.",details:{available:p.fields.slice(0,20).map(q=>q.name)}}),h!==void 0){const q=U(h,`${f}.cardId`),Q=he(g,q);(!Q||!Rn(Q.card.type))&&y({code:"invalid_change",message:"This card doesn't take pinned filters.",path:`${f}.cardId`,fix:"Pin filters on a chart or a table."});const Z=(Va=Q.card.dataSource)==null?void 0:Va.semanticDomainId;Z&&Z!==o.domainId&&y({code:"invalid_change",message:`"${Q.card.title}" reads another domain; pin a field from ${Z}.`,path:`${f}.domainId`,fix:"Use the card's domainId from the outline."});const G=Q.card.inlineFilters??[];G.some(de=>_o(de,v))&&y({code:"invalid_change",message:`"${Q.card.title}" already has a pinned filter on ${o.field}.`,path:`${f}.field`,fix:"Change that filter with filter.update and its id from the card's pinnedFilters."});const H=On({id:a.newId(),field:v,dataSource:Q.card.dataSource??p.dataSource,connectionId:p.connectionId});H.title=o.label;const oe=gd(Q.card,o.datasetName,H,a.relationshipReach);oe&&y({code:"invalid_change",message:oe,path:`${f}.datasetName`,fix:"Pin a field of the card's dataset, a dataset it joins, or one related to it (the outline's queries name them)."}),$e(H,o,f,!0);const le=[...G,H];we(q,o.position===void 0?le:ps(le,H.id,o.position),l,f),Na({cardId:q,filterId:H.id},o,l),o.handle&&(m.has(o.handle)&&y({code:"invalid_change",message:`The handle ${o.handle} is defined twice.`,path:`${f}.handle`,fix:"Give each new card, filter or sheet its own handle."}),m.set(o.handle,{kind:"filter",id:H.id,title:o.label})),c.push({ref:o.handle??H.id,kind:"filter",id:H.id,title:o.label,changeIndex:l});break;}const w=o.sheetIds?ot(o.sheetIds,f):void 0,_=Ds(w),T=ii({field:v,dataSource:p.dataSource,connectionId:p.connectionId,connectionType:p.connectionType,scope:_,dashboard:g,createId:a.newId,label:o.label}),C={...T.filter};C.dateSelectionMode||(C.type=o.selection??"multiple");const L=o.showAs??(o.defaultValues&&Wt(C.dataType)?"list":void 0);ne(C,L,`${f}.showAs`),X(C,o.defaultCondition,`${f}.defaultCondition`),ge(C,o.defaultValues,`${f}.defaultValues`),o.defaultValues&&(C.defaultValues=o.defaultValues),o.defaultPeriod&&Object.assign(C,St(C,sa(o.defaultPeriod,v,`${f}.defaultPeriod`,y))),O({op:"filter.add",input:{...T,filter:C},changeIndex:l},f),se.set(T.id,{sheetIds:w??"all",changeIndex:l}),(o.defaultValues!==void 0||o.defaultPeriod!==void 0||o.defaultCondition!==void 0)&&xe.set(T.id,{values:o.defaultValues,period:o.defaultPeriod,...(o.defaultCondition!==void 0?{condition:o.defaultCondition}:{}),changeIndex:l});const K=o.handle;K&&(m.has(K)&&y({code:"invalid_change",message:`The handle ${K} is defined twice.`,path:`${f}.handle`,fix:"Give each new card, filter or sheet its own handle."}),m.set(K,{kind:"filter",id:T.id,title:o.label})),c.push({ref:K??T.id,kind:"filter",id:T.id,title:o.label,changeIndex:l});break;}case"filter.update":{const h=Te(o.filterId,o.cardId,f);if(h){o.sheetIds!==void 0&&y({code:"invalid_change",message:"A pinned filter shows on its card, not on sheets.",path:`${f}.sheetIds`,fix:"Leave sheetIds out for a pinned filter."});const G={...h.filter};o.label!==void 0&&(G.title=o.label),$e(G,o,f,!1);const H=(h.card.inlineFilters??[]).map(oe=>oe.id===G.id?G:oe);we(h.card.id,o.position===void 0?H:ps(H,G.id,o.position),l,f),Na({cardId:h.card.id,filterId:G.id},o,l),c.push({ref:o.filterId,kind:"filter",id:G.id,title:G.title,changeIndex:l});break;}o.position!==void 0&&y({code:"invalid_change",message:"position orders a card's pinned filters.",path:`${f}.position`,fix:"Leave it out for a dashboard filter."});const p=j(o.filterId,`${f}.filterId`),v=je(g,p,void 0,$);v!=null&&v.editable||y({code:"filter_not_editable",message:v&&!v.editable?v.notEditable.message:"This filter can't be changed through the MCP.",path:`${f}.filterId`,fix:"Tell the user to change it in the editor; removing or excluding it works."});const w=(g.inputs??[]).find(G=>G.id===p);if((w==null?void 0:w.kind)!=="filter"||!w.filter)throw new Ae();const _={...w.filter};let T=!1;o.selection&&(_.type=o.selection);const C=na(_),L=JSON.stringify([_.operation,_.defaultValues??null]);ne(_,o.showAs,`${f}.showAs`),o.defaultCondition!==void 0&&X(_,o.defaultCondition,`${f}.defaultCondition`),o.defaultValues&&ge(_,o.defaultValues,`${f}.defaultValues`);const K=na(_)!==C;if(JSON.stringify([_.operation,_.defaultValues??null])!==L&&(T=!0),o.defaultValues!==void 0&&(T=!0,o.defaultValues===null?delete _.defaultValues:_.defaultValues=o.defaultValues),o.defaultPeriod!==void 0){T=!0;const G=St(_,o.defaultPeriod===null?void 0:sa(o.defaultPeriod,{dataType:_.dataType},`${f}.defaultPeriod`,y));Object.assign(_,G),o.defaultPeriod===null&&delete _.defaultDateFilter;}let q;if(o.defaultComparison!==void 0){const G=Io.nullable().safeParse(o.defaultComparison);G.success||y({code:"invalid_change",message:`defaultComparison: ${G.error.issues.map(oe=>[...oe.path,oe.message].join(" ")).join("; ")}.`,path:`${f}.defaultComparison`,fix:'Send { kind: "shift", unit: "period" | "day" | "week" | "month" | "quarter" | "year", offset?: n, matchWeekdays?: true with "year" }, or null for none.'}),En(w)||y({code:"invalid_change",message:"defaultComparison is for a dashboard date filter that compares.",path:`${f}.defaultComparison`,fix:"Leave it out; a measure compares through its own comparison on card.update."});const H=o.defaultComparison===null?null:Sa(G.data);q={defaultComparisonSelection:H?{mode:"period",spec:H}:null};}const Q=o.sheetIds===void 0?void 0:o.sheetIds?ot(o.sheetIds,f):"all",Z={...(o.label!==void 0?{label:o.label}:{}),...(o.selection!==void 0||T||K?{definition:_}:{}),...(Q?{scope:gn(w.scope,Ds(Q==="all"?void 0:Q),new Set([...Ca(g).values()].filter(G=>G.sheetKind==="document").map(G=>G.sheetId)))}:{}),...(T||q?{values:{...(T?{defaultChanged:!0}:{}),...q,target:{}}}:{})};O({op:"filter.update",filterId:p,settings:Z,changeIndex:l},f),Q&&se.set(p,{sheetIds:Q,changeIndex:l}),(T||q)&&Ea.set(p,{changeIndex:l,statedComparison:!!(q!=null&&q.defaultComparisonSelection)}),T&&xe.set(p,{values:o.defaultValues,period:o.defaultPeriod,...(o.defaultCondition!==void 0?{condition:o.defaultCondition}:{}),changeIndex:l}),c.push({ref:o.filterId,kind:"filter",id:p,title:w.label,changeIndex:l});break;}case"filter.remove":{const h=Te(o.filterId,o.cardId,f);if(h){we(h.card.id,(h.card.inlineFilters??[]).filter(w=>w.id!==h.filter.id),l,f,!0),c.push({ref:o.filterId,kind:"filter",id:h.filter.id,title:h.filter.title,changeIndex:l});break;}const p=j(o.filterId,`${f}.filterId`),v=((Ba=(g.inputs??[]).find(w=>w.id===p))==null?void 0:Ba.label)??"";O({op:"filter.remove",filterId:p,changeIndex:l},f),c.push({ref:o.filterId,kind:"filter",id:p,title:v,changeIndex:l});break;}case"filter.bind":{const h=j(o.filterId,`${f}.filterId`),p=je(g,h,void 0,$);p!=null&&p.editable||y({code:"filter_not_editable",message:p&&!p.editable?p.notEditable.message:"This filter can't be changed through the MCP.",path:`${f}.filterId`,fix:"Tell the user to change it in the editor; removing or excluding it works."});const v=Fe(o.cardId,`${f}.cardId`),w=_a(g,v).card,_=Ce(g).findFilterInput({inputId:h}),T=_&&Xe(_.input,w,$).reach==="relationshipApplied",C=await pd(w,o.field,a,`${f}.field`,y,T?p.label:void 0);O({op:"filter.bind",filterId:h,cardId:v,binding:{kind:"bound",cardId:v,bindingId:a.newId(),target:C},changeIndex:l},f),c.push({ref:o.filterId,kind:"filter",id:h,title:p.label,changeIndex:l});break;}case"layout.arrange":{const h=o.sheetId?Oe(o.sheetId,`${f}.sheetId`):(()=>{const p=Ue();return p.length!==1&&y({code:p.length?"sheet_required":"sheet_not_a_grid",message:p.length?"This dashboard has several grid sheets; say which one to arrange.":"This dashboard has no grid sheet to arrange.",path:`${f}.sheetId`,fix:p.length?"Send sheetId: one of details.sheets.":"Add a sheet with sheet.add earlier in this list.",details:{sheets:Se()}}),p[0];})();O({op:"layout.arrange",sheetId:h.id,...(o.keepOrder?{keepOrder:!0}:{}),changeIndex:l},f);break;}case"layout.tabs":{const h=o.cardIds.map((K,q)=>U(K,`${f}.cardIds[${q}]`)),p=(K,q,Q=`${f}.cardIds`)=>y({code:"layout_invalid",message:K,path:Q,fix:q});new Set(h).size!==h.length&&p("Each card is named once in tabs.","Name two or more different cards, each once.");const v=h.map((K,q)=>he(g,K)??p("A Document section's card can't be a tab.","Name cards on a grid sheet.",`${f}.cardIds[${q}]`)),w=v[0].sheet;v.some(K=>K.sheet.id!==w.id)&&p("Tabs are cards on one sheet.","Name cards on one sheet; a card moves to another sheet in the editor."),v.some(K=>ta(K.frame)&&K.frame.cards.length>1)&&p("A custom visual's inputs stay in its spot.","Name cards that aren't a custom visual's inputs, or arrange them in the editor.");const _=v[0].frame,T=v[0].card;c.push({ref:o.cardIds[0],kind:"card",id:T.id,title:T.title??"",changeIndex:l});const C=Us(_);if(h.every((K,q)=>C[q]===K))break;const L=[...new Map(v.map(K=>[K.frame.id,K.frame])).values()].filter(K=>K.visualId);L.length&&n.push({code:"detaches_linked_visual",message:"Moving these cards makes the tiles they leave or join local to this dashboard; they stop following their library visuals.",path:f,details:{cardIds:L.flatMap(K=>K.cards.map(q=>q.id))}}),T.type==="kpi"&&v.slice(1).some(K=>K.card.type==="text")&&n.push({code:"tabs_show_as_kpi_info",message:`A text card in ${qe(T.title)}'s spot shows as the KPI's info, not as a tab.`,path:f,fix:"Put another card first if the text should be a tab of its own."}),O({op:"layout.tabs",sheetId:w.id,cardIds:h,changeIndex:l},f);break;}case"layout.untab":{const h=U(o.cardId,`${f}.cardId`),p=he(g,h);if(p||y({code:"layout_invalid",message:"A Document section's card has no spot of its own.",path:`${f}.cardId`,fix:"Name a card on a grid sheet."}),ta(p.frame)&&p.frame.cards.length>1&&y({code:"layout_invalid",message:"A custom visual's inputs stay in its spot.",path:`${f}.cardId`,fix:"Arrange a custom visual in the editor."}),c.push({ref:o.cardId,kind:"card",id:h,title:p.card.title??"",changeIndex:l}),p.frame.cards.length<2)break;p.frame.visualId&&n.push({code:"detaches_linked_visual",message:`Taking "${p.card.title}" out of its tabs makes them local to this dashboard; they stop following their library visual.`,path:f,details:{cardIds:p.frame.cards.map(v=>v.id)}}),O({op:"layout.untab",cardId:h,newFrameId:a.newId(),changeIndex:l},f);break;}case"filter.exclude":{const h=j(o.filterId,`${f}.filterId`),p=Fe(o.cardId,`${f}.cardId`),v=((ja=(g.inputs??[]).find(w=>w.id===h))==null?void 0:ja.label)??"";O({op:"filter.exclude",filterId:h,cardId:p,changeIndex:l},f),c.push({ref:o.filterId,kind:"filter",id:h,title:v,changeIndex:l});break;}case"highlight.add":case"highlight.remove":{const h=U(o.cardId,`${f}.cardId`),{card:p}=E(h,f),{op:v,cardId:w,..._}=o,T=await Y({cardId:h,cardRef:o.cardId,request:{highlights:o.op==="highlight.add"?{add:[_]}:{remove:[o.ruleId]}},queryLabels:[],index:l,path:f}),C=(Wa=(Ka=T==null?void 0:T.highlights)==null?void 0:Ka.add)==null?void 0:Wa[0];c.push({ref:o.cardId,kind:"card",id:h,title:p.title??"",changeIndex:l,...(C?{ruleId:C.id}:{})});break;}case"sheet.add":{const h=a.newId();o.kind!=="table"&&o.card&&y({code:"invalid_change",message:"Only a Table sheet is added with a card.",path:`${f}.card`,fix:'Send kind "table", or add the card with card.add after the sheet.'}),o.kind==="table"&&!o.card&&y({code:"table_sheet_no_card",message:"A Table sheet is added with its table.",path:`${f}.card`,fix:"Send card: the table, as card.add takes it (type table, detail_table or matrix)."});const p=o.kind==="table"?o.card:void 0,v=p?await nt(p,`${f}.card`):void 0;O({op:"sheet.add",sheet:{id:h,title:o.title,...(v?{kind:"table"}:{})},...(v?{frame:v.frame}:{}),changeIndex:l},f);const w=o.handle??`$sheet_${++A}`;if(m.has(w)&&y({code:"invalid_change",message:`The handle ${w} is defined twice.`,path:`${f}.handle`,fix:"Give each new card, filter or sheet its own handle."}),m.set(w,{kind:"sheet",id:h,title:o.title}),c.push({ref:w,kind:"sheet",id:h,title:o.title,changeIndex:l}),v&&p){const _=p.handle??`$card_${++x}`;m.has(_)&&y({code:"invalid_change",message:`The handle ${_} is defined twice.`,path:`${f}.card.handle`,fix:"Give each new card, filter or sheet its own handle."}),m.set(_,{kind:"card",id:v.card.id,title:p.title}),c.push({ref:_,kind:"card",id:v.card.id,title:p.title,changeIndex:l}),await Ee(v,p,_,l,`${f}.card`);}break;}case"sheet.update":{const h=Ge(o.sheetId,`${f}.sheetId`,{grid:!1});(h.title??"")!==o.title&&O({op:"sheet.update",sheetId:h.id,title:o.title,changeIndex:l},f),c.push({ref:o.sheetId,kind:"sheet",id:h.id,title:o.title,changeIndex:l});break;}case"dashboard.update":{const h=o.title!==void 0&&o.title!==g.title?o.title:void 0,p=o.description===null?g.description?null:void 0:o.description!==g.description?o.description:void 0;(h!==void 0||p!==void 0)&&O({op:"dashboard.update",...(h!==void 0?{title:h}:{}),...(p!==void 0?{description:p}:{}),changeIndex:l},f);break;}case"dashboard.style":{const{op:h,...p}=o;S??(S=a.readOrganizationAppearance?a.readOrganizationAppearance():Promise.resolve(null));const{style:v,organizationAppearance:w}=ai(g,await S),_=Cn({style:v,edit:p,layers:{organizationAppearance:w}});if(_.ok)_.sentences.length&&O({op:"dashboard.style",style:_.style,sentences:_.sentences,changeIndex:l},f);else{const{refusal:T}=_;y({code:T.code,message:T.message,path:T.field==="edit"?f:`${f}.${T.field}`,fix:T.fix});}break;}case"variable.add":{Dt(g,o.name)&&y({code:"variable_name_taken",message:`A variable named ${o.name} is already on this dashboard.`,path:`${f}.name`,fix:"Choose another name, or change it with variable.update."});const h=await ks({id:a.newId(),name:o.name,...(o.label?{label:o.label}:{}),query:o.query,get:o.get,...(o.presentation?{presentation:o.presentation}:{}),...(o.emptyText?{emptyText:o.emptyText}:{}),path:f},g,re);O({op:"variable.add",variable:h,changeIndex:l},f),c.push({ref:o.name,kind:"variable",id:h.id,title:h.name,changeIndex:l});break;}case"variable.update":{const h=Gr(g,o.name,`${f}.name`,re),p=o.rename??h.name,v={...(o.rename!==void 0?{name:o.rename}:{}),...(o.label!==void 0?{label:o.label}:{}),...(o.presentation!==void 0?{presentation:o.presentation}:{}),...(o.emptyText!==void 0?{emptyText:o.emptyText}:{})},w={...g,variables:(g.variables??[]).filter(C=>C.id!==h.id)};if(o.query){const C=await ks({id:h.id,name:p,label:o.label===null?void 0:o.label??h.label,query:o.query,get:o.get??h.get,presentation:o.presentation===null?void 0:o.presentation??h.presentation,emptyText:o.emptyText===null?void 0:o.emptyText??h.emptyText,path:f},w,re);v.query=C.query,v.get=C.get;}else if(o.get!==void 0){const C=Yr(h,o.get,w,re,f);v.query=C.query,v.get=C.get;}Object.keys(v).length||y({code:"invalid_change",message:`variable.update on ${h.name} changes nothing.`,path:f,fix:"Send rename, label, query, get, presentation or emptyText."});const _={...h,...Object.fromEntries(Object.entries(v).map(([C,L])=>[C,L??void 0])),id:h.id},T=$a(_,{...w,variables:[...w.variables,_]});T.length&&k(Ii(T,f)),O({op:"variable.update",variableId:h.id,patch:v,changeIndex:l},f),c.push({ref:o.name,kind:"variable",id:h.id,title:p,changeIndex:l});break;}case"variable.remove":{const h=Dt(g,o.name);h||y(wi(g,o.name,`${f}.name`));const p=h,v=Jr(g,p.id);v.places.length&&y({code:"variable_in_use",message:`${p.name} is shown in ${v.words}.`,path:`${f}.name`,fix:"Remove its chips first (card.update with text, or document.text.update), or ask the user whether the chips should read as missing.",details:{places:v.places}}),O({op:"variable.remove",variableId:p.id,changeIndex:l},f),c.push({ref:o.name,kind:"variable",id:p.id,title:p.name,changeIndex:l});break;}case"document.text.update":{const h=Ge(o.sheetId,`${f}.sheetId`,{grid:!1}),{edit:p,unchanged:v}=zr(o,g,h,f,re);if(c.push({ref:o.sheetId,kind:"sheet",id:h.id,title:h.title??"",changeIndex:l}),v)break;O({op:"document.text",sheetId:h.id,edit:p,changeIndex:l},f);break;}case"calculation.add":case"calculation.update":case"calculation.remove":await Bt(o,l,f);break;default:{const h=o;throw new Error(`Unhandled change ${JSON.stringify(h)}`);}}}catch(h){if(!(h instanceof Ae))throw h;}}if(i.length)return{ok:!1,problems:i};const ue=mt(e,d,{...b,...$});if(!ue.ok)return{ok:!1,problems:[{code:"invalid_change",message:ue.failedAt.message,path:`changes[${((Ua=d[ue.failedAt.index])==null?void 0:Ua.changeIndex)??0}]`,fix:"Read the outline again and propose again."}]};for(const l of r){if(D.has(l))continue;const o=he(ue.dashboard,l);if(!o)continue;const f=((Ga=d.find(w=>Aa(w)===l))==null?void 0:Ga.changeIndex)??0,h=Ve(o.card,{sql:!0,calculatedFields:ue.dashboard.calculatedFields??[]}),p=((Qa=ze(o.card))==null?void 0:Qa.type)??xt(o.card.type);h.editable&&("sql"in h.query?!!h.query.sql:"measures"in h.query?h.query.measures.length>0:h.query.columns.length>0)&&((Ha=lt[p])==null?void 0:Ha.forms.includes(bt(h.query)))||i.push({code:"type_not_supported",message:`As changed, "${o.card.title}" would have no query a ${p.replace(/_/g," ")} can run.`,path:`changes[${f}]`,fix:`Send a complete query with the type change: ${((Ya=lt[p])==null?void 0:Ya.forms.map(w=>It[w]).join(" or "))??"a measures query"}.`});}if(i.push(...ld(e,ue.dashboard,d,se,$)),i.push(...cd(ue.dashboard,xe,a.calendar)),i.push(...ur(ue.dashboard,Ea,a.calendar)),i.length)return{ok:!1,problems:i};for(const l of d){if(l.op!=="filter.add"&&!(l.op==="filter.update"&&l.settings.scope))continue;const o=l.op==="filter.add"?l.input.id:l.filterId,f=je(ue.dashboard,o,void 0,$);if(!(f!=null&&f.editable))continue;const h=async _=>{const T=[];for(const C of _){const L=C.datasetName?await a.findRelationshipFields({domainId:f.domainId,fromDataset:f.datasetName,field:f.field,toDataset:C.datasetName}):[];T.push({...C,suggestedFields:L});}return T;},p=_=>_.map(T=>`"${T.title}"`).join(", "),v=f.notReached.filter(_=>_.reason==="sql_no_filter_reference"),w=f.notReached.filter(_=>_.reason!=="sql_no_filter_reference");if(v.length&&n.push({code:"filter_not_reaching_cards",message:`"${f.label}" doesn't reach ${v.length} SQL card${v.length===1?"":"s"} whose SQL doesn't use dashboard filters: ${p(v)}.`,path:`changes[${l.changeIndex??0}]`,fix:"To filter a SQL card, add {{ filters | where }} to its SQL (or {{ filters | and }} after an existing WHERE) with card.update, or leave it unfiltered.",details:{cards:v}}),w.length){const _=await h(w);n.push({code:"filter_not_reaching_cards",message:`"${f.label}" doesn't reach ${_.length} card${_.length===1?"":"s"} on its sheets: ${p(_)}.`,path:`changes[${l.changeIndex??0}]`,fix:"Add filter.bind with one of the suggested fields to reach a card, or leave it unfiltered.",details:{cards:_}});}if((Ja=f.sqlPending)!=null&&Ja.length&&n.push({code:"filter_reach_through_sql",message:`"${f.label}" may reach ${f.sqlPending.length} SQL card${f.sqlPending.length===1?"":"s"} as ${f.sqlPending.length===1?"its":"their"} SQL decides: ${p(f.sqlPending)}.`,path:`changes[${l.changeIndex??0}]`,fix:"Read the card's SQL to tell the user whether it uses this filter.",details:{cards:f.sqlPending}}),(za=f.relationshipPending)!=null&&za.length){const _=await h(f.relationshipPending);n.push({code:"filter_reach_through_relationships",message:`"${f.label}" may reach ${_.length} card${_.length===1?"":"s"} on its sheets through the domain's relationships: ${p(_)}. Whether it applies is decided when each card runs.`,path:`changes[${l.changeIndex??0}]`,fix:"Add filter.bind with one of the suggested fields to make it certain, or leave it to the relationships.",details:{cards:_}});}}if(a.readComparisonDates){const l=a.readComparisonDates,o=/* @__PURE__ */new Map(),f=v=>{const w=o.get(v.dashboard)??/* @__PURE__ */new Map();o.set(v.dashboard,w);const _=w.get(v.card.id);if(_)return _;const T=l(v);return w.set(v.card.id,T),T;};for(const[v,w]of B){const _=(Xa=he(ue.dashboard,v))==null?void 0:Xa.card;if(!_)continue;const T=await f({card:_,dashboard:ue.dashboard});T.dateWindow==="none"&&n.push({code:"comparison_without_date_window",message:`"${_.title||"Untitled"}" compares with an earlier period only while a date range applies to ${((Za=T.comparisonDate)==null?void 0:Za.label)??"its date"}; none does yet.`,path:w,fix:"Add a timeWindow on that date, or a dashboard date filter that reaches the card."});}const h=/* @__PURE__ */new Map();for(const v of d){const w="cardId"in v?v.cardId:"variableId"in v?v.variableId:v.op==="variable.add"?v.variable.id:void 0;typeof w=="string"&&!h.has(w)&&h.set(w,v.changeIndex??0);}const p=((es=d.find(v=>v.op.startsWith("filter.")))==null?void 0:es.changeIndex)??0;n.push(...(await fr({before:e,after:ue.dashboard,changeIndexOf:v=>h.get(v)??p,readComparisonDates:f})));}n.push(...Wr({before:e,after:ue.dashboard,operations:d,context:{...b,...$},reachOptions:$}));const Di=nd(ue.dashboard,d,ue.descriptions,$);return{ok:!0,operations:d,context:b,dashboard:ue.dashboard,detaches:ue.detaches,refs:c,descriptions:Di,changedCardIds:r,requires:[...u],warnings:n};}function nd(e,t,a,s){const i=t.filter(u=>u.op==="card.add"||u.op==="sheet.add"&&u.frame);if(!i.length)return[...a];const n=Ta(e,void 0,s);if(!n.length)return[...a];const d=u=>Me(u.map(r=>`"${r}"`)),c=/* @__PURE__ */new Map();for(const u of i){const r=Aa(u);if(!r||u.changeIndex===void 0)continue;const m=n.filter(I=>I.reaches.includes(r)).map(I=>I.label),b=I=>n.filter(F=>{var y;return"notReached"in F&&((y=F.notReached)==null?void 0:y.some(M=>M.cardId===r&&M.reason==="sql_no_filter_reference"===I));}).map(F=>F.label),$=b(!1),g=b(!0),S=n.filter(I=>{var F;return(F=I.relationshipPending)==null?void 0:F.some(y=>y.cardId===r);}).map(I=>I.label),x=n.filter(I=>{var F;return(F=I.sqlPending)==null?void 0:F.some(y=>y.cardId===r);}).map(I=>I.label),A=[...(m.length?[`The dashboard's ${d(m)} filter${m.length===1?" applies":"s apply"} to it.`]:[]),...($.length?[`${d($)} ${$.length===1?"doesn't":"don't"} reach it.`]:[]),...(g.length?[`${d(g)} ${g.length===1?"doesn't":"don't"} reach it: its SQL doesn't use dashboard filters.`]:[]),...(S.length?[`${d(S)} may reach it through the domain's relationships.`]:[]),...(x.length?[`${d(x)} may apply through its SQL.`]:[])];A.length&&c.set(u.changeIndex,A.join(" "));}return a.map(u=>{const r=u.changeIndex===void 0?void 0:c.get(u.changeIndex);return r?{...u,sentence:`${u.sentence} ${r}`}:u;});}function Aa(e){var t,a,s;if(e.op==="card.update"||e.op==="card.remove")return e.cardId;if(e.op==="card.add")return(t=e.frame.cards[0])==null?void 0:t.id;if(e.op==="sheet.add")return(s=(a=e.frame)==null?void 0:a.cards[0])==null?void 0:s.id;}function rd(e){return Object.fromEntries(Uo.flatMap(t=>e[t]===void 0?[]:[[t,e[t]]]));}function dd(e,t){if(!t.length||!e.config)return e;const a={...e.config},s=[];if(a.matrix){const n=a.matrix,d=Yo(n),c=[...n.spec.rows,...n.spec.columns],u={...n.presentation.levelLabels},r={...n.presentation.measureLabels};for(const{key:m,label:b}of t){if(m.role==="metric"){const $=d.measures.findIndex(g=>Ft(g,m));if($<0)continue;r[n.spec.measures[$].id]=b;}else{const $=d.levels.findIndex(g=>Ft(g,m));if($<0)continue;u[c[$].id]=b;}s.push(m);}return a.matrix={...n,presentation:{...n.presentation,levelLabels:u,measureLabels:r}},{...e,config:a,statedLabels:s};}const i={metric:"metricColumns",group_by:"groupByColumns",detail:"detailColumns"};for(const{key:n,label:d}of t){const c=[...(a[i[n.role]]??[])],u=Xs(n.role,c).findIndex(r=>Ft(r,n));u<0||(c[u]=Nn(c[u],d),a[i[n.role]]=c,s.push(n));}return{...e,config:a,statedLabels:s};}function ld(e,t,a,s,i){var A;const n=[],d=new Map(_e(t).map(I=>[I.cardId,I])),c=Ca(t),u=Ce(t),r=I=>{var F,y;return((y=(F=t.sheets)==null?void 0:F.find(M=>M.id===I))==null?void 0:y.title)??I;},m=(I,F)=>{var y;return((y=[...a].reverse().find(M=>Aa(M)===F||"filterId"in M&&M.filterId===I))==null?void 0:y.changeIndex)??0;},b=(I,F)=>{const y=u.findFilterInput({inputId:I}).input,M=d.get(F),R=`"${M.card.title??""}"`,O=`"${y.label}"`;if(M.kind==="documentSectionCard")return{reason:"document_section",message:`${R} is in a Document section, which takes only the filters its Document sheet shows.`,fix:"Tell the user to change where the filter shows in the editor."};const Y=c.get(M.sheetId);if(Y&&!Zs(y,Y))return{reason:"outside_sheets",message:`${O} isn't shown on "${r(M.sheetId)}", so it can't filter ${R}.`,fix:"Show it on that sheet first with filter.update sheetIds (null for every sheet), in the same proposal."};const D=va(y,M.card);switch(D.status){case"incompatible":return{reason:"incompatible_field",message:`${R} can't take ${O}'s values on that field: their types differ.`,fix:"Bind a field of the same type (filter.bind)."};case"stale":return{reason:"field_not_on_card",message:`${R} doesn't have the field ${O} is bound to.`,fix:"Bind a field the card has (filter.bind), or exclude the card (filter.exclude), in the same proposal."};case"ambiguous":return{reason:"ambiguous_field",message:`${R} has more than one field ${O} could filter.`,fix:"Bind the field it should use (filter.bind), or exclude the card (filter.exclude), in the same proposal."};case"relationship":{const E=Xe(y,M.card,i);return E.reach==="blocked"?{reason:"relationship_route_changed",message:`The relationships ${R} used for ${O} changed in the domain.`,fix:"Tell the user to choose the relationship again in the filter's Cards tab."}:E.reason==="relationship_ambiguous"?{reason:"relationship_ambiguous",message:`${O} connects to ${R} through more than one path.`,fix:"Tell the user to choose a path in the filter's Cards tab, or bind a field the card has (filter.bind)."}:{reason:"relationship_pending",message:`${O} may reach ${R} through the domain's relationships; whether it applies is decided when the card runs.`,fix:"Bind a field the card has (filter.bind) to make it certain, or leave it to the relationships."};}case"excluded":case"bound":case"unsupportedTarget":case"sql":case"automatic":case"passthrough":case"notApplicable":return{reason:"filter_settings_override",message:`${O} still wouldn't filter ${R}: its settings leave that card out.`,fix:"Tell the user to change the filter's settings in the editor."};default:{const E=D;throw new Error(`Unhandled filter card target ${String(E.status)}`);}}},$=/* @__PURE__ */new Set(),g=/* @__PURE__ */new Map();for(const I of a)(I.op==="filter.bind"||I.op==="filter.exclude")&&g.set(`${I.filterId}|${I.cardId}`,I);for(const I of g.values()){const F=je(t,I.filterId,void 0,i),y=d.get(I.cardId);if(!F||!y)continue;const M=F.reaches.includes(I.cardId);if(I.op==="filter.bind"?M:!M)continue;$.add(`${I.filterId}|${I.cardId}`);const R=I.op==="filter.bind"?b(I.filterId,I.cardId):{reason:"filter_settings_override",message:`"${F.label}" would still filter "${y.card.title??""}".`,fix:"Tell the user to change the filter's settings in the editor."};n.push({code:"filter_not_editable",message:R.message,path:`changes[${I.changeIndex??0}]`,fix:R.fix,details:{reason:R.reason,cardId:I.cardId}});}for(const[I,F]of s){const y=je(t,I,void 0,i);if(!y)continue;const M=y.editable&&((A=y.exceptSheetIds)==null?void 0:A.some(Y=>{var D;return((D=c.get(Y))==null?void 0:D.sheetKind)==="dashboard";})),R=y.editable&&!M?y.sheetIds:void 0,O=F.sheetIds==="all"?"all":[...F.sheetIds].sort();Be(R==="all"||!R?R:[...R].sort(),O)||n.push({code:"filter_not_editable",message:`"${y.label}" wouldn't show on the sheets asked for. Change where it shows in the editor.`,path:`changes[${F.changeIndex}].sheetIds`,fix:"Tell the user to change the filter's sheets in the editor.",details:{reason:"filter_settings_override",...(R?{sheetIds:R}:{})}});}const S=Ce(e),x=I=>I==="blocked"||I==="ambiguous";for(const I of u.inputs){const F=I.input.id;for(const y of u.reachedCards({inputId:F})){if($.has(`${F}|${y.cardId}`)||!x(Xe(I.input,y.card,i).reach))continue;const M=S.findFilterInput({inputId:F}),R=M&&S.reachedCards({inputId:F}).find(Y=>Y.cardId===y.cardId);if(M&&R&&x(Xe(M.input,R.card,i).reach))continue;const O=b(F,y.cardId);n.push({code:"invalid_change",message:`${O.message} The card would stop showing data while "${I.input.label}" has a value.`,path:`changes[${m(F,y.cardId)}]`,fix:O.fix,details:{reason:O.reason,filterId:F,cardId:y.cardId}});}}return n;}function cd(e,t,a){const s=[],i=Ce(e),n=_e(e).flatMap(d=>d.kind==="frameCard"?[d.card]:[]);for(const[d,c]of t){const u=c.pinned?void 0:i.findFilterInput({inputId:d}),r=c.pinned?oi(n,c.pinned.filterId,c.pinned.cardId):void 0,m=(r==null?void 0:r.kind)==="found"?r:void 0;if(!u&&!m)continue;const b=u?u.input.filter:m.filter,$=u?u.input.label:m.filter.title,g=u?Lt({dashboard:e,target:{kind:"dashboardInput",input:u.input,scope:{}},calendar:a}).value:Ms(m.filter,a),S=b.dateSelectionMode,x=S==="day"?"its date picker takes one day":S==="months"?"its month picker takes one whole month":void 0,A=(I,F)=>s.push({code:"filter_not_editable",message:I,path:`changes[${c.changeIndex}]`,fix:F,details:{reason:"default_not_applied",...(S?{datePicker:S}:{})}});if(c.condition!==void 0){const I=c.condition?Js(c.condition):void 0,F=I!=null&&I.ok?I.condition:null,y=g&&g.operation!=="in"&&g.operation!=="not in"?{operation:g.operation,values:(g.values??[]).map(Number)}:null;JSON.stringify(F)!==JSON.stringify(y)&&A(F?`"${$}" wouldn't load with that default condition.`:`"${$}" would still load with a default.`,"Tell the user to change the filter's default in the editor.");continue;}if(c.period){const I=xa(g&&"relativeMeta"in g?g.relativeMeta:void 0);(!I||Bn(c.period)||!ri(I,c.period))&&A(`"${$}" wouldn't load with that default${x?`: ${x}`:""}.`,x?"Ask for a default the picker can take, or tell the user to make it a date range in the editor.":"Tell the user to change the filter's default in the editor.");}else if(c.values){const I=F=>JSON.stringify((F??[]).map(String).sort());(!g||I(g.values)!==I(c.values))&&A(`"${$}" wouldn't load with those values.`,"Tell the user to change the filter's default in the editor.");}else(Mt(b.dataType)?c.period===null:c.values===null)&&g&&A(`"${$}" would still load with a default.`,"Tell the user to change the filter's default in the editor.");}return s;}function aa(e){const t=e.measures;if(!Array.isArray(t))return{query:e,calculations:[]};const a=[],s=t.map((i,n)=>{if(!i||typeof i!="object")return i;const{comparison:d,transform:c,...u}=i;return d===void 0&&c===void 0?i:(a.push({index:n,calculations:{...(d!==void 0?{comparison:d}:{}),...(c!==void 0?{transform:c}:{})}}),Object.keys(u).length===1&&typeof u.name=="string"?u.name:u);});return{query:{...e,measures:s},calculations:a};}function As(e){var a,s;const t=(s=(a=e.config)==null?void 0:a.groupByColumns)==null?void 0:s.find(i=>Mo(i.dataType||"")==="date");return{comparisonDate:t?{name:t.name,label:t.label||t.name}:null,dateWindow:"unknown"};}function ud(e,t){if("sql"in t)return[];const a=e,s=(...n)=>new Set(n.flatMap(d=>Array.isArray(d)?d:d?[d]:[]).map(d=>De(d,t.datasetName))),i={metric:s(a.measures),group_by:s(a.dimensions,a.dateField),detail:s(a.columns)};return ht(t).filter(n=>i[n.key.role].has(n.key.field));}function fd(e,t,a,s){const i=Object.fromEntries(Object.entries(t).filter(([,b])=>b!=null)),n=bt(i),d=bt(e),c=b=>ha[b].safeParse(i);if(!e||n&&n!==d){const b=n??d,$=b?c(b):void 0;return $!=null&&$.success?$.data:s({code:e?"query_form_mismatch":"type_not_supported",message:e?"This patch changes the query's form (measures, records or SQL) without a complete query.":"This card's current query can't be patched; send a complete query.",path:a,fix:"Send a complete query of the new form: domainId, datasetName and measures (or columns), or connectionId and sql."});}const u={...e};for(const[b,$]of Object.entries(t))$!==void 0&&($===null?delete u[b]:u[b]=$);const r=Si(e,t);r&&delete u.timeWindow;const m=ha[d].safeParse(u);if(!m.success){const b=m.error.issues[0];return s({code:(b==null?void 0:b.code)==="unrecognized_keys"?"query_form_mismatch":"invalid_change",message:(b==null?void 0:b.message)??"The merged query is not valid.",path:b?_i(a,b):a,fix:"Patch only keys of the card's query form, or send a complete query of a new form."});}return r?{...m.data,timeWindow:r}:m.data;}function Si(e,t){if(!(!e||"sql"in e||t.timeWindow!==void 0))return e.timeWindow;}function Ds(e){return e?{kind:"sheets",sheetIds:e}:{kind:"allSheets",sheetKinds:["dashboard"]};}function sa(e,t,a,s){return["date","datetime","timestamp"].some(d=>fa(t.dataType).includes(d))||s({code:"invalid_change",message:"defaultPeriod is for date filters.",path:a,fix:"Use defaultValues for this field."}),xi(e,{use:"filterDefault",columnHasTime:hd(t)},a,s);}function xi(e,t,a,s){const i=ni(e,t);return i.ok?i.window:s({code:"invalid_change",message:i.refusal.message,fix:i.refusal.fix,path:i.refusal.path?`${a}.${i.refusal.path}`:a});}function hd(e){return Vs({dataType:e.dataType})==="datetime";}function md(e){var t,a,s;return(s=(a=(t=e==null?void 0:e.filters)==null?void 0:t.conditions)==null?void 0:a.find(i=>i.relativeMeta))==null?void 0:s.field;}async function pd(e,t,a,s,i,n){const d=Ro(e),c=d.kind==="config"?d.executableSources:d.kind==="sql"?d.pinnedCatalogSources.map(x=>x.source):[],u=Le(e),r=typeof t=="string"?(u==null?void 0:u.kind)==="semantic"?u.datasetName:void 0:t.datasetName,m=c.find(x=>x.kind==="semantic"&&fa(x.datasetName)===fa(r));if((!m||m.kind!=="semantic")&&n)return i({code:"field_not_found",message:`"${n}" already filters "${e.title}" through the domain's relationships, so it needs no binding; the card doesn't read ${r?`the dataset ${r}`:"that dataset"}.`,path:s,fix:"Leave out this filter.bind: the filter applies to the card as it is."});if(!m||m.kind!=="semantic")return i({code:"field_not_found",message:`"${e.title}" doesn't read ${r?`the dataset ${r}`:"a dataset"}.`,path:s,fix:"Name a field of the card's own dataset, or { name, datasetName } for a dataset its query joins."});const b=await a.loadCardSource({domainId:m.domainId,datasetName:m.datasetName}),$=typeof t=="string"?t:t.name,g=b?qt(b.fields,$,m.datasetName):void 0,S=g?kn(m,{column_name:g.name,data_type:g.dataType,...(g.sourceField?{sourceField:g.sourceField}:{})}):void 0;return S||i({code:"field_not_found",message:`"${$}" isn't a field of ${m.datasetName}.`,path:s,fix:"Use one of details.available, or read semaphor_get_dataset_schema.",details:{available:((b==null?void 0:b.fields)??[]).slice(0,20).map(x=>x.name)}});}function gd(e,t,a,s){const i=mr(hr(a),e,{relationshipReach:s});if(i.reached||i.reach==="relationship"||i.reach==="sqlTemplate")return;const n=e.title||"This card";if(i.reach==="blocked"||i.reach==="ambiguous")return`A filter on ${t} would stop "${n}" from running${i.message?`: ${i.message}`:""}.`;const d=No(e),c=i.reason==="sql_no_filter_reference"?"its SQL uses no filter":i.reason?Tn(i.reason,d?{name:d.name,label:d.label}:void 0).toLowerCase():`it doesn't read ${t} or reach it through a relationship`;return`A filter on ${t} would never filter "${n}": ${c}.`;}const bd={max:fs,what:"A proposal that creates a dashboard",fix:`Create with the first ${fs}, then change the new dashboard in a second proposal.`};async function El(e,t){const a=c=>c&&typeof c=="object"?c.op:void 0,s=e.changes.flatMap((c,u)=>a(c)==="dashboard.update"?[{code:"invalid_change",message:"A create names its dashboard in create, not with dashboard.update.",path:`changes[${u}].op`,fix:"State the title and description in create."}]:[]);if(s.length)return{ok:!1,problems:s};const i=vd(e,t),n=await Ci(i,e.changes,t,{limit:bd});if(!n.ok)return n;const d=yd(n,e.changes);return{...d,seed:i,sentence:$d(d.dashboard)};}function yd(e,t){if(t.some(n=>{if(!n||typeof n!="object")return!1;const{op:d}=n;return d==="layout.arrange"||d==="card.add"&&("width"in n||"position"in n);}))return e;const s=(e.dashboard.sheets??[]).filter(n=>wa(n)&&(n.frames??[]).length>0).map(n=>({op:"layout.arrange",sheetId:n.id}));if(!s.length)return e;const i=mt(e.dashboard,s,e.context);if(!i.ok)throw new Error(`Arranging a new dashboard failed: ${i.failedAt.code}`);return{...e,operations:[...e.operations,...s],dashboard:i.dashboard,descriptions:[...e.descriptions,...i.descriptions]};}function vd(e,t){const a=e.changes.some(s=>s&&typeof s=="object"&&s.op==="sheet.add");return{id:e.dashboardId,title:e.create.title,...(e.create.description?{description:e.create.description}:{}),interactionDefaults:{clickToFilter:"on"},inputs:[],sheets:a?[]:[{id:t.newId(),title:"Sheet 1"}]};}const ia=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function $d(e){const t=e.sheets??[],a=t.reduce((n,d)=>n+(d.frames??[]).reduce((c,u)=>{var r;return c+(((r=u.cards)==null?void 0:r.length)??0);},0),0),s=(e.inputs??[]).filter(n=>n.kind==="filter").length,i=[ia(t.length,"sheet"),ia(a,"card"),...(s?[ia(s,"filter")]:[])];return`Creates a private dashboard ${qe(e.title)} with ${Me(i)}.`;}const wd=50;function Nl(e,t){var R,O,Y;const a=(R=t.sheetIds)!=null&&R.length?new Set(t.sheetIds):void 0,s=(O=t.cardIds)!=null&&O.length?new Set(t.cardIds):void 0,i=(e.sheets??[]).filter(D=>!a||a.has(D.id)),n=_e(e).filter(D=>(!a||a.has(D.sheetId))&&(!s||s.has(D.cardId))),d=n.length>(t.maxQueryCards??wd),c=new Map((e.sheets??[]).flatMap(D=>(D.frames??[]).map(E=>[E.id,E]))),u=/* @__PURE__ */new Map(),r=D=>{(D==null?void 0:D.kind)==="semantic"&&u.set(`${D.domainId}|${D.datasetName}`,{domainId:D.domainId,datasetName:D.datasetName});},m=new Map((e.sheets??[]).map(D=>[D.id,ra({dashboard:e,place:{kind:D.kind==="document"?"document":"sheet",sheetId:D.id}})])),b=D=>({catalog:D,inputs:e.inputs,variables:e.variables}),$=D=>b(m.get(D)),g=/* @__PURE__ */new Map(),S=(D,E)=>{if(D.kind==="document")return $(D.id);const B=ra({dashboard:e,place:{kind:"sheet",sheetId:D.id,cardId:E}});return g.set(`${D.id}:${E}`,B),b(B);},x=i.map(D=>({sheetId:D.id,title:D.title??"",kind:Xo(D),...(D.kind==="document"?_d(D,$(D.id)):wa(D)?{layout:xd(D)}:{}),cards:n.filter(E=>E.sheetId===D.id).map(E=>{var V,U;const B=E.card,W=E.kind==="frameCard"?(V=c.get(E.frameId))==null?void 0:V.visualId:void 0,N=W?{linkedVisualId:W}:{},J={cardId:E.cardId,title:B.title??""};if(E.kind!=="frameCard"){const j=Le(B);return r(j),{...J,..._t(B),...(j?{source:j}:{}),editable:!1,notEditable:E.kind==="documentSectionCard"?{reason:"document_section",message:"Cards in Document sections can't be changed through the MCP yet. Change them in the editor."}:{reason:"not_expressible",message:"This card isn't in a tile, so it can't be changed through the MCP. Change it in the editor.",detail:"a card outside a tile"}};}if(B.type==="text"){const j=zs(B,S(D,B.id));return j.editable?{...J,type:"text",...N,editable:!0,text:j.text,...(j.editorOnly.length?{editorOnly:j.editorOnly}:{})}:{...J,..._t(B),...N,editable:!1,notEditable:{reason:"text",message:j.message}};}const P=Ve(B,{sql:t.sql,calculatedFields:e.calculatedFields??[]});if(r(P.source),!P.editable)return{...J,..._t(B),...(P.source?{source:P.source}:{}),...N,editable:!1,notEditable:{reason:P.reason,message:P.reason==="not_expressible"||P.reason==="type_not_supported"?`${P.message} ${Ys}`:P.message,...(P.detail?{detail:P.detail}:{})},...(B.type==="customVisual"&&!d?{visual:$s(B,t.customVisualNames)}:{})};const k=d?void 0:ba(B);return{...J,..._t(B),type:P.type,source:P.source,...N,editable:!0,...(d?{}:{query:P.query,...(P.matrix?{matrix:P.matrix}:{}),...(P.timeWindowReadOnly?{timeWindowReadOnly:P.timeWindowReadOnly}:{}),...((U=B.inlineFilters)!=null&&U.length?{pinnedFilters:yr(B,Et(t.calendar,t.updatedAt))}:{}),...(B.type==="customVisual"?{visual:$s(B,t.customVisualNames)}:{})}),...k};})})),A=Ta(e,Et(t.calendar,t.updatedAt),{...(t.relationshipReach?{relationshipReach:t.relationshipReach}:{})});for(const D of A)D.editable&&u.set(`${D.domainId}|${D.datasetName}`,{domainId:D.domainId,datasetName:D.datasetName});const I=Cd(e,t,new Map([...m,...g]));for(const D of e.variables??[]){const E=ua(D);(E==null?void 0:E.kind)==="semantic"&&u.set(`${E.domainId}|${E.datasetName}`,{domainId:E.domainId,datasetName:E.datasetName});}const F=(e.variables??[]).filter(D=>{var E;return((E=ua(D))==null?void 0:E.kind)==="physical";}).map(D=>D.name),y=(e.sheets??[]).some(D=>{var E;return(E=D.document)==null?void 0:E.sections.some(B=>{var W,N;return B.type==="text"&&(((W=B.style)==null?void 0:W.fontWeight)||((N=B.style)==null?void 0:N.color));});}),M=[...(F.length?[`a variable on a table or view source (${F.join(", ")}): changed in the editor`]:[]),...(y?["a Document text section's weight or color: changed in the editor"]:[]),"a dashboard calculated field over more than one dataset: built in the editor, or added to the domain","a calculated field on a Matrix: use a domain calculation, or build it in the editor","a date grouping on a dashboard calculated field, or a condition on a dashboard calculated measure: set in the editor","click to filter (turning clicks on or off, which fields a click carries, binding a field, excluding a card): changed in the editor","a date before or after a point measured from today, on a card filter or a filter default: changed in the editor","a filter's option list (where its values come from, Connect filters through): changed in the editor","a card on a database table instead of a dataset, or a card with joins set in the editor (Join a table, Set up join): built and changed in the editor"];return{dashboardId:t.dashboardId,title:e.title??"",...(e.description?{description:e.description}:{}),updatedAt:t.updatedAt,access:t.access,datasets:[...u.values()],sheets:x,filters:A,variables:I,style:Id(e,t),...((Y=e.calculatedFields)!=null&&Y.length?{calculatedFields:kd(e)}:{}),editorOnly:M,...(d?{truncated:!0}:{})};}function Id(e,t){const{style:a,organizationAppearance:s}=ai(e,t.organizationAppearance);return{set:rr(a),shows:An({organizationAppearance:s,dashboardStyle:a},"light").shows};}function Rs(e,t){const a=tn(t);return a?{...e,style:a}:e;}function _d(e,t){const a=e.document;if(!a)return{};const s=i=>{var n;return(((n=a[i])==null?void 0:n.blocks)??[]).flatMap(d=>d.type==="text"&&d.role?[Rs({role:d.role,text:Ot(d.content,{...t,documentInputs:a.inputs})},d.style)]:[]);};return{header:s("header"),footer:s("footer"),textSections:a.sections.flatMap(i=>i.type==="text"?[Rs({sectionId:i.id,text:Ot(i.content,{...t,documentInputs:a.inputs})},i.style)]:[])};}function Cd(e,t,a){const s=ei(e),i=r=>s.filter(({ref:m})=>r(m)).map(({place:m,where:b})=>({sheetId:m.sheetId,where:b.kind,id:b.kind==="card"?b.cardId:b.kind==="section"?b.sectionId:b.blockId})),n=/* @__PURE__ */new Map();for(const r of a.values())for(const m of r.entries){const b=n.get(m.name);(!b||b.kind==="report"&&m.kind!=="report")&&n.set(m.name,m);}const d=[...n.values()].filter(r=>r.kind==="input").map(r=>({name:r.name,kind:"input",words:r.input.kind==="control"?`The ${r.label} control's value`:`The ${r.label} filter's value`,parts:[...r.parts],usedIn:i(m=>m.source==="input"&&m.inputId===r.input.id||m.source==="dashboardInputAlias"&&m.variableName===r.name),editable:!1})),c=[...n.values()].filter(r=>r.kind==="report").map(r=>({name:r.name,kind:"report",words:Sd[r.reportKey],parts:[],usedIn:i(m=>m.source==="documentMeta"&&m.key===r.reportKey),editable:!1})),u=(e.variables??[]).map(r=>{const m=vi(r,{sql:t.sql}),b=$a(r,e)[0],$=Zo(r.presentation);return{name:r.name,kind:"data",words:Fn(r),parts:bn(r),...($?{presentation:$}:{}),usedIn:i(g=>g.source==="data"&&g.variableId===r.id),editable:m.editable,...(m.editable?{}:{notEditable:{reason:m.reason,message:m.message}}),...(b?{broken:`${b.message} ${b.fix}`}:{})};});return[...d,...c,...u];}const Sd={generatedAt:"When the report was generated",pageNumber:"The page number (Documents)",pageCount:"The page count (Documents)"};function _t(e){const t=ze(e);return t?{type:t.type,...t.properties}:{type:xt(e.type)};}function xd(e){const t=new Map((e.frames??[]).map(a=>[a.id,a]));return Gn(e).rows.map(a=>({tiles:a.tiles.map(s=>{const i=t.get(s.frameId);return{cardIds:i?Us(i):[],width:s.width};})}));}function kd(e){return(e.calculatedFields??[]).flatMap(t=>{const a=Hs(t),s=en(t);if(!a||!s)return[];const i=Qs(e,Tt(t));return[{domainId:s.domainId,dataset:s.datasetName,name:a.name,...(a.label?{label:a.label}:{}),...(a.description&&a.description!==`Calculated field: ${a.label}`?{description:a.description}:{}),expression:a.expression,inputs:Object.fromEntries(Object.entries(a.inputs).map(([n,d])=>{var c;return[n,{dataset:d.dataset,field:d.field,...(t.role==="metric"&&((c=t.calculatedFormula)==null?void 0:c.computeStage)!=="row"&&d.aggregate?{aggregate:d.aggregate}:{})}];})),use:a.use,dataType:a.dataType,usedBy:[...i.cards.map(n=>n.cardId),...i.filters.map(n=>n.filterId)]}];});}function me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e);}function Re(e,t){return me(e)&&Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0;}const ve=Re,Td=["metricColumns","groupByColumns","detailColumns","pivotByColumns","sortByColumns"],Fd=["xAxisConfig","yAxisConfig","secondaryYAxisConfig","tooltipConfig","dataLabelsConfig"],Ad='`format` on the matching column in `config.metricColumns`, `groupByColumns` or `detailColumns`; for a SQL or Python card, `preferences.sqlColumns["<column>"].format`',Ct="`preferences.conditionalFormatting`, with columns named by card column id";function Dd(e){return pt(String(e.type))??ka;}function ft(e,t,a){if(a===void 0)return;const s=me(a)?Dd(a).safeParse(a):ka.safeParse(a);if(!s.success)for(const i of s.error.issues){const n=i.code==="unrecognized_keys"?i.keys:[i.path.length?String(i.path[i.path.length-1]):"type"];for(const d of n)e.push({path:[t,...i.path.map(String),...(i.code==="unrecognized_keys"?[d]:[])].join("."),field:d,replacement:d==="locale"?"nothing: the viewer's locale applies":i.code==="unrecognized_keys"?"nothing: the stored format type has no such key":`a value the stored format type accepts (${i.message})`});}}function oa(e,t,a){if(me(a)){for(const s of["dateFormat","customFormat"])ve(a,s)&&e.push({path:`${t}.${s}`,field:s,replacement:"`format` on this column (a temporal bucket or date format)"});ft(e,`${t}.format`,a.format);}}function ki(e,t){const a=[],s=e.config;for(const S of Td){const x=s==null?void 0:s[S];Array.isArray(x)&&x.forEach((A,I)=>oa(a,`${t}.config.${S}[${I}]`,A));}const i=me(s==null?void 0:s.matrix)?s.matrix:void 0,n=me(i==null?void 0:i.presentation)?i.presentation:void 0;for(const S of["measureFormats","levelFormats"]){const x=n==null?void 0:n[S];if(me(x))for(const[A,I]of Object.entries(x))ft(a,`${t}.config.matrix.presentation.${S}.${A}`,I);}ve(n,"conditionalFormatting")&&a.push({path:`${t}.config.matrix.presentation.conditionalFormatting`,field:"conditionalFormatting",replacement:Ct});const d=e.interactionConfig,c=d==null?void 0:d.drillHierarchies;Array.isArray(c)&&c.forEach((S,x)=>{me(S)&&(oa(a,`${t}.interactionConfig.drillHierarchies[${x}].baseField`,S.baseField),Array.isArray(S.steps)&&S.steps.forEach((A,I)=>{me(A)&&oa(a,`${t}.interactionConfig.drillHierarchies[${x}].steps[${I}].field`,A.field);}));});const u=e.preferences;if(!u)return a;const r=`${t}.preferences`;if(ve(u,"formatNumber")){const S=u.formatNumber,x=me(S)&&Object.keys(S).every(A=>A==="colorRanges");a.push(x?{path:`${r}.formatNumber.colorRanges`,field:"colorRanges",replacement:`${Ct} (a rule on the KPI's value)`}:{path:`${r}.formatNumber`,field:"formatNumber",replacement:"`format` on each measure in `config.metricColumns`; for a SQL KPI, `preferences.sqlKpiValue.format`"});}ve(u,"numberAxisFormat")&&a.push({path:`${r}.numberAxisFormat`,field:"numberAxisFormat",replacement:"`valueFormat` on `preferences.yAxisConfig` (or the axis it formats)"}),ve(u,"columnSettings")&&a.push({path:`${r}.columnSettings`,field:"columnSettings",replacement:"`preferences.tablePrefs.columnSettingsMap`, keyed by column"});const m=u.kpiVisualOptions;ve(m,"formatOptions")&&a.push({path:`${r}.kpiVisualOptions.formatOptions`,field:"formatOptions",replacement:"`format` on each measure in `config.metricColumns`; for a SQL KPI, `preferences.sqlKpiValue.format`"}),ve(m,"queryComparisonPolarity")&&a.push({path:`${r}.kpiVisualOptions.queryComparisonPolarity`,field:"queryComparisonPolarity",replacement:"`preferences.sqlKpiValue.comparisonPolarity`"});const b=u.tablePrefs;ve(b,"conditionalFormatting")&&a.push({path:`${r}.tablePrefs.conditionalFormatting`,field:"conditionalFormatting",replacement:Ct});const $=b==null?void 0:b.columnSettingsMap;if(me($))for(const[S,x]of Object.entries($)){if(!me(x))continue;const A=`${r}.tablePrefs.columnSettingsMap.${S}`;for(const I of["numberFormat","dateFormat","inheritMetricFormat"])ve(x,I)&&a.push({path:`${A}.${I}`,field:I,replacement:I==="inheritMetricFormat"?"nothing: a column follows its `format`":Ad});ve(x,"colorRanges")&&a.push({path:`${A}.colorRanges`,field:"colorRanges",replacement:Ct});}for(const S of Fd){const x=u[S];if(me(x)){for(const A of["formatMode","mode","formatOptions"])ve(x,A)&&a.push({path:`${r}.${S}.${A}`,field:A,replacement:`\`preferences.${S}.valueFormat\` (absent means the column's format)`});S==="dataLabelsConfig"&&ve(x,"format")&&a.push({path:`${r}.${S}.format`,field:"format",replacement:"`preferences.dataLabelsConfig.valueFormat`"}),ft(a,`${r}.${S}.valueFormat`,x.valueFormat);}}const g=u.sqlColumns;if(me(g))for(const[S,x]of Object.entries(g))me(x)&&ft(a,`${r}.sqlColumns.${S}.format`,x.format);return me(u.sqlKpiValue)&&ft(a,`${r}.sqlKpiValue.format`,u.sqlKpiValue.format),a;}function Rd(e){const t=`sheets[id=${e.sheetId}]`;switch(e.kind){case"sheetCard":return`${t}.cards[id=${e.cardId}]`;case"frameCard":return`${t}.frames[id=${e.frameId}].cards[id=${e.cardId}]`;case"documentSectionCard":return`${t}.document.sections[id=${e.sectionId}].cards[id=${e.cardId}]`;}}function Ti(e){if(!me(e))return[];if(Array.isArray(e.sheets))return _e(e).map(a=>({card:a.card,at:Rd(a)}));const t=e;return Array.isArray(t.cards)?t.cards.map(a=>({card:a,at:`cards[id=${a.id}]`})):[];}function Pl(e){return Ti(e).flatMap(({card:t,at:a})=>ki(t,a));}function Od(e,t){var n;const a=(n=e.preferences)==null?void 0:n.conditionalFormatting;if(a===void 0)return[];const s=`${t}.preferences.conditionalFormatting`,i=an.safeParse(a);return i.success?sn(e).map(d=>({code:"invalid_conditional_formatting",path:`${s}.rules[id=${d.ruleId}].${d.path}`,message:d.message})):i.error.issues.map(d=>({code:"invalid_conditional_formatting",path:[s,...d.path.map(c=>typeof c=="number"?`[${c}]`:c)].join(".").replace(/\.\[/g,"["),message:d.message}));}function ql(e){return Ti(e).flatMap(({card:t,at:a})=>[...ki(t,a).map(s=>({code:"retired_presentation_field",path:s.path,message:`\`${s.field}\` is retired: use ${s.replacement}.`})),...Od(t,a)]);}const Da=["metricColumns","groupByColumns","detailColumns","pivotByColumns","sortByColumns"],Ed=["xAxisConfig","yAxisConfig","secondaryYAxisConfig","tooltipConfig","dataLabelsConfig"];function ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e);}function Fi(e,t){return JSON.stringify(e)===JSON.stringify(t);}function et(e,t){const a=s=>ce(s)?Object.fromEntries(Object.keys(s).sort().map(i=>[i,a(s[i])])):s;return Fi(a(e),a(t));}function Nt(e){const t=jn(e);return t==="date"||t==="datetime";}function Ai(e){var t,a;return!!((t=e.sql)!=null&&t.trim()||(a=e.python)!=null&&a.trim());}function Nd(e){return e.type==="kpi"&&fn(e);}function ma(e){return e.type==="table"||e.type==="detailTable";}function pe(e,t){var s;const a=(s=e.config)==null?void 0:s[t];return Array.isArray(a)?a:[];}function Pd(e,t){for(const a of Da){const s=pe(e,a).indexOf(t);if(s>=0)return`config.${a}[${s}]`;}}function it(e,t){let a=!1;for(const s of t)Object.prototype.hasOwnProperty.call(e,s)&&(delete e[s],a=!0);return a;}function Pt(e,t,a,s){t.format=a,t.formatOrigin="override",e.changes.push({path:s,action:"moved",to:`${Pd(e.card,t)??"config"}.format`});}function Ra(e){if(ce(e))return gt(e);}function pa(e,t,a){if(!(!Re(t,"dateFormat")&&!Re(t,"customFormat"))){if(Nt(t.dataType)&&t.format==null&&t.dateFormat!=null){const s=cn({fieldId:t.id,dataType:t.dataType,granularity:t.granularity,dateFormat:t.dateFormat,customFormat:t.customFormat});s.ok&&(t.format=s.format,t.formatOrigin="override",e.changes.push({path:`${a}.dateFormat`,action:"moved",to:`${a}.format`}));}it(t,["dateFormat","customFormat"])&&e.changes.push({path:`${a}.dateFormat`,action:"removed"});}}function qd(e,t,a){if(!Re(t,"dateFormat")&&!Re(t,"customFormat"))return;const s=t.dateFormat==="custom"?t.customFormat:t.dateFormat;e.card.type==="detailTable"&&Nt(t.dataType)&&!t.format&&typeof s=="string"&&s.trim()?(t.format={type:"date",pattern:s},t.formatOrigin="override",e.changes.push({path:`${a}.dateFormat`,action:"moved",to:`${a}.format`})):e.card.type==="detailTable"&&Nt(t.dataType)&&t.format&&typeof s=="string"&&s.trim()&&!et(t.format,{type:"date",pattern:s})&&e.unconverted.push({path:`${a}.dateFormat`,reason:"detail_date_beside_format",detail:"A detail date pattern on a column that has a format of its own."}),it(t,["dateFormat","customFormat"])&&e.changes.push({path:`${a}.dateFormat`,action:"removed"});}function Ld(e,t,a,s){if(t.format!==void 0){const i=Ra(t.format);i?et(i,t.format)||(t.format=i,e.changes.push({path:`${s}.format`,action:"cleaned"})):(delete t.format,e.changes.push({path:`${s}.format`,action:"removed"}));}a==="groupByColumns"||a==="pivotByColumns"?pa(e,t,s):a==="detailColumns"?qd(e,t,s):it(t,["dateFormat","customFormat"])&&e.changes.push({path:`${s}.dateFormat`,action:"removed"});}function Md(e,t){for(const a of Da)pe(e.card,a).forEach((s,i)=>{var d;if(!s.format||s.formatOrigin)return;const n=(d=t.modelFormatFor)==null?void 0:d.call(t,s);s.formatOrigin=n&&et(gt(n),s.format)?"semantic":"override",e.changes.push({path:`config.${a}[${i}].formatOrigin`,action:"marked"});});}function Vd(e){var a;const t=(a=e.card.interactionConfig)==null?void 0:a.drillHierarchies;Array.isArray(t)&&t.forEach((s,i)=>{if(!ce(s))return;const n=`interactionConfig.drillHierarchies[${i}]`;ce(s.baseField)&&pa(e,s.baseField,`${n}.baseField`),Array.isArray(s.steps)&&s.steps.forEach((d,c)=>{if(ce(d)&&ce(d.field)){const u=d.field,r=`${n}.steps[${c}].field`;if(u.format!==void 0){const m=Ra(u.format);m&&!et(m,u.format)&&(u.format=m,e.changes.push({path:`${r}.format`,action:"cleaned"}));}pa(e,u,r);}});});}const Bd=["numberFormat","dateFormat","inheritMetricFormat","colorRanges"];function jd(e,t){const a=i=>i==null?void 0:i.trim().toLowerCase(),s=a(t);return[e.id,e.alias,e.name,e.qualifiedFieldName,e.label,e.role==="metric"?Pn(e):void 0].some(i=>i!==void 0&&a(i)===s);}function Os(e,t){const a=un(e,{columnId:t});if(a)return a;const s=[...pe(e,"detailColumns"),...pe(e,"metricColumns"),...pe(e,"groupByColumns")].filter(i=>jd(i,t));return s.length===1?s[0]:void 0;}function Kd(e){return e.type==="number"&&ce(e.numberFormat)&&e.inheritMetricFormat!==!0;}function Wd(e,t){var a;return Nt(t.dataType)?pe(e,"detailColumns").includes(t)?e.type==="detailTable":Un(t.granularity)||((a=t.format)==null?void 0:a.type)==="temporal_bucket"||t.semanticTemporalPresentation!=null:!1;}function Es(e,t,a,s){var d;const i=(d=e.card).preferences??(d.preferences={}),n=i.sqlColumns??(i.sqlColumns={});n[t]={...n[t],format:a},e.changes.push({path:s,action:"moved",to:`preferences.sqlColumns[${JSON.stringify(t)}].format`});}function Ud(e){const[t,...a]=e;if(!t)return;const s=Object.fromEntries(Object.entries(t).filter(([i,n])=>a.every(d=>Fi(d[i],n))));return ka.safeParse(s).success?s:void 0;}function Gd(e,t){const a=e.card,s=yn({groupByColumns:pe(a,"groupByColumns"),metricColumns:pe(a,"metricColumns"),pivotByColumns:pe(a,"pivotByColumns"),detailColumns:a.type==="detailTable"?pe(a,"detailColumns"):[]});for(const[i,n]of t){const d=n.find(u=>u.key===s.get(i)),c=d??n[0];if(Pt(e,i,c.format,c.from),!d)for(const u of n)u!==c&&!et(u.format,c.format)&&e.unconverted.push({path:u.from,reason:"ambiguous_column_setting",detail:`"${u.key}" and "${c.key}" both name ${i.id}.`});}}function Qd(e,t){var n;if(!t.length)return;const a=pe(e.card,"metricColumns"),s=a.length===1?a[0]:void 0,i=s&&!s.format?Ud(t.map(d=>d.format)):void 0;s&&i&&Pt(e,s,i,t[0].from);for(const d of t)if(!(s!=null&&s.format&&et(d.format,s.format))){if(!a.length){e.unconverted.push({path:d.from,reason:"generated_count_pivot_format",detail:`"${d.key}" is one pivot value's column on a table with no measure; it formats the row count the query adds.`});continue;}e.unconverted.push(((n=s==null?void 0:s.format)==null?void 0:n.type)===d.format.type?{path:d.from,reason:"pivot_value_format_difference",detail:`"${d.key}" is one pivot value's column; its format differs from its measure's, which every pivot value now shows.`}:{path:d.from,reason:"per_pivot_value_format",detail:`"${d.key}" is one pivot value's column; a card column holds one format for every pivot value.`});}}function Hd(e){var u;const t=(u=e.card.preferences)==null?void 0:u.tablePrefs,a=t==null?void 0:t.columnSettingsMap;if(!ce(a))return;const s=e.card,i=Ai(s),n=pe(s,"pivotByColumns").length>0,d=/* @__PURE__ */new Map(),c=[];for(const[r,m]of Object.entries(a)){if(!ce(m))continue;const b=m,$=`preferences.tablePrefs.columnSettingsMap[${JSON.stringify(r)}]`;if(Kd(b)){const g=on(b.numberFormat);if(g&&i)Es(e,r,g,`${$}.numberFormat`);else if(g&&ma(s)){const S=Os(s,r),x={key:r,format:g,from:`${$}.numberFormat`};S?d.set(S,[...(d.get(S)??[]),x]):n?c.push(x):e.unconverted.push({path:x.from,reason:"unmatched_column_setting",detail:`"${r}" names no card column.`});}else g&&s.type!=="matrixTable"&&s.type!=="kpi"&&pe(s,"metricColumns").some(x=>x.comparison!=null)&&e.unconverted.push({path:`${$}.numberFormat`,reason:"chart_comparison_column_setting",detail:`"${r}" formats this chart's comparison tooltip only.`});}if(ce(b.dateFormat)){const g=b.type==="date";if(g&&i)Es(e,r,nn(b.dateFormat),`${$}.dateFormat`);else if(g&&ma(s)){const S=Os(s,r);(!S||!Wd(s,S))&&e.unconverted.push({path:`${$}.dateFormat`,reason:"config_column_date_setting",detail:`"${r}"'s download formats its dates with this setting.`});}}for(const g of Bd)Object.prototype.hasOwnProperty.call(b,g)&&(delete b[g],e.changes.push({path:`${$}.${g}`,action:"removed"}));}Gd(e,d),Qd(e,c);}function Yd(e){return Object.keys(e).some(t=>t!=="enabled"&&t!=="colorRanges"&&e[t]!==void 0);}function Jd(e){return(e==null?void 0:e.enabled)===!1||(e==null?void 0:e.enabled)==="false";}function zd(e){const t=e.card,a=t.preferences;if(!a)return;const s=a.kpiVisualOptions,i=ce(s==null?void 0:s.formatOptions)?s.formatOptions:void 0,n=a,d=ce(n.formatNumber)?n.formatNumber:void 0,c=i?gt(rn(i)):void 0,u=d&&Yd(d)?gt(dn(d)):void 0;if(t.type==="kpi"){if(Jd(d)&&e.unconverted.push({path:"preferences.formatNumber.enabled",reason:"raw_display",detail:"Formatting is switched off on this KPI."}),Nd(t)){const r=c??u,m=s==null?void 0:s.queryComparisonPolarity;(r||m)&&(a.sqlKpiValue={...a.sqlKpiValue,...(r?{format:r}:{}),...(m?{comparisonPolarity:m}:{})},e.changes.push({path:c?"preferences.kpiVisualOptions.formatOptions":"preferences.formatNumber",action:"moved",to:"preferences.sqlKpiValue"}));}else pe(t,"metricColumns").forEach(m=>{c?Pt(e,m,c,"preferences.kpiVisualOptions.formatOptions"):u&&!m.format&&Pt(e,m,u,"preferences.formatNumber");});Xd(e,d);}else if(u){const r=pe(t,"metricColumns");Ai(t)?e.unconverted.push({path:"preferences.formatNumber",reason:"sql_card_wide_format",detail:"A card-wide number format on a SQL or Python card."}):!ma(t)&&t.type!=="matrixTable"&&r.some(m=>!m.format)&&e.unconverted.push({path:"preferences.formatNumber",reason:"chart_card_wide_format",detail:"A card-wide number format on a chart measure without a format of its own."});}if(!d&&Re(n,"formatNumber")&&(delete n.formatNumber,e.changes.push({path:"preferences.formatNumber",action:"removed"})),d){const r=d.colorRanges;Array.isArray(r)&&r.length>0?n.formatNumber={colorRanges:r}:delete n.formatNumber,e.changes.push({path:"preferences.formatNumber",action:"removed"});}s&&it(s,["formatOptions","queryComparisonPolarity"])&&(e.changes.push({path:"preferences.kpiVisualOptions.formatOptions",action:"removed"}),Object.keys(s).length===0&&delete a.kpiVisualOptions);for(const r of["numberAxisFormat","columnSettings"])it(a,[r])&&e.changes.push({path:`preferences.${r}`,action:"removed"});}function Xd(e,t){var n;const a=t==null?void 0:t.decimalPlaces,s=e.card.preferences;if(typeof a!="number"||((n=s.comparisonPresentation)==null?void 0:n.precision)!==void 0)return;const i=vn(a);i!==void 0&&(s.comparisonPresentation={...s.comparisonPresentation,precision:i},e.changes.push({path:"preferences.formatNumber.decimalPlaces",action:"moved",to:"preferences.comparisonPresentation.precision"}));}const Zd=/* @__PURE__ */new Set(["number","currency","percent","scientific","date","duration"]);function el(e){const t=e.card.preferences;if(t)for(const a of Ed){const s=t[a];if(!ce(s))continue;const i=`preferences.${a}`,n=ce(s.formatOptions)?s.formatOptions:void 0,d=a==="dataLabelsConfig"&&typeof s.format=="string"?s.format:void 0,c=s.formatMode==="override"||s.formatMode==="inherit"?s.formatMode:s.mode==="override"||s.mode==="inherit"?s.mode:void 0,u=c??(d==="none"?"raw":d&&d!=="auto"||n?"override":"inherit");if(u==="raw"||c===void 0&&d==="none")e.unconverted.push({path:`${i}.format`,reason:"raw_display",detail:"Data labels show raw values."});else if(u==="override"){const r=n&&n.type?n:d&&Zd.has(d)?{...n,type:d}:n,m=r?gt(ln(r,{preserveOmittedProperties:!0})):void 0;m&&(s.valueFormat=m,e.changes.push({path:`${i}.formatOptions`,action:"moved",to:`${i}.valueFormat`}));}it(s,["formatMode","mode","formatOptions",...(a==="dataLabelsConfig"?["format"]:[])])&&e.changes.push({path:`${i}.formatMode`,action:"removed"});}}function tl(e){var s;const t=(s=e.card.config)==null?void 0:s.matrix,a=ce(t)&&ce(t.presentation)?t.presentation:void 0;if(a)for(const i of["measureFormats","levelFormats"]){const n=a[i];if(ce(n))for(const[d,c]of Object.entries(n)){const u=Ra(c);u&&!et(u,c)&&(n[d]=u,e.changes.push({path:`config.matrix.presentation.${i}[${JSON.stringify(d)}]`,action:"cleaned"}));}}}function al(e,t={}){const a={card:structuredClone(e),changes:[],unconverted:[]};for(const s of Da)pe(a.card,s).forEach((i,n)=>{ce(i)&&Ld(a,i,s,`config.${s}[${n}]`);});return Vd(a),Hd(a),zd(a),el(a),tl(a),Md(a,t),a.changes.length===0&&a.unconverted.length===0?{card:e,changes:[],unconverted:[]}:a;}const sl="__semaphor_unassigned_trigger__",il="__NULL__";function ol(e){var t,a;return!!((t=e.sql)!=null&&t.trim()||(a=e.python)!=null&&a.trim());}function nl(e){const t=e.config;return t?e.type==="detailTable"?t.detailColumns??[]:[...(t.detailColumns??[]),...(t.metricColumns??[]),...(t.groupByColumns??[])]:[];}function Ns(e){return[e.id,e.alias,e.name,e.qualifiedFieldName,e.label];}function rl(e,t){var r,m;const a=((r=e.config)==null?void 0:r.metricColumns)??[],s=((m=e.config)==null?void 0:m.pivotByColumns)??[];if(a.length!==1||s.length!==1)return{reason:"pivot_key_form"};const i=a[0],n=s[0],d=i.aliasTemplate??"",c=d.includes(`{{${n.name}}}`)||d.includes(`{{${n.entityName}.${n.name}}}`),u=!!(i.valueAliases&&Object.keys(i.valueAliases).length);return c||u||/["'`\t\n\r]/.test(t)||t.startsWith("col_")?{reason:"pivot_key_form"}:{ref:{kind:"pivot",metricId:i.id,members:[{fieldId:n.id,value:t===il?null:t}]}};}function dl(e,t){var d,c;if(t===sl)return{reason:"unassigned_trigger"};if(ol(e))return{ref:{kind:"result",key:t}};const a=nl(e),s=a.filter(u=>Ns(u).includes(t)),i=s.length?s:a.filter(u=>Ns(u).some(r=>(r==null?void 0:r.trim().toLowerCase())===t.trim().toLowerCase())),n=[...new Set(i.map(u=>u.id))];return n.length===1?{ref:{kind:"field",fieldId:n[0]}}:n.length>1?{reason:"ambiguous_column"}:(c=(d=e.config)==null?void 0:d.pivotByColumns)!=null&&c.length?rl(e,t):{reason:"no_matching_column"};}function Ps(e,t,a,s,i){const n=(Y,D,E)=>{s.push({ruleId:e.id,name:e.name,enabled:e.enabled!==!1,path:`${a}.${Y}`,reference:D,reason:E});},d=e.condition.columnId??"",c=t(d);if(!("ref"in c))return n("condition.columnId",d,c.reason);const u=e.target.level,r=u==="row"?e.target.applyToColumnIds:e.target.columnIds;if(u==="cell"&&!(r!=null&&r.length)&&e.enabled!==!1)return n("target.columnIds","","every_column");const m=[];for(const[Y,D]of(r??[]).entries()){const E=t(D);if(!("ref"in E))return n(`target.${u==="row"?"applyToColumnIds":"columnIds"}[${Y}]`,D,E.reason);m.push(E.ref);}const{columnIds:b,applyToColumnIds:$,conditionColumnId:g,matrix:S,rowRoles:x,depth:A,includeTotals:I,includeSubtotals:F,...y}=e.target,{columnId:M,...R}=e.condition,O={...y,...(m.length?{columns:m}:{}),...(i?{...(S!==void 0?{matrix:S}:{}),...(x!==void 0?{rowRoles:x}:{}),...(A!==void 0?{depth:A}:{}),...(I!==void 0?{includeTotals:I}:{}),...(F!==void 0?{includeSubtotals:F}:{})}:{})};return{...e,condition:{...R,column:c.ref},target:O};}function ll(e,t){var i;const a=(i=js(e))==null?void 0:i.value;if(!a)return[];const s=n=>n===null?0:typeof n=="number"||typeof n=="string"||typeof n=="boolean"?Number(n):NaN;return t.flatMap((n,d)=>{if(!n||typeof n!="object")return[];const{start:c,end:u,color:r}=n,m=s(c),b=s(u);if(Number.isNaN(m)||Number.isNaN(b)||m>b||m===1/0||b===-1/0)return[];const $=m===-1/0?void 0:m,g=b===1/0?void 0:b,S=$!==void 0&&g!==void 0?{kind:"between",column:a,min:$,max:g,inclusive:!0}:$!==void 0?{kind:"comparison",column:a,operator:"gte",value:$}:g!==void 0?{kind:"comparison",column:a,operator:"lte",value:g}:{kind:"blank",column:a,isBlank:!1},x=typeof r=="string"?r:"";return[{id:`kpi-color-range-${d+1}`,condition:S,target:{level:"cell"},style:{textColor:x}}];}).reverse();}function cl(e){var m,b,$,g,S,x,A;const t=structuredClone(e),a=[],s=[],i=[],n=I=>{a.some(F=>F.from.startsWith(I))||a.push({ruleId:"",action:"removed",from:I});},d=(m=t.preferences)==null?void 0:m.tablePrefs;if(d&&Re(d,"conditionalFormatting")){const I=d.conditionalFormatting,F="preferences.tablePrefs.conditionalFormatting",y=t.type==="table"||t.type==="detailTable";((I==null?void 0:I.rules)??[]).forEach((M,R)=>{var Y;if(!y||((Y=M.target)==null?void 0:Y.matrix)!==void 0){a.push({ruleId:M.id,action:"removed",from:`${F}.rules[${R}]`});return;}const O=Ps(M,D=>dl(t,D),`${F}.rules[${R}]`,s,!1);O&&(i.push(O),a.push({ruleId:M.id,action:"moved",from:`${F}.rules[${R}]`}));}),delete d.conditionalFormatting,s.some(M=>M.path.startsWith(F))||n(F);}const c=($=(b=t.config)==null?void 0:b.matrix)==null?void 0:$.presentation;if(c&&Re(c,"conditionalFormatting")){const I=c.conditionalFormatting,F="config.matrix.presentation.conditionalFormatting",y=new Set((S=(g=t.config)==null?void 0:g.matrix)==null?void 0:S.spec.measures.map(M=>M.id));((I==null?void 0:I.rules)??[]).forEach((M,R)=>{const O=Ps(M,Y=>y.has(Y)?{ref:{kind:"matrixMeasure",measureId:Y}}:{reason:"no_matching_column"},`${F}.rules[${R}]`,s,!0);O&&(i.push(O),a.push({ruleId:M.id,action:"moved",from:`${F}.rules[${R}]`}));}),delete c.conditionalFormatting,s.some(M=>M.path.startsWith(F))||n(F);}const u=t.preferences,r=u==null?void 0:u.formatNumber;if(r&&Re(r,"colorRanges")){const I=Array.isArray(r.colorRanges)?r.colorRanges:[];if(t.type==="kpi"){const F=ll(t,I);i.push(...F),F.forEach(y=>a.push({ruleId:y.id,action:"moved",from:"preferences.formatNumber.colorRanges"}));}delete r.colorRanges,Object.keys(r).length===0&&delete u.formatNumber,a.some(F=>F.from==="preferences.formatNumber.colorRanges")||a.push({ruleId:"",action:"removed",from:"preferences.formatNumber.colorRanges"});}if(!a.length&&!s.length)return{card:e,changes:[],unresolved:[]};if(i.length){const I=((A=(x=t.preferences)==null?void 0:x.conditionalFormatting)==null?void 0:A.rules)??[],F=new Set(I.map(y=>y.id));t.preferences={...t.preferences,conditionalFormatting:{version:1,rules:[...I,...i.filter(y=>!F.has(y.id))]}};}return{card:t,changes:a,unresolved:s};}function Ll(e,t={}){const{only:a,...s}=t,i=a==="rules"?void 0:al(e,s),n=a==="formats"?void 0:cl((i==null?void 0:i.card)??e);return{card:(n==null?void 0:n.card)??(i==null?void 0:i.card)??e,formats:i,rules:n};}function Ml(e){return e.kind==="metric"?e.resultId:e.measureId;}function ul(e){if(e.op==="dashboard.update"||e.op==="dashboard.style"||e.op==="sheet.update")return!0;if(e.op!=="card.update")return!1;switch(e.update.kind){case"relabel":return!0;case"settings":return e.update.settings.totals===void 0&&e.update.settings.trend!==!0&&e.update.settings.trendGrain===void 0;default:return!1;}}function Vl(e){return e.impact.length||e.detaches?"needed":e.operations.length>0&&e.operations.every(ul)?"not_needed":"needed";}export{Kl as AGGREGATES,Wl as AUTOMATIC_FALLBACK_GRAIN,Ul as AUTOMATIC_TEMPORAL_BUCKET_FORMAT,Vo as AUTOMATIC_TIME_GRAIN,Gl as CALCULATED_FIELDS_GROUP_ID,Ql as CALCULATED_FIELDS_GROUP_NAME,Hl as CALCULATION_CHANGE_OPS,Yl as CARD_CONFIG_KEY_CLASSES,Jl as CARD_FIELD_SHELVES,zl as CARD_FILTER_FOLDER_ROLES,Xl as CARD_KEY_CLASSES,Uo as CARD_QUERY_CONFIG_KEYS,Sy as CARD_QUERY_REQUEST_DESCRIPTIVE_FIELDS,xy as CARD_QUERY_REQUEST_EXECUTED_FIELDS,Zl as CARD_SURFACES,ec as CARD_TYPES,lt as CARD_TYPE_RULES,$t as CHART_COLORS_BOUNDS,tc as CHIP_VALUE_COLUMN,ac as COLUMN_KEY_CLASSES,sc as COLUMN_PRESENTATION_KEYS,ic as COMPARISON_POLARITIES,tb as COMPARISON_SIGN_WORDS,oc as CONTROL_BINDING_MAPPING_MISSING_ERROR_CODE,nc as CONTROL_BINDING_TARGET_INVALID_ERROR_CODE,rc as CONTROL_BINDING_VALUE_INVALID_ERROR_CODE,dc as CONTROL_CONTEXT_UNSUPPORTED_ERROR_CODE,lc as CONTROL_DEFINITION_DUPLICATE_ERROR_CODE,cc as CONTROL_DEFINITION_INVALID_ERROR_CODE,uc as CONTROL_PLACEHOLDER_QUOTED_ERROR_CODE,fc as CONTROL_REFERENCE_MISSING_ERROR_CODE,hc as CONTROL_VALUE_INVALID_ERROR_CODE,mc as CONTROL_VALUE_MISSING_ERROR_CODE,pc as CORNER_STEPS,ky as CardQueryRequestError,gc as ControlResolutionError,bc as DASHBOARD_CHANGE_OPS,yc as DASHBOARD_DEFAULT_OPTION_DEPENDENCIES,ab as DASHBOARD_FILTER_OPERATIONS,vc as DASHBOARD_INPUT_RUNTIME_SCOPE_KINDS,wn as DASHBOARD_STYLE_NUMBER_BOUNDS,$c as DEFAULT_DETAIL_DATE_STYLE,wc as DETAIL_BACKUP_SHELVES,Ic as DETAIL_DATE_STYLES,sb as DOCUMENT_KPI_SECTION_MAX_CARDS,ib as DOCUMENT_KPI_SECTION_MAX_TILES,_c as DOMAIN_EDIT_CHANGE_OPS,Cc as DYNAMIC_TEXT_MESSAGE,Sc as DashboardFilterMappingContractError,xc as ExecutionControlContractError,kc as FILTER_OPERATORS,os as FORMAT_WORDS,Tc as FilterModelError,Fc as KPI_MEASURES_SHOWN,Jv as KPI_TREND_GRAINS,zv as KPI_TREND_PERIODS,Ac as LEGACY_TABLE_CARD_TYPES,Jb as LEGACY_TABLE_ROUTING_ID_NAMESPACE,Dc as MATCH_WEEKDAYS_ONLY_BY_YEARS,fs as MAX_CREATE_CHANGES,Rc as MAX_DATE_GRAIN_POINTS,Oc as MAX_NEXT_STEP_CHARS,zo as MAX_PROPOSED_CHANGES,Ec as MAX_QUERY_LIMIT,Nc as MAX_TEXT_WORDS,Pc as MEASURE_CALCULATION_SUMMARIES,hv as NEW_CARD_TYPE,qc as NON_ADDITIVE_SUM_OF_ROWS_HINT,Lc as NUMBER_CONDITION_GROUPS,Mc as NUMBER_CONDITION_SPECS,Vc as PUBLIC_TRANSFORM_KIND,Bc as QUERY_ASPECTS,jc as QUERY_CONFIG_KEY_ASPECTS,mv as RELATIONSHIP_ROUTE_CHANGED_MESSAGE,Kc as RESERVED_VARIABLE_NAMES,Wc as SEE_RECORDS_CARD_TYPES,Uc as SEE_RECORDS_LIMITS,Gc as SEE_RECORDS_MAX_PAGE,pv as SEE_RECORDS_MESSAGES,Qc as SEMAPHOR_CARTESIAN_CHART_TYPES,Hc as SETTINGS_BY_KIND,e$ as SHELF_FIELD_KEYS,Yc as SPACING_STEPS,Jc as TABLE_SHEET_CARD_TYPES,zc as TIME_GRAINS,Xc as TOOLBAR_FILTER_REACH_FIELDS,Zc as TO_DATE_IS_AUTOMATIC,Ys as UNREADABLE_CARD_TAKES,ob as VARIABLE_CARD_TYPE,nb as VARIABLE_COMPARISON_PARTS,eu as VARIABLE_GETS,rb as VARIABLE_LIST_CAP,db as VARIABLE_LIST_SHOWN,tu as VARIABLE_NAME_PATTERN,lb as VARIABLE_VALUE_PART,au as WINDOW_ERROR_CODES,su as WINDOW_WARNING_CODES,iu as acceptedColumnRefKinds,ou as acceptsGrainThatRan,nu as addCalculatedField,Ty as addCardJoin,ru as adoptCalculatedFields,du as analyticsFilterSchema,lu as appliedBindingControlValue,cu as applyCalculatedFieldOperation,zb as applyCardReferenceRemapping,uu as applyCardSettings,mt as applyDashboardOperations,fu as applyFilterApplicability,gv as applyFilterSettingsChange,Xb as applyGroupByOverride,hu as applyLinkedClickToFilterOverrides,mu as applyMeasureCalculations,pu as applyOptionDependencyOverride,gu as applyVariableChange,bu as asDateDefaultPointCondition,yu as automaticDateGrain,Bo as automaticGrainSupport,vu as blockClause,$u as blockSentence,n$ as bookmarkImpactSentence,wu as buildCalculatedFieldDefinition,bv as buildCardExportFormatOptions,Zb as buildCardExportQueryContext,yv as buildCardExportRequest,vv as buildCardExportRequestFromOptions,Iu as buildCardFilterDefinition,$v as buildCardRecordsCsv,Fy as buildColumnCatalog,_u as buildControlDefinitionIndex,Ro as buildDashboardCardSourceIndex,Ay as buildEntityColumnGroup,wv as buildFilterInputFromDefinition,ii as buildFilterInputFromField,Cu as buildLinkedClickToFilterOverrides,Su as buildMetricInputFieldsForExpression,xu as buildProposeChangeInputSchema,Iv as buildRecordsCsv,ku as buildSavedEditorCard,_v as buildTableExportFormatOptions,Cv as buildTableFileCsv,Tu as calculatedColumnMatchesField,Fu as calculatedFieldDomainId,Ao as calculatedFieldInUseMessage,Au as calculatedFieldListOperations,en as calculatedFieldSemanticSource,Qs as calculatedFieldUsage,Du as calculationAddSchema,Ru as calculationChangeSchemas,Ou as calculationRemoveSchema,Eu as calculationUpdateSchema,Nu as calculationsRemovedWords,Wt as canShowAsRange,No as cardBaseEntity,Pu as cardBaseSource,Sv as cardColumnRefForKey,qu as cardColumnRefSchema,an as cardConditionalFormattingSchema,Lu as cardConfigAsRan,Mu as cardFieldFolders,Vu as cardFieldsInPlaces,Bu as cardQueryPatchSchema,ju as cardReachesDatasetThroughRelationships,Ku as cardReadsOnlyOwnJoins,Wu as cardSelectedEntities,Yi as cardSettingsKind,Qi as cardTypeSentenceName,Uu as carryColumnSettings,Go as changeCardType,Gu as changeMatrixEditor,Qu as checkCalculatedColumnDefinitions,Hu as checkCalculatedFieldList,sn as checkConditionalRuleColumns,$a as checkDataVariable,Yu as checkDetailDateFormat,ql as checkPresentationStores,Ju as checkSheetShapes,zu as chipOverVariable,Xu as classifyCalculatedColumn,Zu as clearedCardShelves,ef as clickToFilterSettingsSchema,tf as collectJoinPlanIdentifiers,ei as collectVariableReferences,af as columnConditionalRules,ga as columnDataset,Rt as columnFieldKey,Xs as columnKeys,sf as columnRefIssue,is as columnRefKey,of as columnSettingsInputSchema,nf as comparesMetricPair,cb as comparisonPartPresentation,Io as comparisonShiftSchema,ey as composeCardReferenceRemapping,rf as conditionalRuleSchema,Vl as confirmClassFor,df as contextChangeSchema,lf as controlBindingExecutionSchema,cf as controlDefinitionExecutionSchema,ko as controlRefusal,Rl as convertLegacyStyle,uf as createCalculatedDimension,ff as createCalculatedField,hf as createDashboardFilterBindingId,yy as createMatrixAuthoringDraft,vy as createMatrixConfig,xn as createNewCard,mf as createTargetSchema,Sn as createTextCard,pf as customDetailDateFormat,gf as customGroupedDateFormat,bf as dashboardCardFilterSourceInventoryContains,wo as dashboardChangeSchema,yf as dashboardCopiesOn,Do as dashboardFieldFromCompiled,vf as dashboardFilterTargetMatchesLogicalValue,ub as dashboardFilterValueTypeForDataType,pn as dashboardInputScopeIncludesDocumentSheets,rr as dashboardStyleAsEdit,$f as dashboardStyleChangeSchema,ai as dashboardStyleLayers,wf as dateDefaultPointCondition,If as decideClickToFilterCardLevel,_f as decideClickToFilterField,Cf as defaultClickToFilterSettings,Yn as defaultVariableGet,t$ as defaultVariableName,r$ as describeBookmarkImpact,Sf as describeDashboardFilterCardReach,Xe as describeDashboardFilterCardReachDetail,xv as describeDateWindow,kv as describeFilterReachEntry,Tv as describeKpiDateSection,Fv as describeKpiTileDate,Xv as describeKpiTrendRow,xf as describeMeasureCalculations,kf as describeNumberCondition,Tf as describeNumberConditionDefault,xo as describeQueryChange,Av as describeRelationshipRoute,Tn as describeRelationshipSkip,Ff as describeTableColumnTotal,Af as detailDateDisplayFormat,Df as detailDateFormatProblem,Rf as detailDateTwelveHourAvailable,fb as documentInputTextUsage,hb as doesDashboardInputApplyToTarget,mb as doesDashboardInputReachFilterTarget,pb as doesDashboardInputSurviveCarriedContext,Of as doesToolbarFilterReachTab,Dy as domainCalculatedFields,Ef as domainEditChangeSchema,Nf as domainEditChangeSchemas,a$ as draftBlocker,Ry as draftFromJoin,Jn as draftFromVariable,Pf as drawsDetailDatesInBrowser,qf as dropMatrixEditorField,l$ as editBrandStyle,Cn as editDashboardStyle,Dv as encodeTableExportCsv,Lf as estimateDateGrainPoints,Mf as evaluateConditionalRules,Vf as explicitComparisonSchema,Bf as fieldAsRan,jf as fieldDatasets,Kf as fieldFolderTree,mo as fieldIdentityKey,Wf as fieldRef,Uf as fieldRefSchema,Gf as fillFrameSemanticCardDomains,Qf as fillSemanticCardDomain,Hf as fillSemanticCardDomains,Yf as filterApplicabilityContextForCard,Oy as filterFieldCalculatedCandidates,Ey as filterFieldCatalog,Ny as filterFieldFolders,Py as filterFieldReachCard,qy as filterFieldReachCards,Ly as filterFieldTables,My as filterFieldTrees,Vy as filterFolderDataSource,By as filterFolderKey,jy as filterFolderPlacement,Ky as filterReachCount,hr as filterReachInput,Wy as filterReachLine,mr as filterReachOnCard,Rv as filterReachPreviewAnswers,Jf as filterValueReachForCard,zf as filterValueSemanticDataset,Uy as filterableCards,Xf as findBorrowedSelectionBinding,qt as findCatalogField,Zf as findDashboardCardExecutableSource,eh as findDashboardCardPinnedCatalogSource,_a as findDashboardFilterTarget,th as findDashboardSqlPinnedCatalogSource,ki as findRetiredCardPresentationFields,Pl as findRetiredPresentationFields,ho as findSortedColumn,Gy as flattenEntityColumns,ah as foldPrototypeDocumentInputs,sh as folderParentHintFromJoin,ih as folderParentHintFromStep,oh as formatFilterModelIssues,nh as formatResolvedPrimaryDateFieldIssues,rh as formatSkippedFilterWarnings,dh as fromEditableRules,lh as getCalculatedFieldAggregateOverrides,ch as getCalculatedFieldComparableKey,Tt as getCalculatedFieldIdentityKey,uh as getCalculatedFieldNamespace,fh as getCalculatedFieldParameters,hh as getCalculatedFieldShelfOverrides,mh as getCardDefinition,Ov as getClickContextFromTable,ph as getColumnCatalogFieldId,gh as getDashboardFilterSubscriptionHint,bh as getDashboardGlobalDateFilter,gb as getDocumentKpiSectionShapeIssues,bb as getDocumentSectionCards,yh as getDomainCalculatedSelectionOverrides,vh as getFieldAggregationOptions,$h as getMatrixBindingTargets,$y as getMatrixLevelLabel,wy as getMatrixMeasureLabel,wh as getStableDomainCalculatedFieldId,Ih as getTemporalBucketAuthoringOptions,_h as getTemporalBucketAuthoringSelection,Ch as grainChoicePatch,Sh as grainControlApplies,xh as groupedDateDisplayFormat,so as groupedDateDisplayPatterns,kh as handleSchema,Th as hasDashboardFilterSubscription,Ev as hasSeeRecordsMeasureFilter,Re as hasStoredKey,Fh as hasTextCardRichWords,Ah as hasToolbarFilterReachField,ty as hostFilterValueFor,ay as hostFilterValuesToSlots,Dh as indexOfToken,Rh as indexTypedTokens,Oh as inferSemanticDomainIdFromSelectedEntities,Eh as initialNumberFilterSearchMode,Nh as inputScopeKindOf,Ph as inspectMatrixCardConfig,sy as isAdHocFilterValueOnTab,ys as isAggregateGet,qh as isAllowedDashboardInputScopeCombination,Lh as isCalculatedColumn,Fo as isCalculatedFieldInUse,Mh as isCardType,Vh as isCompleteOwnedFilter,yb as isDashboardFilterOperationCompatible,Zs as isDashboardInputOnTab,vb as isDashboardInputOwnedBySheet,$b as isDashboardInputScopeEmpty,wb as isDashboardTargetIdTaken,Bh as isDatabaseEntityReference,Ls as isFilterCardReached,wa as isGridSheet,jh as isGroupedDate,ao as isGroupedTimeGrain,Kh as isLegacyTableCard,Li as isNumberConditionOperation,Wh as isPresentationCurrencyBinding,Uh as isSeeRecordsCardType,Gh as isSemanticAutoJoinCard,Qh as isSemaphorCartesianChartType,fn as isSqlKpi,Hh as isStructuralControlBinding,Ut as isTableSheet,Co as isTableSheetCardType,Yh as isTextCardRichContent,Jh as isValidControlOptionPresentation,Ib as isVariableComparisonPart,zh as isWhenRun,Xh as joinEntityName,Zh as joinEqualityPairs,Qy as joinFromDraft,Hy as joinMatches,Yy as joinTableReference,Jy as joinTargetRefusal,em as kpiSegmentMetricId,tm as kpiShowsTrend,Gi as kpiTrendBy,Nv as kpiTrendByHint,fo as labelAt,am as layoutArrangeSchema,iy as legacyTableRoutingIds,oy as legacyTableRoutingTarget,sm as linkedClickToFilterOverridesSchema,ny as listAdHocFilterValuesOnTab,_e as listDashboardCardLocations,im as listDashboardFilterDefinitions,om as listDashboardFilterInputsOnTab,Ia as listDashboardFilterTargets,_b as listDashboardInputReachKeys,hn as listDashboardInputScopeExceptedCardIds,mn as listDashboardInputScopeExceptedSheetIds,nm as listDashboardInputsTolerantly,Ca as listDashboardTabTargets,Cb as listDataVariablePlaces,ry as listFilterInputValueTargets,Sb as listFilterTargetScopeTargets,xb as listReachedVariableTargets,kb as listReferencedDataVariableIds,rm as listStoredFilterDefinitions,Tb as listVariableScopeTargets,dm as mapCardFieldPlaces,Fb as mapDashboardCards,Ab as mapDocumentSectionCards,lm as mapFormulaTokens,cm as mapRuleColumns,um as matchColumns,dy as matrixCatalogSources,Yo as matrixColumnKeys,fm as matrixColumnsSchema,hm as matrixDefinitionFieldRefs,mm as matrixDefinitionFields,pm as matrixDefinitionSources,gm as matrixEditorCatalogFromFields,ly as matrixExecutionSources,bm as measureCalculationOptions,ym as measureComparisonSchema,vm as measureKeepsBareInputs,$m as measureRefSchema,wm as measureStageOnEdit,Im as measureTransformSchema,Iy as mergeMatrixSorts,Lo as metricCardQuerySchema,Ho as moveMatrixLevel,s$ as newVariableDraft,i$ as newVariableId,_m as normalizeCalculatedFieldId,Cm as normalizeClickToFilterSettings,Sm as normalizeDashboardInputs,xm as normalizeLegacyLinkedTargetOverrides,km as numberConditionProblem,Tm as numberConditionSpec,uo as numberConditionSpecForAgent,Fm as occurrenceKeys,Et as outlineCalendar,Nl as outlineDashboard,je as outlineFilter,Ta as outlineFilters,yr as outlinePinnedFilters,Gt as ownsItsAggregate,zy as parseCardQueryRequest,Xy as parseCardQueryRequestContext,Zy as parseCardQueryRequestExtras,Am as parseColumnRefKey,ev as parseDashboardStyle,Dm as parseExecutionControlBindingsShallow,Rm as parseExecutionControlContext,Om as parseExecutionControlContract,jo as placeDashboardFieldCopies,Em as placedFieldLabel,ls as planCardLabels,ds as planCardRequery,Pv as pluralDatasetLabel,cy as prepareLoadedDashboard,Nm as previewTemporalBucketAuthoringFormat,Db as projectDataVariableToCard,Pm as pruneCardFields,qm as pruneUnrelatedCalculatedFilters,To as queryForm,Lm as queryMeasureSchema,Mm as reachedDatasetEntity,Js as readAgentNumberConditionDefault,Vm as readBraceSpans,Hs as readCalculatedFieldDefinition,Bm as readCardConditionalRules,Ve as readCardQuery,ba as readCardSettings,Le as readCardSource,ze as readCardTypeProperties,tv as readComparisonDates,Ce as readDashboardFilterModel,av as readDefaultComparisonDates,jm as readDetailDateChoice,Km as readExactDomainCalculatedFieldReference,sv as readFilterFieldReachResponse,qv as readFilterReachResponse,uy as readFilterValueList,Wm as readFormulaTokens,Um as readGroupedDateChoice,Lv as readKpiDateContext,Gm as readKpiFigure,Qm as readKpiNumber,Hm as readMatrixCardConfig,Ym as readMeasureCalculations,Jm as readNumberConditionDefault,na as readNumberFilterShowAs,zm as readSqlFilterUse,Xm as readStoredComparison,Zm as readStoredTransform,iv as readTableViewerSwitch,zs as readTextCardWords,Ot as readTextWords,ep as readTransform,Rb as readVariableAnswer,vi as readVariableEditability,ua as readVariableSource,Zo as readablePresentation,tp as rebindDashboardOptionDependencyInputId,rs as rebuildsRole,ap as reconcileMatrixSpecStructure,sp as reconcileTemporalBucketAuthoringFormat,qo as recordsCardQuerySchema,vo as refDataset,De as refKey,da as refName,ip as refusalOfCalculatedFieldOperations,op as registeredCalculationChangeSchemas,np as registeredDomainEditChangeSchemas,rp as relationshipAddSchema,dp as relationshipRouteTarget,lp as remapClickToFilterReferences,cp as remapLinkedClickToFilterOverrides,up as removeCalculatedField,ov as removeCardJoin,Ni as requireNormalizedDashboardInputs,fp as resolveBindingControlValue,Jo as resolveCalculatedFieldName,Ob as resolveCanonicalDetailResultRawKey,Eb as resolveCanonicalResultOutputKey,yn as resolveCanonicalResultOutputKeys,Nb as resolveCanonicalResultRawKey,Mv as resolveCardColumnRef,hp as resolveCardFieldCopies,Lr as resolveCardSettings,Vv as resolveConditionalRules,Ol as resolveDashboardChanges,El as resolveDashboardCreate,mp as resolveDashboardEntitySource,pp as resolveDashboardFieldCopies,gp as resolveDashboardFieldCopiesIn,bp as resolveDashboardFilterAutomaticTarget,yp as resolveDashboardFilterInheritedTarget,vp as resolveDashboardOptionDependencies,$p as resolveDashboardOptionPopulation,wp as resolveDashboardSqlFilterTarget,An as resolveDashboardStyle,Bv as resolveDashboardTemporalPresentation,Ip as resolveDatasetName,_p as resolveDetailTableRawTemporalPresentation,Pb as resolveDistinctDetailRawKeys,Cp as resolveFieldSelectedSource,Sp as resolveGroupByFieldTarget,xp as resolveKpiLayout,js as resolveKpiShape,kp as resolveKpiValueStyle,fy as resolveMatrixControlBindings,_y as resolveMatrixDefinition,ns as resolveMeasureCalculations,Tp as resolveMeasureTransform,Fp as resolveMetricFieldTarget,Ap as resolveScalarMappedValue,Dp as resolveTableColumnTotal,Rp as resolveTemporalBucketAuthoringFormat,Op as resolveTemporalResultOwner,cs as resolveTextCardWords,Ep as resolveValueStyle,Np as respondsToSelectionsSchema,Pp as retainConditionalRules,qp as retainedMatrixPath,qb as rewriteDashboardInputScopeIds,Lp as rewriteFieldMeta,hy as routeLegacyTableCard,my as routeLegacyTableCards,py as routeLegacyTableFrame,Mp as sameBaseEntity,Ft as sameColumnKey,Vp as sameSource,Bp as sameWords,jp as sanitizeTextCardUrl,jv as seeRecordsAvailability,Kv as seeRecordsCardAvailability,Ml as seeRecordsMeasureId,Wv as seeRecordsMeasureKind,Uv as seeRecordsReasonHidesOffer,Kp as seeRecordsRequestSchema,Gv as seeRecordsRowField,Wp as selectDashboardOptionDependencyInputIds,Up as selectionFieldFromExplorerField,Qv as selectionTupleFromClickContext,Gp as semanticDomainIdsOfSelectedEntities,nv as setMeasureCalculations,Qp as settableCardType,Hp as sharedCardPreferences,Yp as sharedTableDialect,Jp as sheetChangeSchemas,Xo as sheetKindOf,zp as simulateCalculatedFieldOperations,Po as sqlCardQuerySchema,Xp as sqlKpiResultKeys,Zp as stageChangeRefusal,rv as startCardOver,eg as statedCardBaseEntity,ht as statedLabelsOf,Vi as storedCardTypeFor,tg as storedRunPresentation,Lb as storedTextRefs,ag as stripInstanceTargetsForLibrarySave,sg as structuralControlOverride,dv as suggestJoinCondition,ui as summarizeFilter,ig as supportsCanonicalDashboardTemporalResult,og as supportsMetricTransform,ng as switchCardBase,rg as tabChangeSchemas,dg as tableColumnTotalLabel,lg as tableSheetCard,lv as tableViewerSwitches,cg as textCardExcerpt,ug as textCardWordingClauses,ra as textCatalogAt,Mi as toAgentNumberConditionDefault,kt as toChartType,fg as toEditableRules,hg as toFiniteKpiNumber,mg as toIndexedTokens,pg as toNamedTokens,xt as toPublicCardType,$o as toStoredComparison,gg as toolbarFilterInputFields,bg as toolbarFilterScope,yg as transformComparisonDocument,vg as transformGroupings,$g as transformOrderSchema,wg as updateCalculatedField,cv as updateCardJoin,Qo as updateMatrixConfig,al as upgradeCardFormats,Ll as upgradeCardPresentation,cl as upgradeConditionalFormatting,gy as upgradeToStoredDashboard,Ig as validateAndResolveWindowTransforms,_g as validateControlValue,Mb as validateDashboardFilterValues,Cg as validateNumberConditionDefault,Sg as validateResolvedPrimaryDateFieldShape,Vb as variableCardKeepsComparison,Bb as variableComparison,At as variableFromDraft,Hn as variableGetOptions,jb as variablePartCell,Kb as variablePartType,bn as variableParts,Wb as variableQueryResponseOf,Hv as variableSourceWords,zn as variableTakesComparison,Fn as variableWords,xg as withCardConditionalRules,kg as withCardConfigSqlDatePatterns,Ub as withCardExcludedFromScope,Gb as withCardIncludedInScope,Tg as withColumnConditionalRules,Fg as withDashboardOptionDependencyOverride,Ag as withDefinitionFormula,Dg as withDetailSqlDatePattern,Qb as withDistinctDetailColumnAliases,Hb as withDraftCard,Rg as withFolderParents,Og as withFormatOverride,Eg as withGrainChoice,Ng as withReadDatasetsSelected,Pg as withSqlDatePattern,qg as withStartingGrain,Lg as withStoredResultKey,gn as withUnstatedScopeParts,Mg as withoutRemovedFieldCopies,Vg as withoutSqlDatePattern,Bg as withoutToolbarFilterReachFields,jg as wordingBlocks,Kg as wordingClauses,Wg as writeColumnFormat,Ug as writeColumnPolarity,Gg as writeComparisonDisplay,Qg as writeComparisonPresentation,Dn as writeCustomVisual,St as writeDateFilterDefault,Hg as writeDateSelectionMode,Yg as writeInheritComparison,Jg as writeInputAggregates,Eo as writeNumberConditionDefault,Oo as writeNumberFilterShowAs,zg as writeSeeRecords,Xg as writeTableColumnFilters,Zg as writeTableSearch,uv as writeTableViewerSwitch,yo as writeTextWords};
1
+ import{r as Ni,bV as Ie,bW as Ms,bQ as Pi,bX as qi,bY as Li,bZ as Xe,b_ as Vs,b$ as Mi,c0 as Bs,c1 as Vi,c2 as Pe,c3 as ca,c4 as Bi,c5 as js,c6 as ji,c7 as ns,c8 as Vt,c9 as va,ca as ae,cb as te,cc as ze,cd as Ki,ce as Wi,cf as $a,cg as Ui,ch as Gi,ci as Qi,ai as Hi,cj as Yi,ck as Ji,cl as zi,cm as Ks,bJ as Xi,cn as Zi,co as eo,cp as to,cq as ao,cr as so,cs as io,ct as oo,cu as no,cv as Qt,cw as ro,u as Ws,cx as lo,cy as co,cz as uo,cA as rs,cB as fo,cC as ho,a5 as wa,cD as Ne,cE as qe,cF as Le,cG as Re,cH as mo,b6 as Us,cI as Ia,cJ as Nt,cK as Tt,cL as mt,cM as po,bb as Gs,cN as go,cO as bo,cP as yo,cQ as ua,cR as Pt,cS as vo,cT as $o,cU as Qs,cV as _a,cW as it,cX as wo,cY as Io,cZ as _o,bU as fe,c_ as Hs,c$ as Co,d0 as So,d1 as Ht,al as Yt,d2 as Ft,d3 as At,d4 as xo,d5 as ko,d6 as Ys,bR as ds,d7 as To,d8 as ls,d9 as Fo,da as cs,db as us,dc as fs,dd as ct,de as Ao,df as Rt,dg as Js,dh as Ro,di as Do,dj as zs,dk as Oo,dl as Xs,dm as Dt,ak as Ca,a4 as Eo,dn as No,dp as hs,dq as Zs,dr as Po,bq as qo,ds as ei,dt as Lo,du as Mo,dv as Vo,dw as ti,e as Bo,dx as jo,dy as Ko,dz as Wo,dA as Uo,dB as Go,dC as Qo,dD as Ho,dE as Yo,dF as Jo,dG as zo,dH as Xo,dI as Zo,dJ as ms,am as en,dK as tn,bH as an,dL as sn,dM as on,dN as nn,dO as rn,dP as dn,dQ as ln,dR as cn,aa as un,dS as fn,ag as hn,dT as mn}from"../chunks/resolve-dashboard-input-context-Dm4PD8Gx.js";import{gr as Ql,ed as Hl,ei as Yl,bB as Jl,bA as zl,gX as Xl,gj as Zl,bk as ec,hU as tc,gi as ac,iU as sc,gd as ic,hE as oc,gk as nc,gl as rc,gN as dc,fJ as lc,fK as cc,fL as uc,fG as fc,fH as hc,fI as mc,fC as pc,fD as gc,fF as bc,fE as yc,aB as vc,fM as $c,gH as wc,g6 as Ic,eP as _c,hg as Cc,i7 as Sc,hf as xc,gR as kc,gY as Tc,eO as Fc,f_ as Ac,gt as Rc,eY as Dc,hG as Oc,eA as Ec,im as Nc,e7 as Pc,gK as qc,gw as Lc,gZ as Mc,is as Vc,iE as Bc,ff as jc,fg as Kc,iy as Wc,gg as Uc,gh as Gc,eV as Qc,hR as Hc,hP as Yc,hQ as Jc,e4 as zc,ik as Xc,aC as Zc,ew as eu,gv as tu,e$ as au,ip as su,gC as iu,eU as ou,iI as nu,iJ as ru,hr as du,eb as lu,jj as cu,jo as uu,gu as fu,fQ as hu,jn as mu,ia as pu,iO as gu,fs as bu,bS as yu,gc as vu,eW as $u,f8 as wu,e8 as Iu,h5 as _u,h6 as Cu,j9 as Su,b4 as xu,fN as ku,ft as Tu,jc as Fu,gJ as Au,d_ as Ru,j4 as Du,bI as Ou,jp as Eu,gS as Nu,gV as Pu,gU as qu,gT as Lu,i1 as Mu,hY as Vu,hp as Bu,ec as ju,bv as Ku,i9 as Wu,gy as Uu,iT as Gu,hV as Qu,hW as Hu,ib as Yu,d$ as Ju,jr as zu,jq as Xu,eh as Zu,ez as ef,h0 as tf,j3 as af,bl as sf,fn as of,iM as nf,hw as rf,hs as df,gB as lf,hI as cf,hq as uf,gM as ff,fZ as hf,fY as mf,jb as pf,ja as gf,eT as bf,gI as yf,hj as vf,ho as $f,es as wf,j5 as If,eH as _f,gG as Cf,f9 as Sf,fw as xf,fy as kf,fk as Tf,dY as Ff,iz as Af,fj as Rf,fe as Df,iD as Of,hh as Ef,hk as Nf,hl as Pf,f0 as qf,gQ as Lf,gO as Mf,hb as Vf,e0 as Bf,e9 as jf,ht as Kf,il as Wf,ea as Uf,bo as Gf,i6 as Qf,gp as Hf,gq as Yf,eG as Jf,eE as zf,eF as Xf,iP as Zf,iQ as eh,iS as th,fx as ah,et as sh,eu as ih,ev as oh,eX as nh,i3 as rh,i4 as dh,eZ as lh,be as ch,iL as uh,hB as fh,g2 as hh,j1 as mh,bG as ph,g3 as gh,g5 as bh,$ as yh,bD as vh,eM as $h,f5 as wh,g4 as Ih,h as _h,fz as Ch,bz as Sh,ek as xh,el as kh,ee as Th,fR as Fh,hm as Ah,gA as Rh,eL as Dh,h2 as Oh,f1 as Eh,iX as Nh,i$ as Ph,eD as qh,fd as Lh,ex as Mh,y as Vh,eQ as Bh,j2 as jh,ge as Kh,eR as Wh,eo as Uh,go as Gh,eB as Qh,A as Hh,hS as Yh,iR as Jh,e5 as zh,fW as Xh,h3 as Zh,fX as em,h7 as tm,bi as am,i2 as sm,hK as im,hJ as om,gD as nm,fp as rm,f4 as dm,f6 as lm,a2 as cm,f7 as um,i8 as fm,iY as hm,hz as mm,gm as pm,gz as gm,dU as bm,dV as ym,dW as vm,e1 as $m,iw as wm,io as Im,j8 as _m,gs as Cm,j6 as Sm,iq as xm,j0 as km,fm as Tm,eS as Fm,fv as Am,fi as Rm,fh as Dm,gn as Om,hy as Em,f$ as Nm,bg as Pm,g0 as qm,i0 as Lm,ej as Mm,bj as Vm,iN as Bm,gx as jm,bu as Km,iW as Wm,hu as Um,hi as Gm,g1 as Qm,iV as Hm,hn as Ym,hO as Jm,hM as zm,D as Xm,iv as Zm,fb as ep,eK as tp,it as ap,iA as sp,iB as ip,ga as op,fB as np,en as rp,js as dp,gW as lp,gP as cp,gL as up,dX as fp,fq as hp,fr as mp,jm as pp,fP as gp,ji as bp,er as yp,jg as vp,jh as $p,eI as wp,eJ as Ip,g7 as _p,g8 as Cp,eN as Sp,bt as xp,e2 as kp,eq as Tp,fT as Fp,hH as Ap,hD as Rp,iC as Dp,fU as Op,fS as Ep,iF as Np,em as Pp,bf as qp,hF as Lp,fo as Mp,hC as Vp,fA as Bp,je as jp,hZ as Kp,bm as Wp,iu as Up,h4 as Gp,hT as Qp,g9 as Hp,fl as Yp,eC as Jp,gf as zp,dZ as Xp,ep as Zp,gE as eg,jt as tg,hN as ag,jk as sg,hX as ig,h1 as og,fu as ng,fV as rg,e6 as dg,iK as lg,h_ as cg,gF as ug,iG as fg,ey as hg,g$ as mg,g_ as pg,hA as gg,hL as bg,iZ as yg,i_ as vg,e_ as $g,f3 as wg,e3 as Ig,ix as _g,ir as Cg,jl as Sg,iH as xg,fO as kg,fc as Tg,bd as Fg,hv as Ag,he as Rg,hx as Dg,gb as Og,jd as Eg,hd as Ng,i5 as Pg,id as qg,ef as Lg,h$ as Mg,ha as Vg,eg as Bg,jf as jg,ju as Kg,hc as Wg,f2 as Ug,h8 as Gg,h9 as Qg,ic as Hg,ie as Yg,ig as Jg,ih as zg,fa as Xg,ii as Zg,j7 as eb,ij as tb,bK as ab,bL as sb}from"../chunks/resolve-dashboard-input-context-Dm4PD8Gx.js";import{d as ai,s as pn}from"../chunks/set-q-2M4nis.js";import{a as ob,C as nb,b as rb,q as db,j as lb,g as cb,c as ub,h as fb,m as hb,J as mb,K as pb,D as gb,w as bb,x as yb,B as vb,I as $b,E as wb,z as Ib,H as _b,F as Cb,G as Sb,A as xb,i as kb,l as Tb,n as Fb,k as Ab,o as Rb,f as Db,p as Ob,e as Eb,R as Nb,O as Pb,P as qb,y as Lb,L as Mb,r as Vb,Q as Bb,t as jb,v as Kb,M as Wb,u as Ub,N as Gb}from"../chunks/set-q-2M4nis.js";import{R as Sa,S as gn,N as xa,T as bn,U as yn,W as ka,X as si,K as we,Y as ii,Z as vn,_ as $n,G as wn,O as In}from"../chunks/bookmark-state-DnkzIsyw.js";import{al as Hb,aE as Yb,a4 as Jb,a5 as zb,af as Xb,aj as Zb,ag as ey,ah as ty,ai as ay,am as sy,aC as iy,aw as oy,L as ny,aA as ry,M as dy,a8 as ly,H as cy,aD as uy,ab as fy,ac as hy,ay as my,ak as py,a9 as gy,av as by,az as yy,aB as vy,P as $y,ax as wy,J as Iy,a6 as _y,ao as Cy,at as Sy,a0 as xy,a1 as ky,$ as Ty,a2 as Fy,aa as Ay,au as Ry,aF as Dy,ap as Oy,an as Ey,aq as Ny,ar as Py,as as qy,ae as Ly,ad as My,a3 as Vy,a7 as By}from"../chunks/bookmark-state-DnkzIsyw.js";import{L as Ky,B as Wy,C as Uy,e as Gy,A as Qy,j as Hy,b as Yy,y as Jy,o as zy,q as Xy,z as Zy,x as ev,k as tv,n as av,p as sv,w as iv,D as ov,s as nv,u as rv,t as dv,v as lv}from"../chunks/stored-dashboard-CTwrNvBy.js";import{aX as oi,r as _n,ad as ps}from"../chunks/pivot-result-contract-expectations-D_ane7I2.js";import{aZ as uv,aY as fv,aQ as hv,aJ as mv,a_ as pv,aK as gv}from"../chunks/pivot-result-contract-expectations-D_ane7I2.js";import{g as ni,C as _t,D as Cn,l as Bt,S as Sn,m as ri,k as pt,n as gs,o as xn,p as kn,q as Tn,s as Fn,t as An,u as Rn,v as Dn,e as On}from"../chunks/filter-reach-preview-CfbwaLf4.js";import{N as yv,a4 as vv,X as $v,z as wv,F as Iv,H as _v,G as Cv,J as Sv,y as xv,I as kv,E as Tv,w as Fv,P as Av,b as Rv,a5 as Dv,R as Ov,T as Ev,a3 as Nv,K as Pv,a0 as qv,A as Lv,Y as Mv,U as Vv,a2 as Bv,a1 as jv,Q as Kv,M as Wv,O as Uv,x as Gv,_ as Qv,Z as Hv,W as Yv,$ as Jv,V as zv,B as Xv,L as Zv}from"../chunks/filter-reach-preview-CfbwaLf4.js";import{w as En}from"../chunks/custom-visual-write-BWApKrHe.js";import{P as bs,C as Nn,U as Pn}from"../chunks/matrix-analytical-definition-jn075ooo.js";import{l as Ta,D as ys,r as qn}from"../chunks/matrix-operation-contract-DceN49RX.js";import{f as fa,d as Ln}from"../chunks/raw-temporal-value-B4Md6Xfb.js";import{a9 as jt,k as Fa,aQ as Mn,b1 as Me,aO as Kt,aP as di,j as Vn,aH as li,aT as Bn,aN as jn,l as Kn}from"../chunks/validators-U8IL8djK.js";import{C as gt,D as ft,B as Wn,T as Un,z as Aa,t as bt,c as Gn}from"../chunks/analytics-base-schemas-DMFrDqn_.js";import"../value-format-preferences/index.js";import"zod";import"../chunks/schema-O1Y3WTGF.js";import{r as Qn}from"../chunks/index-DViPGDFj.js";import"../chunks/context-Cwj8Axgd.js";import{m as vs,c as Hn,b as Yn,f as ci}from"../chunks/kpi-trend-rule-B4ebKzNj.js";import{K as t$,a as a$,d as s$}from"../chunks/kpi-trend-rule-B4ebKzNj.js";import{f as Jn}from"../chunks/selection-filter-compiler-BxtEEB6Z.js";import{v as Ot,a as zn,i as $s,o as Jt,d as Xn,b as Zn,c as er}from"../chunks/variable-draft-DAVLIY3l.js";import{S as o$,f as n$,g as r$,e as d$,n as l$}from"../chunks/variable-draft-DAVLIY3l.js";import{b as u$,d as f$}from"../chunks/bookmark-impact-BEVaXjug.js";import{r as Ze,b as tr,a as ar,s as sr}from"../chunks/resolver-CjsW8Rz0.js";import{n as ir,r as or}from"../chunks/index-bkP6SnYu.js";import{e as m$}from"../chunks/brand-BjC1mPjw.js";const zt=["#14b8a6","#5eead4","#374151","#6b7280","#d1d5db"],nr=["spacing","canvasPadding","canvas","cardCorners","chartColors"],ui=["light","dark"];function Pl(e){const t=[],a=Zt(e.globalStyle)?e.globalStyle:{},s=Zt(a.default)?a.default:{},i=Zt(a.dark)?a.dark:{},n=b=>Ze(i,b)??Ze(s,b),l={},c=n(["gridLayout","margin"]);Array.isArray(c)&&typeof c[1]=="number"&&(l.spacing=ut("spacing",c[1],t),l.canvasPadding=ut("canvasPadding",c[1],t));const u=n(["cardBorderRadius"]);typeof u=="number"&&(l.cardCorners=ut("cardCorners",u,t));const r=n(["controlInputRadius"]);typeof r=="number"&&(l.controlCorners=ut("controlCorners",r,t));const p=n(["chart","options","borderRadius"]);typeof p=="number"&&(l.barCorners=ut("barCorners",p,t));for(const b of ui){const w=b==="light"?Ze(s,["canvasTheme"]):n(["canvasTheme"]),g=lr(w,t);g!==void 0&&(l.canvas={...l.canvas,[b]:g});const S=dr(s,i,b);if(S){const k=S.filter(ni).map(A=>A.toLowerCase());k.length<S.length&&t.push({field:"chartColors",kind:"dropped_colour",detail:`${b}: ${S.length-k.length} colours that aren't hex`}),k.length>=_t.min&&(l.chartColors={...l.chartColors,[b]:k.slice(0,_t.max)}),k.length>_t.max&&t.push({field:"chartColors",kind:"clamped",detail:`${b}: kept the first ${_t.max} colours`});}}return{style:rr(l,e.organizationAppearance,t),notes:t};}function rr(e,t,a){const s=tr({organizationAppearance:t?ir(t).spec:null}),i={...e};for(const n of Object.keys(e)){const l=ar[n],c=n==="canvas"||n==="chartColors";for(const u of ui){const r=sr(i,n,u);if(r===void 0)continue;const p=nr.includes(n)&&Ze(or(t,u),l)!==void 0,b=JSON.stringify(Ze(s.schemes[u],l))===JSON.stringify(r);if(!(!p&&!b))if((c||u==="light")&&a.push({field:n,kind:p?"brand_wins":"equal_to_inherited",detail:c?u:`${JSON.stringify(r)}`}),c){const w={...i[n]};delete w[u],Object.keys(w).length>0?i[n]=w:delete i[n];}else u==="light"&&delete i[n];}}return Object.keys(i).length>0?i:void 0;}function dr(e,t,a){const s=Ze(e,["chart","dataset","backgroundColor"]),i=Ze(t,["chart","dataset","backgroundColor"]),n=Xt(zt,s);if(a==="light")return Array.isArray(s)?n:void 0;const l=Xt(n,Xt(zt,i));if(!(!Array.isArray(i)&&JSON.stringify(l)===JSON.stringify(zt)))return Array.isArray(s)||Array.isArray(i)?l:void 0;}function Xt(e,t){if(!Array.isArray(t))return[...e];const a=Math.max(e.length,t.length);return Array.from({length:a},(s,i)=>t[i]!==void 0?String(t[i]):e[i]);}function lr(e,t){if(!(e==null||e==="")){if(e==="muted")return"muted";if(e==="clear")return"background";if(ni(e))return e.toLowerCase();t.push({field:"canvas",kind:"dropped_colour",detail:String(e)});}}function ut(e,t,a){const{min:s,max:i}=Cn[e],n=Math.min(i,Math.max(s,Math.round(t)));return n!==t&&a.push({field:e,kind:"clamped",detail:`${t} → ${n}`}),n;}function Zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e);}const ea={spacing:(e,t)=>t.spacing=e,canvasPadding:(e,t)=>t.canvasPadding=e,canvas:(e,t)=>t.canvas=e,cardBorder:(e,t)=>t.border=e,cardShadow:(e,t)=>t.shadow=e,cardCorners:(e,t)=>t.corners={...t.corners,cards:e},controlCorners:(e,t)=>t.corners={...t.corners,controls:e},chartColors:(e,t)=>t.chartColors=e,barCorners:(e,t)=>t.barCorners=e};function cr(e){var a;const t={};for(const[s,i]of Object.entries(e??{}))i!==void 0&&((a=ea[s])==null||a.call(ea,i,t));return t;}function ws(e){var l;const{card:t,stated:a,path:s}=e;let i;if(a.slots){i={};for(const[c,u]of Object.entries(a.slots)){if(u===null){i[c]=null;continue;}const r=ur(t,u,e.sqlColumns);if(!r.ok)return{ok:!1,problem:{code:"invalid_change",message:`The card has no field "${u}" for the slot "${c}"${r.fields.length?`; its fields are ${r.fields.join(", ")}`:""}.`,path:`${s}.slots.${c}`,fix:"Name one of the card's query fields, or add the field to the query.",...(r.fields.length?{allowed:r.fields}:{})}};i[c]=r.ref;}}const n=En(t,{...(a.html!==void 0?{html:a.html}:{}),...(i?{slots:i}:{}),...(a.settings?{settings:a.settings}:{})},{manifest:e.manifest});if(!n.ok)return{ok:!1,problem:{...n.problem,path:n.problem.path?`${s}.${n.problem.path}`:s}};for(const[c,u]of Object.entries(i??{})){const r=(l=n.manifest)==null?void 0:l.slots.find(b=>b.id===c),p=u?fr(t,u):void 0;if(r&&p&&p!==r.kind)return{ok:!1,problem:{code:"invalid_change",message:`The slot "${c}" (${r.label}) takes a ${r.kind}, and "${a.slots[c]}" is a ${p}.`,path:`${s}.slots.${c}`,fix:`Name a ${r.kind} of the card's query for it.`}};}return{ok:!0,card:n.card,wording:hr(t.customVisual,n.card.customVisual,n.manifest,n.card,a)};}function fi(e){var s,i;const t=(i=(s=e.customVisual)==null?void 0:s.draft)==null?void 0:i.html;if(t===void 0)return;const a=Ni(t,{kind:"visual"});return a.ok?a.manifest:void 0;}function ur(e,t,a){var l,c,u;const s=t.trim().toLowerCase();if((l=e.sql)!=null&&l.trim()){if(!a)return{ok:!0,ref:{column:t}};const r=a.find(p=>p.toLowerCase()===s);return r?{ok:!0,ref:{column:r}}:{ok:!1,fields:[...a]};}const i=[...(((c=e.config)==null?void 0:c.groupByColumns)??[]),...(((u=e.config)==null?void 0:u.metricColumns)??[])],n=i.find(r=>{var p;return((p=r.label)==null?void 0:p.toLowerCase())===s;})??i.find(r=>{var p;return((p=r.name)==null?void 0:p.toLowerCase())===s;});return n!=null&&n.id?{ok:!0,ref:{fieldId:n.id}}:{ok:!1,fields:i.map(r=>r.label||r.name||"").filter(Boolean)};}function fr(e,t){var a,s;if("fieldId"in t){if((((a=e.config)==null?void 0:a.groupByColumns)??[]).some(i=>i.id===t.fieldId))return"dimension";if((((s=e.config)==null?void 0:s.metricColumns)??[]).some(i=>i.id===t.fieldId))return"measure";}}function hi(e,t,a="label"){var n,l;if(!t)return null;if("column"in t)return t.column;const i=[...(((n=e.config)==null?void 0:n.groupByColumns)??[]),...(((l=e.config)==null?void 0:l.metricColumns)??[])].find(c=>c.id===t.fieldId);return(a==="name"?(i==null?void 0:i.name)||(i==null?void 0:i.label):(i==null?void 0:i.label)||(i==null?void 0:i.name))||t.fieldId;}function hr(e,t,a,s,i){var l;const n={};if(t!=null&&t.draft&&t.draft.html!==((l=e==null?void 0:e.draft)==null?void 0:l.html)&&(n.code=(a==null?void 0:a.name)??"the visual"),i.settings&&a){const c=Object.keys(i.settings).filter(u=>{var r,p;return((r=e==null?void 0:e.settings)==null?void 0:r[u])!==((p=t==null?void 0:t.settings)==null?void 0:p[u]);}).map(u=>{var w,g,S;const r=(w=a.settings)==null?void 0:w[u],p=((g=t==null?void 0:t.settings)==null?void 0:g[u])??(r==null?void 0:r.default),b=(r==null?void 0:r.type)==="select"?((S=r.options.find(k=>k.value===p))==null?void 0:S.label)??String(p):(r==null?void 0:r.type)==="boolean"?p?"on":"off":String(p);return{label:(r==null?void 0:r.label)??u,value:b};});c.length&&(n.settings=c);}if(i.slots&&a){const c=Object.keys(i.slots).filter(u=>{var r,p;return JSON.stringify((r=e==null?void 0:e.slots)==null?void 0:r[u])!==JSON.stringify((p=t==null?void 0:t.slots)==null?void 0:p[u]);}).map(u=>{var r,p;return{label:((r=a.slots.find(b=>b.id===u))==null?void 0:r.label)??u,field:hi(s,(p=t==null?void 0:t.slots)==null?void 0:p[u])};});c.length&&(n.slots=c);}return n;}function Is(e,t){var n;const a=e.customVisual??{},s=((n=fi(e))==null?void 0:n.name)??(a.extensionId?t==null?void 0:t[a.extensionId]:void 0),i=Object.fromEntries(Object.entries(a.slots??{}).map(([l,c])=>[l,hi(e,c,"name")??""]));return{...(s?{name:s}:{}),...(a.extensionId?{extensionId:a.extensionId}:{}),...(a.version?{version:a.version}:{}),...(a.draft?{unsaved:!0}:{}),...(Object.keys(i).length?{slots:i}:{}),...(a.settings&&Object.keys(a.settings).length?{settings:{...a.settings}}:{})};}function mr(e,t,a){var n;const s=[],i=Ie(e);for(const[l,c]of t){const u=i.findFilterInput({inputId:l});if(!u)continue;const r=(n=Ms(e.defaultInputValues??{},u.input,{}))==null?void 0:n.comparisonSelection;if((r==null?void 0:r.mode)!=="period")continue;const p=Ta(r.spec);if(p.kind!=="shift")continue;const b=Bt({dashboard:e,target:{kind:"dashboardInput",input:u.input,scope:{}},calendar:a}).value,w=Pi(b,a);if(!w||!fa(p,w))continue;const g=oi(p,w);s.push({code:"invalid_change",message:`"${u.input.label}"'s default comparison: ${g.message}`,path:`changes[${c.changeIndex}]${c.statedComparison?".defaultComparison":""}`,fix:c.statedComparison?g.fix:`${g.fix} Or keep this default and set defaultComparison to one that clears it.`});}return s;}function _s(e){return Sa(e).map(t=>t.kind==="variable"?{id:t.id,title:`the variable ${t.variable.name}`,card:t.card}:{id:t.id,title:t.card.title||"Untitled",card:t.card});}const Cs=e=>qi(e).flatMap((t,a)=>(t==null?void 0:t.kind)==="shift"?[{index:a,spec:t}]:[]);async function pr(e){const t=[],a=new Map(_s(e.before).map(s=>[s.id,s]));for(const s of _s(e.after)){const i=Cs(s.card);if(!i.length)continue;const n=(await e.readComparisonDates({card:s.card,dashboard:e.after})).window;if(!n)continue;const l=i.filter(p=>fa(p.spec,n));if(!l.length)continue;const c=a.get(s.id),u=c?(await e.readComparisonDates({card:c.card,dashboard:e.before})).window:void 0,r=c?Cs(c.card):[];for(const p of l){const b=r.find(S=>S.index===p.index);if(b&&u&&JSON.stringify(b.spec)===JSON.stringify(p.spec)&&fa(b.spec,u))continue;const g=oi(p.spec,n);t.push({code:"comparison_overlaps_date_window",message:`"${s.title}": ${g.message}`,path:`changes[${e.changeIndexOf(s.id)}]`,fix:`${g.fix} Or keep it: it shows when a viewer picks a range it clears.`,details:{measureIndex:p.index}});}}return t;}function gr(e){const[t]=Li({inputs:[{id:`reach-${e.id}`,kind:"filter",label:e.title||e.column,variableName:"reach",scope:{kind:"allSheets"},runtimeScope:"shared",filter:e,definitionOrigin:"embedded"}],dashboardFilters:[]});return t;}function br(e,t,a){const s=Xe(e,t,a);return{...s,reached:Vs(s.reach)};}const yr={global_date:"The date filter for the whole report can't be changed through the MCP. Change it in the editor; removing or excluding it works.",not_semantic:"This filter reads a database table, not a dataset, so it can't be changed through the MCP. Change it in the editor; removing or excluding it works.",scope_not_expressible:"This filter applies to chosen cards rather than whole sheets, so it can't be changed through the MCP. Change it in the editor; removing or excluding it works."};function vr(e,t,a={}){var c;const s=Ie(e),i=gn(t.scope),n=new Set(Sa(e).map(u=>u.id)),l={reaches:[],excluded:[.../* @__PURE__ */new Set([...(((c=t.application)==null?void 0:c.cards)??[]).filter(u=>u.kind==="excluded").map(u=>u.cardId),...i.filter(u=>n.has(u))])],notReached:[]};if(t.filter.kind==="global-date"){const u=new Set(l.excluded);return l.reaches=[...Vi(e,t.filter).filter(({card:r})=>!u.has(r.id)&&Pe(r)).map(({card:r})=>r.id),...s.reachedVariables({inputId:t.id}).map(r=>r.variableId).filter(r=>!u.has(r))],l;}for(const u of s.reachedCards({inputId:t.id})){const r=Xe(t,u.card,a),p=r.reach,b=()=>{const w=Pe(u.card);return{cardId:u.cardId,title:u.card.title??"",...((w==null?void 0:w.kind)==="semantic"?{datasetName:w.datasetName}:{})};};if(Vs(p)){l.reaches.push(u.cardId);continue;}switch(p){case"blocked":case"ambiguous":(l.blocked??(l.blocked=[])).push({cardId:u.cardId,title:u.card.title??"",reason:p});break;case"relationship":(l.relationshipPending??(l.relationshipPending=[])).push(b());break;case"sqlTemplate":(l.sqlPending??(l.sqlPending=[])).push({cardId:u.cardId,title:u.card.title??""});break;case"excluded":break;case"notApplicable":Pe(u.card)&&l.notReached.push({...b(),...(r.reason?{reason:r.reason}:{})});break;default:{const w=p;throw new Error(`Unhandled filter reach ${String(w)}`);}}}for(const u of s.reachedVariables({inputId:t.id})){const r=xa(e,u.variableId);if((r==null?void 0:r.kind)!=="variable")continue;const p=Xe(t,r.card,a),b=Pe(r.card),w={cardId:r.id,title:r.variable.name,...((b==null?void 0:b.kind)==="semantic"?{datasetName:b.datasetName}:{})};switch(p.reach){case"bound":case"automatic":case"sql":case"relationshipApplied":l.reaches.push(r.id);break;case"blocked":case"ambiguous":(l.blocked??(l.blocked=[])).push({cardId:r.id,title:r.variable.name,reason:p.reach});break;case"relationship":(l.relationshipPending??(l.relationshipPending=[])).push(w);break;case"sqlTemplate":(l.sqlPending??(l.sqlPending=[])).push({cardId:r.id,title:r.variable.name});break;case"excluded":break;case"notApplicable":l.notReached.push({...w,...(p.reason?{reason:p.reason}:{})});break;}}return l;}function $r(e,t){var i;const a=t.scope;if(a.kind==="allSheets"){if((i=a.sheetKinds)!=null&&i.length&&!a.sheetKinds.includes("dashboard"))return;const n=bn(a);return{sheetIds:"all",...(n.length?{exceptSheetIds:[...n]}:{}),...(yn(a)?{includesDocumentSheets:!0}:{})};}if(a.kind!=="sheets")return;const s=[...ka(e).values()].filter(n=>si(t,n));return{sheetIds:s.filter(n=>n.sheetKind==="dashboard").map(n=>n.sheetId),...(s.some(n=>n.sheetKind==="document")?{includesDocumentSheets:!0}:{})};}function qt(e,t){return e??{tz:"UTC",weekStart:1,anchor:{iso:t??"1970-01-01T00:00:00.000Z"}};}function mi(e,t,a,s){var g,S,k;const{input:i}=t,n=vr(e,i,s),l=(A,I)=>({filterId:i.id,label:i.label,editable:!1,kind:I,notEditable:{reason:A,message:yr[A]},reaches:n.reaches,excluded:n.excluded,...(n.blocked?{blocked:n.blocked}:{}),...(n.relationshipPending?{relationshipPending:n.relationshipPending}:{}),...(n.sqlPending?{sqlPending:n.sqlPending}:{})});if(i.filter.kind==="global-date")return l("global_date","global_date");const c=Mi(i.filter).filter(A=>A.kind==="semantic");if(c.length!==1||c[0].kind!=="semantic")return l("not_semantic","field");const u=$r(e,i);if(!u||t.origin!=="embeddedInput")return l("scope_not_expressible","field");const r=((g=i.filter.fieldMeta)==null?void 0:g.name)??((S=i.filter.column)==null?void 0:S.split(".").pop())??"",p=Bt({dashboard:e,target:{kind:"dashboardInput",input:i,scope:{}},calendar:qt(a,void 0)}).value,b=pi(i.filter,p),w=(k=Ms(e.defaultInputValues??{},i,{}))==null?void 0:k.comparisonSelection;return{filterId:i.id,label:i.label,editable:!0,domainId:c[0].domainId,datasetName:c[0].datasetName,field:r,...b,...((w==null?void 0:w.mode)==="period"?{defaultComparison:Ta(w.spec)}:{}),...u,...n};}function pi(e,t){var r;const a=jt(e.dataType),s=ca(e),i=s==="range"&&t&&Bi(t.operation)?{operation:t.operation,values:(t.values??[]).map(Number)}:void 0,n=a||(r=t==null?void 0:t.values)==null?void 0:r.filter(p=>["string","number","boolean"].includes(typeof p)),l=Fa(t&&"relativeMeta"in t?t.relativeMeta:void 0),c=a?l:void 0,u=c?Ir(t==null?void 0:t.operation,c)??Mn(c,{use:"filterDefault",columnHasTime:js(e)==="datetime"},"defaultPeriod"):void 0;return{selection:e.type==="single"?"single":"multiple",...(s?{showAs:s}:{}),...((s!=="range"||!i)&&n!=null&&n.length?{defaultValues:n}:{}),...(i?{defaultCondition:ji(i)}:{}),...(c?{defaultPeriod:c}:{}),...(u?{defaultPeriodReadOnly:u}:{}),...(a?{datePicker:e.dateSelectionMode==="day"?"day":e.dateSelectionMode==="months"?"month":"range"}:{})};}function wr(e,t){return(e.inlineFilters??[]).map(a=>{var s,i,n;return{filterId:a.id,label:a.title,field:((s=a.fieldMeta)==null?void 0:s.name)??((i=a.column)==null?void 0:i.split(".").pop())??"",...((n=a.fieldMeta)!=null&&n.entityName?{datasetName:a.fieldMeta.entityName}:{}),...pi(a,Bs(a,qt(t,void 0)))};});}function Ir(e,t){const a=typeof e=="string"?Ln(e,t):void 0;return a?{reason:"point_default",message:`The default is "${a}", a condition set in the editor. It stays while defaultPeriod is left out.`,fix:"Send a range window as defaultPeriod to replace it.",suggestions:[]}:void 0;}function Ra(e,t,a){return Ie(e).inputs.map(s=>mi(e,s,t,a));}function Ve(e,t,a,s){const i=Ie(e).findFilterInput({inputId:t});return i?mi(e,i,a,s):void 0;}const Da=e=>`${e.domainId}\0${e.datasetName}`;function gi(e,t){var s;if(((s=e.source)==null?void 0:s.kind)==="semantic")return{domainId:e.source.domainId,datasetName:e.source.datasetName};if(!t)return;const a=va(e);return{domainId:t.domainId,datasetName:a||t.datasetName};}function bi(e){const t=Pe(e);return(t==null?void 0:t.kind)==="semantic"?{domainId:t.domainId,datasetName:t.datasetName}:void 0;}function yi(e){const t=e.config,a=t==null?void 0:t.matrix;return a?[...[...a.spec.rows,...a.spec.columns].map(s=>({ref:{kind:"matrixLevel",levelId:s.id},field:s.field})),...a.spec.measures.flatMap(s=>s.kind==="aggregate"?[{ref:{kind:"matrixMeasure",measureId:s.id},field:s.field}]:[])]:[...((t==null?void 0:t.groupByColumns)??[]),...((t==null?void 0:t.metricColumns)??[]),...((t==null?void 0:t.detailColumns)??[])].map(s=>({ref:{kind:"field",fieldId:s.id},field:s}));}function _r(e){const t=bi(e),a=/* @__PURE__ */new Map();for(const{field:s}of yi(e)){const i=gi(s,t);i&&a.set(Da(i),i);}return[...a.values()];}function Cr(e,t,a){if(!a)return;const s=ns(t),i=yi(e).find(c=>ns(c.ref)===s);if(!i)return;const n=gi(i.field,bi(e)),l=n?a[Da(n)]:void 0;return l?Vt(l,i.field.name,n.datasetName):void 0;}const ha=["orientation","stack","donut","columnOrder","totals","dataLabels","legend","axes","comparisonDisplay","trend","trendGrain","seeRecords","columnFilters","tableSearch"],vi=[...ha,"inheritComparison"],Sr={orientation:"orientation",stack:"stacking",donut:"donut hole",columnOrder:"column order",totals:"total row",dataLabels:"data labels",legend:"legend",axes:"axes",comparisonDisplay:"comparison display",trend:"trend under its value",trendGrain:"trend grain",seeRecords:"records to see",columnFilters:"column filters",tableSearch:"search"},xr={x:"xAxisConfig",y:"yAxisConfig"},ta={x:"horizontal",y:"vertical"};function kr(e){const t=`${e.sql?"SQL ":""}${Ji(e.type)}`;return`${/^[aeiou]/i.test(t)?"an":"a"} ${t}`;}function $i(e,t,a){const s=Object.fromEntries(Object.entries(t).filter(([i,n])=>n!==void 0&&!a.includes(i)));return Object.keys(s).length?{op:"card.update",cardId:e.cardRef,...s}:void 0;}const Tr="Set comparison on each measure in query.measures: { kind: 'inherit' } follows the Date filter, { kind: 'off' } shows none, a shift or target is the measure's own.";function Fr(e){var a;const t=[];return e.inheritComparison!==void 0&&t.push({path:"inheritComparison",message:"Whether a measure follows the Date filter is its own comparison now, not a card setting."}),((a=e.comparisonDisplay)==null?void 0:a.show)!==void 0&&t.push({path:"comparisonDisplay.show",message:"Whether a measure shows a comparison is its own comparison now, not a card setting."}),t;}function Ar(e,t){const{inheritComparison:a,comparisonDisplay:s,...i}=t,{show:n,...l}=s??{},c=Object.keys(l).length?{...i,comparisonDisplay:l}:i;return $i(e,c,[]);}function Rr(e,t,a,s,i){var S,k,A,I,F,y,V,D,O,Y,R,E,B,U;const n=Fr(a);for(const{path:N,message:J}of n)i.push(ae("invalid_change",{message:`${J} (${te(e.title)})`,path:`${s.path}.${N}`,fix:Tr,suggestedChange:Ar(s,a)}));if(n.length)return{};const l=ha.filter(N=>a[N]!==void 0);if(!l.length)return{};const c=ha.filter(N=>t.settings.has(N)),u=l.filter(N=>!t.settings.has(N));for(const N of u)i.push(ae("setting_not_for_card",{message:`${te(e.title)} is ${kr(t)}, which has no ${Sr[N]}.`,path:`${s.path}.${N}`,fix:c.length?`Leave out ${N}; this card takes ${c.join(", ")}.`:`Leave out ${N}.`,allowed:c,suggestedChange:$i(s,a,u)}));if(u.length)return{};const r={},p=((S=ze(e))==null?void 0:S.properties)??{},b={...p,...(a.orientation!==void 0?{orientation:a.orientation}:{}),...(a.stack!==void 0?{stack:a.stack}:{}),...(a.donut!==void 0?{donut:a.donut}:{})};["orientation","stack","donut"].some(N=>b[N]!==p[N])&&(r.variant=Ki(t.type,b));const w=r.variant?Wi(e,r.variant):e,g=$a(w);if(a.columnOrder){const N=Ui(e,t,a.columnOrder,s,i);N&&(r.columnOrder=N);}if(a.totals){const N=Gi(e,t,a.totals,((k=g.totals)==null?void 0:k.row)??!1,s,i);N&&(r.totals=N);}if(a.dataLabels){const N={};a.dataLabels.show!==Qi(w)&&(N.show=a.dataLabels.show);const J=a.dataLabels.format;if(J===null&&(A=g.dataLabels)!=null&&A.format&&(N.format=null),J){const P=Dr(e,t,J,`${s.path}.dataLabels.format`,i);P&&!Me(P,(I=g.dataLabels)==null?void 0:I.format)&&(N.format=P);}Object.keys(N).length&&(r.dataLabels=N);}if(a.legend){const N={};a.legend.show!==((F=g.legend)==null?void 0:F.show)&&(N.show=a.legend.show),a.legend.position!==void 0&&a.legend.position!==((y=g.legend)==null?void 0:y.position)&&(N.position=a.legend.position),Object.keys(N).length&&(r.legend=N);}if(a.axes){const N=Hi(w.type,w.preferences),J={};for(const P of["x","y"]){const T=a.axes[P];if(!T)continue;const M=Or(e,P,T,((V=g.axes)==null?void 0:V[P])??{},P===N,`${s.path}.axes.${P}`,i);M&&(J[xr[P]]=M);}Object.keys(J).length&&(r.axes=J);}if(a.comparisonDisplay){const N=(D=e.preferences)==null?void 0:D.comparisonPresentation,J={},{mode:P,precision:T}=a.comparisonDisplay;P!==void 0&&P!==((N==null?void 0:N.displayMode)??"difference")&&(J.mode=P),T!==void 0&&T!==((N==null?void 0:N.precision)??null)&&(J.precision=T),Object.keys(J).length&&(r.comparisonDisplay=J);}if(a.seeRecords!==void 0&&a.seeRecords!==(e.seeRecords!==!1)&&(r.seeRecords=a.seeRecords),a.columnFilters!==void 0&&a.columnFilters!==(((Y=(O=e.preferences)==null?void 0:O.tablePrefs)==null?void 0:Y.allowViewerColumnFilters)!==!1)&&(r.columnFilters=a.columnFilters),a.tableSearch!==void 0&&a.tableSearch!==(((E=(R=e.preferences)==null?void 0:R.tablePrefs)==null?void 0:E.allowViewerSearch)!==!1)&&(r.tableSearch=a.tableSearch),a.trend!==void 0&&a.trend!==(((B=e.config)==null?void 0:B.kpiBand)==="trend")&&(r.trend=a.trend),a.trendGrain!==void 0){const N=Yi(e.config);N?i.push(ae("value_invalid",{message:`${te(e.title)} draws its trend by its Trend By${N.granularity?`, by ${N.granularity}`:""}, so it takes no grain of its own.`,path:`${s.path}.trendGrain`,fix:"Change the Trend By's timeGrain in its query, or remove the Trend By to set a grain here.",allowed:[]})):a.trendGrain!==(((U=e.config)==null?void 0:U.kpiTrendGrain)??"automatic")&&(r.trendGrain=a.trendGrain==="automatic"?null:a.trendGrain);}return r;}function Dr(e,t,a,s,i){const n=String(a.type),l=zi("cartesian","number"),c=gt(n),u=c==null?void 0:c.safeParse(a);if(!l.includes(n)||!(u!=null&&u.success)){const p=u&&!u.success?u.error.issues[0]:void 0;i.push(ae("format_invalid",{message:l.includes(n)?`That format for the values on ${te(e.title)} isn't valid: ${(p==null?void 0:p.message)??"invalid"}.`:`The values on ${te(e.title)} are numbers, so they can't take a ${n.replace("_"," ")} format.`,path:s,fix:"Send a whole number, currency, percent, scientific or duration format.",allowed:l.includes(n)?ft(n):[...l]}));return;}const r=Ks({surface:t.type==="pie"?"pie":"cartesian",value:"number",rawValueKinds:[]},u.data);if(!r.ok){i.push(ae("format_invalid",{message:`${te(e.title)} can't draw that format on its values: ${r.reason}.`,path:s}));return;}return u.data;}function Or(e,t,a,s,i,n,l){const c={};a.title!==void 0&&(a.title!==null&&!a.title.trim()?l.push(ae("value_invalid",{message:"An axis title can't be empty.",path:`${n}.title`,fix:"Send a title, or null for none."})):(a.title??void 0)!==s.title&&(c.title=a.title));const u=["min","max"].filter(r=>a[r]!==void 0&&a[r]!==null);if(!i&&u.length){const r=ta[t==="x"?"y":"x"];l.push(ae("setting_not_for_card",{message:`${te(e.title)}'s ${ta[t]} axis lists categories; set a range on its ${r} axis.`,path:`${n}.${u[0]}`,allowed:["title"]}));return;}if(i){for(const b of["min","max"]){const w=a[b];if(w!==void 0){if(w!==null&&!Number.isFinite(w)){l.push(ae("value_invalid",{message:`An axis ${b} must be a number.`,path:`${n}.${b}`}));return;}(w??void 0)!==s[b]&&(c[b]=w);}}const r=a.min!==void 0?a.min:s.min,p=a.max!==void 0?a.max:s.max;if(typeof r=="number"&&typeof p=="number"&&r>p){l.push(ae("value_invalid",{message:`The ${ta[t]} axis of ${te(e.title)} can't start at ${r} and end at ${p}.`,path:n,fix:"Send a min no greater than the max."}));return;}}return Object.keys(c).length?c:void 0;}function Ss(e,t,a,s,i){const n=i==="date"&&s.role==="dimension";return ae("setting_not_for_card",{message:i==="text"?`${t} on ${te(e.title)} shows its text as it is; text formats apply on a Matrix only.`:i==="category"?`${t} labels the categories of ${te(e.title)}, which a chart shows as the query returns them; format it on a table or a Matrix.`:`${te(e.title)} shows ${t}, ${wi(s)}, without a format of its own; this card type doesn't apply one.`,path:a,...(n?{fix:`Group ${t} by day, week, month, quarter or year to format its dates.`}:{})});}const wi=e=>e.granularity?`a date grouped by ${e.granularity}`:e.dataType?`a ${e.dataType.toLowerCase()}`:"this column";function Be(e,t){return`${e}.columns[${JSON.stringify(t)}]`;}function ot(e,t,a,s){const{[s]:i,...n}=a;return Object.keys(n).length?{op:"card.update",cardId:e.cardRef,columns:{[t]:n}}:void 0;}function Er(e,t,a){const{hidden:s,width:i,...n}=a;return Object.keys(n).length?{op:"card.update",cardId:e.cardRef,columns:{[t]:n}}:void 0;}function Ct(e,t,a){return{op:"card.update",cardId:e.cardRef,columns:{[t]:{format:a}}};}function Nr(e,t,a,s,i,n,l){var r;const c=i.label;if(c===void 0||c===a.label)return;const u=`${Be(n.path,s)}.label`;if(!t.settings.has("columns.label")||!a.labelKey){l.push(ae("setting_not_for_card",{message:t.sql?`${te(e.title)}'s column ${s} takes its header from the query; rename it in the SQL.`:`${s} on ${te(e.title)} takes no header of its own.`,path:u,allowed:["hidden","width","format"].filter(p=>p!=="hidden"||t.settings.has("columns.hidden")),suggestedChange:ot(n,s,i,"label")}));return;}if(c===null){const p=((r=Cr(e,a.ref,n.catalogs))==null?void 0:r.label)||a.field||a.label;return a.labelInherited&&a.label===p?void 0:{key:a.labelKey,label:p,origin:"semantic"};}if(!c.trim()){l.push(ae("value_invalid",{message:"A column header can't be empty.",path:u,fix:"Send a header, or null to use the model's."}));return;}return{key:a.labelKey,label:c};}function Pr(e,t,a,s,i,n,l){var R,E,B;const c=`${Be(n.path,s)}.format`;if(!t.settings.has("columns.format")){l.push(ae("setting_not_for_card",{message:`${te(e.title)} takes no column formats.`,path:c}));return;}const u=a.ref,r=((R=n.modelFormats)==null?void 0:R.status)==="read"?n.modelFormats.formats:void 0,p=u.kind==="matrixLevel"?r==null?void 0:r[u.levelId]:u.kind==="matrixMeasure"?r==null?void 0:r[u.measureId]:void 0,b=_n({card:e,column:u,...(r?{modelFormats:r}:{}),...(p?{catalogFormat:p}:{})}),w=b.source==="override"?b.format:void 0;if(i===null)return w?null:void 0;if(w&&Me(i,w))return;const g=so(e,t,a,n.sqlResultColumns),S=g.value,k=io(g);if(k.length===0){l.push(Ss(e,s,c,a,S));return;}const A=!("type"in i)||i.type===void 0;if(A&&!b.format){const U=k[0];l.push(ae("format_invalid",{message:((E=n.modelFormats)==null?void 0:E.status)==="unavailable"?`${s} on ${te(e.title)} may follow its model's format, which couldn't be read; state the whole format with its type.`:`${s} on ${te(e.title)} has no format to change; state the whole format with its type.`,path:c,fix:"Add `type` to the format.",allowed:ft(U),suggestedChange:Ct(n,s,{type:U,...i})}));return;}const I=A?{...b.format,...i}:i,F=String(I.type);if(!k.includes(F)){l.push(F==="string"?Ss(e,s,`${c}.type`,a,"text"):ae("format_invalid",{message:S==="result"?`${s} on ${te(e.title)} comes straight from the query, so it can't take a ${F.replace("_"," ")} format.`:`${s} on ${te(e.title)} is ${wi(a)}, so it can't take a ${F.replace("_"," ")} format.`,path:`${c}.type`,allowed:[...k]}));return;}const y=gt(F),V=y==null?void 0:y.safeParse(I);if(!y||!(V!=null&&V.success)){const U=V&&!V.success?V.error.issues[0]:void 0;l.push(ae("format_invalid",{message:y?(U==null?void 0:U.code)==="unrecognized_keys"?`A ${F} format has no ${U.keys.join(", ")}.`:`That format for ${s} isn't valid: ${(U==null?void 0:U.message)??"invalid"}.`:`${JSON.stringify(F)} isn't a format type.`,path:c,fix:jr(F),allowed:y?ft(F):[...Wn],...(b.format?{suggestedChange:Ct(n,s,b.format)}:{})}));return;}const D=V.data;if(D.type==="temporal_bucket"&&a.granularity){const U=a.granularity,N=ps(D,U);if(!N.ok){const J=oo(U)?no(U).map(P=>({type:"temporal_bucket",presentation:{mode:"pattern",pattern:P}})):Un.map(P=>({type:"temporal_bucket",presentation:{mode:"preset",preset:P}})).filter(P=>ps(P,U).ok);l.push(ae("date_finer_than_grain",{message:`${s} on ${te(e.title)} is grouped by ${a.granularity}, which that date format doesn't fit: ${N.message}`,path:c,allowed:J.map(({presentation:P})=>P.mode==="pattern"?P.pattern:P.mode==="preset"?P.preset:"auto"),...(J[0]?{suggestedChange:Ct(n,s,J[0])}:{})}));return;}}if(D.type==="date"){const U=i,N=b.format??{},J=Object.keys(U).filter(P=>!Qt.includes(P)&&!Me(U[P],N[P]));if(J.length){const P=Object.fromEntries(Object.entries(D).filter(([T])=>!J.includes(T)));l.push(ae("format_invalid",{message:`A date format set here takes a pattern or a preset; it doesn't set ${J.join(", ")}.`,path:c,fix:`Leave out ${J.join(", ")}.`,allowed:Qt.filter(T=>T!=="type"),suggestedChange:Ct(n,s,P)}));return;}}const O=D.type==="date"&&g.surface==="detail_table"&&g.value==="date"?ro(a,D,(B=e.dataSource)==null?void 0:B.connectionType):void 0;if(O){l.push(ae("format_invalid",O.reason==="connection"?{message:`${te(e.title)} can't show ${s} that way: ${O.message}`,path:c,fix:"Write the pattern in uppercase letters (YYYY MM DD HH mm ss) with no dialect, for example 'DD MMM YYYY' or 'HH:mm'.",allowed:Qt.filter(U=>U!=="type")}:{message:`${te(e.title)} can't draw that format on ${s}: ${O.message}.`,path:c,fix:"Change the format to one the column can show.",allowed:ft(F)}));return;}const Y=Ks(g,D);if(!Y.ok){l.push(ae("format_invalid",{message:`${te(e.title)} can't draw that format on ${s}: ${Y.reason}.`,path:c,fix:"Change the format to one the column can show.",allowed:ft(F)}));return;}return w&&Me(w,D)?void 0:D;}function qr(e,t,a,s,i,n,l){var k,A;const c=i.polarity;if(c===void 0)return;const u=`${Be(n.path,s)}.polarity`,r=a.ref;if(!(t.settings.has("columns.polarity")&&(r.kind==="sqlKpiValue"||r.kind==="field"&&a.role==="measure"))){l.push(ae("setting_not_for_card",{message:a.role==="measure"||a.role==="value"?`${te(e.title)} shows no comparison, so ${s} has no favorable direction.`:`${s} on ${te(e.title)} isn't a measure, so it has no favorable direction.`,path:u,fix:"Leave out polarity.",suggestedChange:ot(n,s,i,"polarity")}));return;}const b=r.kind==="field"?(A=(k=e.config)==null?void 0:k.metricColumns)==null?void 0:A.find(I=>I.id===r.fieldId):void 0,w=r.kind==="sqlKpiValue"?Ws(e):void 0,g=r.kind==="sqlKpiValue"?(w==null?void 0:w.source)==="sql"&&w.polarity!==ys?w.polarity:void 0:b==null?void 0:b.comparisonPolarity,S=b==null?void 0:b.semanticComparisonPolarity;if(c===null)return g?null:void 0;if(S&&c!==S){l.push(ae("polarity_set_by_model",{message:`The model says ${s} is ${S.replace(/_/g," ")}; a card can't say otherwise.`,path:u,fix:"Change it in the model, or leave polarity out.",allowed:[S],suggestedChange:ot(n,s,i,"polarity")}));return;}return c===(S??g??ys)?void 0:c;}function Lr(e,t,a,s,i,n,l,c){if(i.pinned===void 0||i.pinned===((n==null?void 0:n.pinned)===!0))return;const u=t.pivoted&&a.role!=="dimension";if(!t.settings.has("columns.pinned")||a.columnId===void 0||u){c.push(ae("setting_not_for_card",{message:u?`${te(e.title)} has pivot columns, so only its row columns can be pinned; ${s} isn't one.`:`${te(e.title)} pins no columns; pinned columns are for tables and detail tables.`,path:`${Be(l.path,s)}.pinned`,suggestedChange:ot(l,s,i,"pinned")}));return;}return i.pinned;}function Mr(e,t,a,s,i,n,l,c,u){const r=i.display;if(r===void 0)return;const p=`${Be(c.path,s)}.display`;if(!t.settings.has("columns.display")||a.resultKey===void 0){u.push(ae("setting_not_for_card",{message:`${te(e.title)} has no Display as; it is for table and detail table columns.`,path:p,suggestedChange:ot(c,s,i,"display")}));return;}if(r===null)return l===void 0?void 0:null;if(!(l!==void 0&&Me(aa(r),l))){if(!lo(a.role)){u.push(ae("setting_not_for_card",{message:`Display as is for text columns; ${s} is a measure, which shows as a number.`,path:`${p}.as`,suggestedChange:ot(c,s,i,"display")}));return;}if(r.as==="monospace"&&r.lines!==void 0&&!co.includes(r.lines)){u.push(ae("value_invalid",{message:`${s} can show 2, 3 or 5 lines of monospace, or all of them.`,path:`${p}.lines`,fix:'Send lines: 2, 3, 5 or "all".'}));return;}if(r.as==="status"){const b=Object.entries(r.colors??{}).find(([,w])=>!Sn.includes(w));if(b||r.shape!==void 0&&r.shape!=="pill"&&r.shape!=="dot"){u.push(ae("value_invalid",{message:b?`${b[0]} in ${s} can be green, red, amber, blue or grey.`:`${s} shows its status as a pill or a dot.`,path:b?`${p}.colors`:`${p}.shape`,fix:b?"Send one of green, red, amber, blue or grey for each value.":'Send shape "pill" or "dot".'}));return;}}if(r.as==="link"){if(typeof r.address!="string"||!r.address.trim()){u.push(ae("invalid_change",{message:`A link in ${s} needs an address.`,path:`${p}.address`,fix:"Send an address, such as https://example.com/runs/{value}."}));return;}const b=A=>{var I;return(I=n.find(F=>F.resultKey===A||F.name===A))==null?void 0:I.resultKey;},w=r.label&&r.label!=="value"&&"column"in r.label?r.label.column:void 0,g=[...uo(r.address),...(w!==void 0?[w]:[])].find(A=>b(A)===void 0);if(g!==void 0){u.push(ae("column_not_found",{message:`${te(e.title)} has no column ${g} for the link in ${s}.`,path:w===g?`${p}.label.column`:`${p}.address`,allowed:n.flatMap(A=>A.resultKey!==void 0?[A.name]:[])}));return;}const S=r.address.replace(/{([^}]+)}/g,(A,I)=>I==="value"?A:`{${b(I)}}`),k={...r,address:S,...(w!==void 0?{label:{column:b(w)}}:{})};return Me(aa(k),l)?void 0:k;}return Me(aa(r),l)?void 0:r;}}function aa(e){return fo(ho(void 0,e));}function Vr(e,t,a,s,i,n,l,c){var p,b,w;if(i.hidden===void 0&&i.width===void 0)return{};const u=Be(l.path,s);if(!t.settings.has("columns.hidden")||a.resultKey===void 0){const g=t.pivoted&&a.role==="measure";return c.push(ae("setting_not_for_card",{message:g?`${s} on ${te(e.title)} has a column for each pivot value; hide or size them in the editor.`:`${te(e.title)} has no hidden columns or column widths; those are for tables.`,path:`${u}.${i.hidden!==void 0?"hidden":"width"}`,allowed:g?["label","format"]:["label","format"].filter(S=>t.settings.has(`columns.${S}`)),suggestedChange:Er(l,s,i)})),{};}const r={};if(i.hidden!==void 0&&i.hidden!==((n==null?void 0:n.hidden)===!0)&&(r.hidden=i.hidden),i.width!==void 0&&i.width!==((n==null?void 0:n.width)??null)){const{minSize:g,maxSize:S}=ao((w=(b=(p=e.preferences)==null?void 0:p.tablePrefs)==null?void 0:b.columnSettingsMap)==null?void 0:w[a.resultKey]);i.width!==null&&(!Number.isFinite(i.width)||i.width<g||i.width>S)?c.push(ae("value_invalid",{message:`${s} on ${te(e.title)} can be ${g} to ${S} pixels wide.`,path:`${u}.width`,fix:`Send a width from ${g} to ${S} pixels, or null for automatic.`})):r.width=i.width;}return r;}function Br(e,t,a){var A,I,F,y,V;const{columns:s={},...i}=t.settings??{},n=[],l=vi.some(D=>i[D]!==void 0),c=!!((I=(A=t.highlights)==null?void 0:A.add)!=null&&I.length||(y=(F=t.highlights)==null?void 0:F.remove)!=null&&y.length);if(!Object.keys(s).length&&!l&&!c)return{ok:!0,labels:[],settings:null,warnings:[]};const u=Xi(e);if(!u)return{ok:!1,problems:[ae("setting_not_for_card",{message:`${te(e.title)} takes no card settings through this tool.`,path:a.path})]};const r=Rr(e,u,i,a,n),p=Zi(e,u,a.sqlResultColumns),b=c?eo(e,u,p,t.highlights,a,n):void 0,w=$a(e),g=[],S=[];for(const[D,O]of Object.entries(s)){const Y=to(p,D,{path:Be(a.path,D),cardTitle:te(e.title)});if(!Y.ok){n.push(Y.problem);continue;}const R=Y.column;if(R.sqlName==="inferred"){n.push(ae("columns_unavailable",{message:`${te(e.title)}'s columns weren't read from its query, so ${D} can't be checked.`,path:Be(a.path,D),fix:"Check that the card runs and returns rows, then propose again."}));continue;}const E=Nr(e,u,R,D,O,a,n);E&&g.push(E);const B=Vr(e,u,R,D,O,w.columns[R.name],a,n),U=O.format!==void 0?Pr(e,u,R,D,O.format,a,n):void 0,N=qr(e,u,R,D,O,a,n),J=Lr(e,u,R,D,O,w.columns[R.name],a,n),P=Mr(e,u,R,D,O,p,(V=w.columns[R.name])==null?void 0:V.display,a,n),T={column:R.ref,...B,...(J!==void 0?{pinned:J}:{}),...(P!==void 0?{display:P}:{}),...(U!==void 0?{format:U}:{}),...(N!==void 0?{polarity:N}:{})};Object.keys(T).length>1&&S.push(T);}if(n.length)return{ok:!1,problems:n};const k={...r,...(S.length?{columns:S}:{}),...(b?{highlights:b}:{})};return{ok:!0,labels:g,settings:Object.keys(k).length?k:null,warnings:[]};}function jr(e){const t=gt(e),a=t&&t===gt("number")?rs.number:e==="temporal_bucket"||e==="date"?rs[e]:void 0;return a?`Send a stored format: ${a}.`:"Send the format in the stored shape the outline shows.";}const Kr=/* @__PURE__ */new Set([">",">=","<","<=","between"]),je=e=>JSON.stringify([...(e??[])].map(t=>JSON.stringify(t)).sort()),xs=e=>e.charAt(0).toLowerCase()+e.slice(1);function Wr(e){var a,s,i;const t=e.type==="matrixTable"?(s=(a=e.config)==null?void 0:a.matrix)==null?void 0:s.spec.filters:(i=e.config)==null?void 0:i.filters;return(t==null?void 0:t.conditions)??[];}function sa(e){var u,r,p;const t=Le(e,{sql:!0});if(!t.editable)return{readable:!1,editorOnly:!0,held:[],signatures:[]};if("sql"in t.query)return{readable:!1,held:[],signatures:[]};const a=t.query,s=a.datasetName,i=Wr(e),n=[],l=[];for(const b of a.filters??[]){const w=Re(b.field,s),g=b.operator==="="?"in":b.operator;l.push(`${w}|${g}|${b.scope??"row"}|${je(b.values)}`);const S=(u=i.find(I=>I.id===b.id))==null?void 0:u.field;if(!S||b.scope==="aggregate"||b.field==="__count"||jt(S.dataType))continue;const k=S.label||S.name,A=b.values??[];if((b.operator==="="||b.operator==="in")&&A.length)n.push({kind:"values",values:A,fieldKey:w,field:S,fieldLabel:k,valueWords:A.map(String).join(" or ")});else if(Kr.has(b.operator)&&A.length&&A.every(I=>typeof I=="number")){const I=xs(((r=mo(b.operator))==null?void 0:r.label)??b.operator);n.push({kind:"number",operator:b.operator,values:A,fieldKey:w,field:S,fieldLabel:k,valueWords:b.operator==="between"?`between ${A[0]} and ${A[1]}`:`${I} ${A[0]}`});}}let c;if(a.timeWindow&&a.dateField){const b=Re(a.dateField,s),w=a.timeWindow;c={key:b,window:w};const g=(p=i.find(k=>k.relativeMeta))==null?void 0:p.field,S=g&&di(w,{use:"filterDefault",columnHasTime:Us(g)}).ok;g&&S&&n.push({kind:"window",window:w,fieldKey:b,field:g,fieldLabel:g.label||g.name,valueWords:xs(Vn(w).label)});}return{readable:!0,held:n,signatures:l,...(c?{window:c}:{})};}function ia(e,t){return e.fieldKey!==t.fieldKey||e.kind!==t.kind?!1:e.kind==="values"&&t.kind==="values"?je(e.values)===je(t.values):e.kind==="number"&&t.kind==="number"?e.operator===t.operator&&JSON.stringify(e.values)===JSON.stringify(t.values):e.kind==="window"&&t.kind==="window"?Kt(e.window,t.window):!1;}function Ur(e){return e.kind==="window"?`${e.fieldKey}|window|${JSON.stringify(e.window)}`:e.kind==="number"?`${e.fieldKey}|${e.operator}|${JSON.stringify(e.values)}`:`${e.fieldKey}|values|${je(e.values)}`;}function Gr(e,t){const a=[...e.signatures].sort(),s=[...t.signatures].sort();return a.length!==s.length||a.some((i,n)=>i!==s[n])||!!e.window!=!!t.window?!1:!e.window||e.window.key===t.window.key&&Kt(e.window.window,t.window.window);}function ks(e,t){var a,s,i;return t.kind==="window"?!!e.defaultPeriod&&Kt(e.defaultPeriod,t.window):t.kind==="values"?(a=e.defaultValues)!=null&&a.length?je(e.defaultValues)===je(t.values):t.values.length===1&&((s=e.defaultCondition)==null?void 0:s.operator)==="="&&JSON.stringify(e.defaultCondition.values)===JSON.stringify(t.values):((i=e.defaultCondition)==null?void 0:i.operator)===t.operator&&JSON.stringify(e.defaultCondition.values??[])===JSON.stringify(t.values);}function Ts(e,t,a){var u;const s=Ve(e,t,void 0,a);if(!s)return;const i=s.editable?[s.defaultValues,s.defaultCondition,s.defaultPeriod]:[],n=(u=Ie(e).findFilterInput({inputId:t}))==null?void 0:u.input,l=new Map(we(e).map(r=>[r.cardId,r.card])),c=[...s.reaches].sort().map(r=>{const p=l.get(r);if(!n||!p)return r;const b=Ia(n,p),w=(b.status==="bound"||b.status==="automatic")&&b.target.kind==="field"?b.target.field:void 0;return`${r}:${b.status}:${w?Nt({name:w.name,source:w.source}):""}`;});return JSON.stringify([i,c]);}function Qr({before:e,after:t,operations:a,context:s,reachOptions:i}){var P;const n=(t.sheets??[]).filter(T=>!wa(T)),l=T=>{var M,Q;return((Q=(M=t.sheets)==null?void 0:M.find(K=>K.id===T))==null?void 0:Q.title)||"this sheet";},c=/* @__PURE__ */new Map();for(const T of we(t))c.set(T.cardId,{cardId:T.cardId,sheetId:T.sheetId,card:T.card});const u=new Map(we(e).map(T=>[T.cardId,T.card])),r=/* @__PURE__ */new Map(),p=T=>{let M=r.get(T);return M||(M=sa(c.get(T).card),r.set(T,M)),M;},b=/* @__PURE__ */new Map(),w=(T,M)=>{M!==void 0&&!b.has(T)&&b.set(T,M);},g=/* @__PURE__ */new Set();for(const T of a){const M=T.op==="card.add"?(P=T.frame.cards[0])==null?void 0:P.id:T.op==="card.update"?T.cardId:void 0;if(!M||!c.has(M))continue;const Q=u.get(M);(!Q||!Gr(sa(Q),p(M)))&&(g.add(M),w(M,T.changeIndex));}const S=/* @__PURE__ */new Map();for(const T of a){const M=T.op==="filter.add"?T.input.id:T.op==="filter.update"||T.op==="filter.bind"||T.op==="filter.exclude"?T.filterId:void 0;M&&!S.has(M)&&S.set(M,T.changeIndex);}for(const[T,M]of S){const Q=Ve(t,T,void 0,i);if(!(!Q||Ts(t,T,i)===Ts(e,T,i)))for(const K of Q.reaches)c.has(K)&&(g.add(K),w(K,M));}if(!g.size)return[];const k=Ra(t,void 0,i),A=Ie(t),I=(T,M,Q)=>{var be,_e,Ce,Se;const K=(be=A.findFilterInput({inputId:T.filterId}))==null?void 0:be.input,ne=(_e=c.get(Q))==null?void 0:_e.card;if(K&&ne){const Te=Ia(K,ne);if((Te.status==="bound"||Te.status==="automatic")&&Te.target.kind==="field"){const{name:ce,source:tt}=Te.target.field;return Nt({name:ce,source:tt})===M.fieldKey;}}if(T.editable)return Nt({name:T.field,source:{kind:"semantic",domainId:T.domainId,datasetName:T.datasetName}})===M.fieldKey;if(T.kind!=="field")return!1;const X=(Ce=A.findFilterInput({inputId:T.filterId}))==null?void 0:Ce.input.filter;if(!X)return!1;const ge={name:X.column??((Se=X.fieldMeta)==null?void 0:Se.name)??"",fieldMeta:X.fieldMeta};return Jn(ge,{name:M.field.name,qualifiedFieldName:M.field.qualifiedFieldName});},F=(T,M,Q)=>{var ge,be;let K=0;const ne=ri({field:M.field,dataSource:Q.dataSource,connectionId:((ge=Q.dataSource)==null?void 0:ge.connectionId)??Q.connectionId,connectionType:(be=Q.dataSource)==null?void 0:be.connectionType,scope:{kind:"sheets",sheetIds:[T]},dashboard:t,createId:()=>`shared-condition-reach-${++K}`,label:M.fieldLabel}),X=pt(t,[{op:"filter.add",input:ne}],s);return X.ok?Ve(X.dashboard,ne.id,void 0,i):void 0;},y=new Set(k.filter(T=>!T.editable&&T.kind==="global_date").flatMap(T=>T.reaches)),V=T=>y.has(T)?p(T).held.filter(M=>M.kind!=="window"):p(T).held,D=(T,M)=>{if(M.kind==="number")return!0;const Q=A.findFilterInput({inputId:T.filterId});if(!Q)return!1;const K={...Q.input.filter};M.kind==="window"?Object.assign(K,Tt(K,M.window)):K.defaultValues=M.values;const ne=pt(t,[{op:"filter.update",filterId:T.filterId,settings:{definition:K,values:{defaultChanged:!0,target:{}}}}],s);if(!ne.ok)return!1;const X=Ie(ne.dashboard).findFilterInput({inputId:T.filterId});if(!X)return!1;const ge=Bt({dashboard:ne.dashboard,target:{kind:"dashboardInput",input:X.input,scope:{}},calendar:s.calendar}).value;if(M.kind==="window"){const be=Fa(ge&&"relativeMeta"in ge?ge.relativeMeta:void 0);return!!be&&li(be,M.window);}return!!ge&&je(ge.values)===je(M.values);},O=T=>qe(T.map(M=>{var Q;return Ne((Q=c.get(M))==null?void 0:Q.card.title);})),Y=T=>T===1?"doesn't":"don't",R=(T,M)=>T.reaches.flatMap(Q=>{if(c.has(Q))return[];const K=xa(t,Q);return(K==null?void 0:K.kind)!=="variable"?[]:sa(K.card).held.some(X=>ia(X,M))?[]:[`the {{${K.variable.name}}} value`];}),E=/* @__PURE__ */new Map(),B=/* @__PURE__ */new Set(),U=[],N=/* @__PURE__ */new Set(),J=/* @__PURE__ */new Set();for(const T of n){const M=[...c.values()].filter(Q=>Q.sheetId===T.id).map(Q=>Q.cardId);for(const Q of M)if(g.has(Q))for(const K of V(Q)){const ne=`${T.id}|${K.fieldKey}`;if(J.has(ne))continue;const X=k.find(z=>z.reaches.some(se=>{var Qe;return((Qe=c.get(se))==null?void 0:Qe.sheetId)===T.id&&I(z,K,se);}));if(M.filter(z=>V(z).some(se=>ia(se,K))).length<2)continue;const be=`${ne}|${Ur(K)}|${Q}`;if(B.has(be))continue;B.add(be);const _e=`${ne}`;!X&&!E.has(_e)&&E.set(_e,F(T.id,K,c.get(Q).card));const Ce=X??E.get(_e);if(!Ce)continue;const Se=Ce.reaches.filter(z=>{var se;return((se=c.get(z))==null?void 0:se.sheetId)===T.id;}),Te=z=>!X||I(X,K,z),ce=Se.filter(z=>Te(z)&&V(z).some(se=>ia(se,K))),tt=Se.filter(z=>p(z).readable&&!ce.includes(z));if(ce.length<2||tt.length||!ce.includes(Q))continue;J.add(ne);for(const z of ce)N.add(`${z}|${K.fieldKey}`);const xe=K.fieldLabel,at=`${xe} ${K.kind==="window"?"in":"is"} ${K.valueWords}`,Fe=[...Se.filter(z=>!ce.includes(z)&&!p(z).editorOnly).map(z=>{var se;return Ne((se=c.get(z))==null?void 0:se.card.title);}),...R(Ce,K)],Ke=Se.filter(z=>p(z).editorOnly),We=`changes[${ce.map(z=>b.get(z)).find(z=>z!==void 0)??0}]`,vt={cards:ce.map(z=>{var se;return{cardId:z,title:((se=c.get(z))==null?void 0:se.card.title)??""};})};if(!X){const z=[...(Ce.relationshipPending??[]),...(Ce.sqlPending??[])].map(se=>se.cardId).filter(se=>{var Qe;return((Qe=c.get(se))==null?void 0:Qe.sheetId)===T.id;});U.push({code:"repeated_card_condition",message:[`"${at}" is on every card of ${T.title||"this sheet"} that a filter on ${xe} would reach: ${O(ce)}.`,...(Fe.length?[`A filter on ${xe} would also narrow ${qe(Fe)}, which ${Y(Fe.length)} have it today.`]:[]),...(z.length?[`It may also narrow ${O(z)}, as their SQL or the domain's relationships decide.`]:[]),...(Ke.length?[`It would also narrow ${O(Ke)}, which can only be changed in the editor: any condition of their own stays until changed there.`]:[])].join(" "),path:We,fix:`To let viewers change it in one place, add one filter on ${xe} with that default for ${T.title||"this sheet"} (filter.add with datasetName "${va(K.field)}" and field "${K.field.name}"), remove it from each card's query, keeping their other conditions (card.update), and exclude the cards that shouldn't change (filter.exclude). Keep it on the cards if each needs its own.`,details:vt});continue;}const ye=X.label,Ue=[...X.reaches.filter(z=>c.has(z)&&!ce.includes(z)).map(z=>{const se=c.get(z);return se.sheetId===T.id?Ne(se.card.title):`${Ne(se.card.title)} (${l(se.sheetId)})`;}),...R(X,K)],Ge=X.editable&&ks(X,K),rt=X.editable&&X.datePicker!=="range"?X.datePicker:void 0,dt=X.editable&&!Ge&&K.kind==="number"&&X.showAs==="list"?"range":X.editable&&!Ge&&K.kind==="values"&&X.showAs==="range"?"list":void 0,$t=X.editable?dt==="range"?`show the "${ye}" filter as a range with that default (filter.update with showAs "range" and defaultCondition), so viewers pick a condition instead of ticking values, and remove it from each card's query, keeping their other conditions (card.update).`:dt==="list"?`show the "${ye}" filter as a list with that default (filter.update with showAs "list" and defaultValues), so viewers tick values instead of picking a condition, and remove it from each card's query, keeping their other conditions (card.update).`:!Ge&&!D(X,K)?rt&&K.kind==="window"?`ask the user to make the "${ye}" filter a date range in the editor and give it that default (its ${rt==="day"?"date picker takes one day":"month picker takes one whole month"}); then remove it from each card's query, keeping their other conditions (card.update).`:`ask the user to set the "${ye}" filter's default in the editor (it wouldn't load with that default as it is); then remove it from each card's query, keeping their other conditions (card.update).`:Ge?`remove it from each card's query, keeping their other conditions (card.update): "${ye}" already has it as its default.`:`set the "${ye}" filter's default to it (filter.update) and remove it from each card's query, keeping their other conditions (card.update).`:`ask the user to set the "${ye}" filter's default in the editor; then remove it from each card's query, keeping their other conditions (card.update).`,Oe=[...(X.relationshipPending??[]),...(X.sqlPending??[])].filter(z=>!ce.includes(z.cardId)).map(z=>{const se=c.get(z.cardId);return se&&se.sheetId!==T.id?`${Ne(z.title)} (${l(se.sheetId)})`:Ne(z.title);}),lt=!Ge&&(Ue.length>0||Oe.length>0);U.push({code:"repeated_card_condition",message:[`"${at}" is on every card of ${T.title||"this sheet"} that the dashboard's "${ye}" filter reaches: ${O(ce)}.`,...(lt&&Ue.length?[`"${ye}" also reaches ${qe(Ue)}, which ${Y(Ue.length)} have it: a new default changes what ${Ue.length===1?"it shows":"they show"} by default.`]:[]),...(lt&&Oe.length?[`A new default may also change what ${qe(Oe)} ${Oe.length===1?"shows":"show"}, as ${Oe.length===1?"its":"their"} SQL or the domain's relationships decide.`]:[])].join(" "),path:We,fix:[`To let viewers change it in one place, ${$t}`,lt?`Keeping it on the cards is valid when the user didn't ask to change what the other cards show; excluding a card from "${ye}" (filter.exclude) stops it following the viewer's choice, so it doesn't keep the card as it was.`:"Keep it on the cards if each needs its own."].join(" "),details:vt});}}for(const T of g){const M=c.get(T);if(!(!M||!n.some(Q=>Q.id===M.sheetId))){for(const Q of V(T))if(!N.has(`${T}|${Q.fieldKey}`))for(const K of k){if(!K.editable||!K.reaches.includes(T)||!I(K,Q,T)||!ks(K,Q))continue;const ne=M.card.title||"Untitled",X=Q.kind==="window"?`window (${Q.valueWords})`:`condition (${Q.fieldLabel} is ${Q.valueWords})`;U.push({code:"card_condition_repeats_filter_default",message:`"${ne}" keeps its own ${X}, the default of the dashboard's "${K.label}" filter, so it won't follow the filter when a viewer changes it.`,path:`changes[${b.get(T)??0}]`,fix:`To follow the filter, remove it from the card's query (card.update): the card shows what the viewer picks. To keep both, change nothing: the card shows only what both its own condition and "${K.label}" allow, and nothing when they don't overlap. To make the card independent, exclude it from "${K.label}" (filter.exclude): it always shows ${Q.valueWords}.`,details:{cards:[{cardId:T,title:M.card.title??""}],filterId:K.filterId}});}}}return U;}function Hr(e,t,a,s,i,n,l=[]){var y,V,D,O,Y,R;const c=n??Le(e,{sql:!0,calculations:!1,calculatedFields:l});if(!c.editable)return[c.message];const u=c.query,r=t;if("sql"in t)return r.sql===u.sql&&r.connectionId===u.connectionId?[]:["the SQL"];const p=(s==null?void 0:s.source.kind)==="semantic"?Le({id:e.id,title:e.title,type:s.type,dataSource:s.source.dataSource,connectionId:s.source.connectionId,config:s.config},{sql:!0,calculations:!1,calculatedFields:l}):void 0;if(p&&!p.editable)return["the compiled query"];const b=p!=null&&p.editable?p.query:void 0,w=String(r.datasetName??""),g=[],S=E=>Re(E,w),k=(E,B,U)=>{const N=B??[],J=U??[];(N.length!==J.length||N.some((P,T)=>S(P)!==S(J[T])))&&g.push(E);};for(const E of["domainId","datasetName"])r[E]!==u[E]&&g.push(E);if(k("measures",r.measures,u.measures),k("columns",r.columns,u.columns),a||c.matrix){const E=U=>new Set(((U==null?void 0:U.columns)??[]).map(S)),B=(U,N)=>(U??[]).filter(J=>!E(N).has(S(J)));k("dimensions",B(r.dimensions,a),B(u.dimensions,c.matrix)),k("matrix.columns",a==null?void 0:a.columns,(y=c.matrix)==null?void 0:y.columns);}else k("dimensions",r.dimensions,u.dimensions);const A=r.timeWindow!==void 0&&!r.timeGrain,I=A&&u.timeWindow===void 0?void 0:A&&r.dateField===void 0?b==null?void 0:b.dateField:r.dateField;I!==void 0&&(u.dateField===void 0||S(I)!==S(u.dateField))&&g.push("dateField"),r.timeGrain!==void 0&&r.timeGrain!==u.timeGrain&&g.push("timeGrain");const F=(V=e.config)!=null&&V.matrix?e.config.matrix.spec.measures.map(E=>E.kind==="aggregate"?{aggregate:E.aggregate}:{}):((D=e.config)==null?void 0:D.metricColumns)??[];(r.measures??[]).forEach((E,B)=>{const U=E&&typeof E=="object"?E.aggregate:void 0;U&&bs(F[B]??{})!==U&&g.push(`the aggregate of measures[${B}]`);});for(const{key:E,label:B}of mt(t))po(e,E)!==B&&g.push(`the label "${B}"`);if(!i||i.aspects.includes("filters")){const E=r.filters??[];let B=u.filters??[];const U=r.timeWindow,N=u.timeWindow,J=(P,T)=>{const M=Q=>JSON.stringify((Q??[]).map(String));return S(P.field)===S(T.field)&&P.operator===T.operator&&(P.scope??"row")===(T.scope??"row")&&(typeof P.field=="object"?P.field.aggregate:void 0)===(typeof T.field=="object"?T.field.aggregate:void 0)&&(P.values===void 0||M(P.values)===M(T.values));};if(U&&!N){const P=((b==null?void 0:b.filters)??[]).filter(T=>!(b!=null&&b.timeWindow)&&!E.some(M=>J(M,T)));(!P.length||P.some(T=>!B.some(M=>J(T,M))))&&g.push("timeWindow"),B=B.filter(T=>!P.some(M=>J(M,T)));}else U?Kt(r.timeWindow,u.timeWindow)||g.push("timeWindow"):N&&g.push("timeWindow");(E.length!==B.length||E.some((P,T)=>!J(P,B[T])))&&g.push("filters");}if(r.orderBy!==void 0){const E=r.orderBy,B=(Y=(O=e.config)==null?void 0:O.sortByColumns)==null?void 0:Y[0],U=B&&Gs(e.config??{},B),N=E.field&&typeof E.field=="object"?E.field.aggregate:void 0;(!B||!U||B.direction!==E.direction||(B.comparisonPart??void 0)!==(E.part??void 0)||S(E.field)!==go(U.name,va(U))||N!==void 0&&bs(U)!==N)&&g.push("orderBy");}return r.limit!==void 0&&((R=e.config)==null?void 0:R.rowLimit)!==r.limit&&g.push("limit"),g;}function ma(e){const t=Sa({variables:[e]})[0];return t?Pe(t.card):void 0;}function Ii(e,t){const a=ma(e);return(a==null?void 0:a.kind)==="sql"?t.sql?{editable:!0,source:a}:{editable:!1,reason:"needs_sql_access",message:`${e.name} is written in SQL, which needs SQL access.`,source:a}:(a==null?void 0:a.kind)==="physical"?{editable:!1,reason:"table_source",message:`${e.name} reads a table or view, so it is changed in the editor.`,source:a}:{editable:!0,source:a};}const _i=e=>typeof e=="string"?{kind:e}:e;function Et(e,t){const a=e.variables??[];return a.find(s=>s.name===t)??a.find(s=>s.id===t);}function Yr(e,t,a,s){var l;const i=Et(e,t);i||s.problem(Ci(e,t,a));const n=Ii(i,{sql:!0});return((l=n.source)==null?void 0:l.kind)==="sql"&&s.need(a),n.editable||s.problem({code:"variable_not_editable",message:n.message,path:a,fix:"Tell the user to change it in the editor; removing it works.",details:{reason:n.reason}}),i;}function Ci(e,t,a){const s=(e.variables??[]).map(i=>i.name);return{code:"variable_unknown",message:`No variable named ${t} on this dashboard.`,path:a,fix:`Add one with variable.add${s.length?`, or use one of: ${s.join(", ")}`:""}.`,details:{available:s}};}function Si(e,t){return e.map(a=>({code:a.code==="nameTaken"||a.code==="nameReserved"?"variable_name_taken":a.code==="inUse"?"variable_in_use":"invalid_change",message:a.message,path:a.path?`${t}.${a.path.split(".")[0]}`:t,fix:a.fix,...(a.places?{details:{places:a.places}}:{})}));}async function Fs(e,t,a){var y,V;const{problem:s,need:i,services:n}=a,{path:l,query:c}=e,u=_i(e.get),r={id:e.id,name:e.name,...(e.label?{label:e.label}:{}),...(e.presentation?{presentation:e.presentation}:{}),...(e.emptyText?{emptyText:e.emptyText}:{}),sortDirection:"asc",sql:""};if("sql"in c)return i(`${l}.query`),u.kind!=="only"&&u.kind!=="first"&&s({code:"invalid_change",message:"A SQL variable takes the only row or the first row of its result.",path:`${l}.get`,fix:'Send get: "only" or "first", or write the aggregate or the list in the SQL itself.'}),F(Ot({...r,mode:"sql",connectionId:c.connectionId,sql:c.sql,get:u.kind},t));const p=await n.loadCardSource({domainId:c.domainId,datasetName:c.datasetName});p!=null&&p.dataSource||s({code:"variable_source_unreachable",message:`The dataset ${c.datasetName} isn't in the domain ${c.domainId} or in this project.`,path:`${l}.query.datasetName`,fix:"List the domain's datasets with semaphor_list_datasets and name one of them."});const b=p.fields;for(const D of Qs({...c,measures:c.measures??[]}))s({...D,path:`${l}.${D.path}`});const w=(D,O)=>{const Y=it(D),R=wo(D,c.datasetName);R.toLowerCase()!==c.datasetName.toLowerCase()&&s({code:"field_not_found",message:`A variable reads one dataset: "${Y}" names ${R}, not ${c.datasetName}.`,path:O,fix:`Name a field of ${c.datasetName}, or set datasetName to ${R} and read its field.`});const E=Vt(b,Y,c.datasetName);return E||s({code:"field_not_found",message:`"${Y}" isn't a field of ${c.datasetName}.`,path:O,fix:"Use one of details.available, or read semaphor_get_dataset_schema.",details:{available:b.slice(0,20).map(B=>B.name)}}),E;},g=c.measures??[],S=c.dimensions??[],k={...r,mode:"data",dataSource:p.dataSource,connectionId:p.connectionId,get:"only",...((y=c.filters)!=null&&y.length?{conditions:await zr(c,n,l,a.refuseAll)}:{})};if(u.kind==="aggregate"){(g.length!==1||S.length)&&s({code:"invalid_change",message:"An aggregate reads one measure and no dimension.",path:`${l}.query`,fix:`Send measures: [{ name, aggregate }] alone; for one field's value use get: "only", "first" or "list" with dimensions: [field].`}),c.orderBy&&s({code:"invalid_change",message:"An aggregate is one value, so it has no order.",path:`${l}.query.orderBy`,fix:"Leave out orderBy."});const D=w(g[0],`${l}.query.measures[0]`),O=typeof g[0]=="string"?void 0:g[0].aggregate,Y=zn(D).filter(B=>$s(B.value)),R=O??(Jt(D)?"calculation":Xn(D));if(!$s(R)||!Y.some(B=>B.value===R)){const B=Y.map(U=>U.value);s({code:"invalid_change",message:O?`${O} isn't an aggregate ${D.label||D.name} takes.`:`${D.label||D.name} needs its aggregate.`,path:`${l}.query.measures[0]`,fix:Jt(D)?`${D.label||D.name} aggregates itself: send it without an aggregate.`:`Send { name: "${D.name}", aggregate } with one of: ${B.join(", ")}.`,allowed:B});}const E=Jr(g[0],{...k,field:D,get:R},`${l}.query.measures[0].comparison`,s);return F(Ot({...k,field:D,get:R,...(E?{comparison:E}:{})},t));}(S.length!==1||g.length)&&s({code:"invalid_change",message:`The ${u.kind==="only"?"only value":u.kind==="first"?"first value":"list"} reads one dimension; a measure's one value is get: "aggregate".`,path:`${l}.query`,fix:"Send dimensions: [field] and no measures; order the first value or the list with orderBy."});const A=w(S[0],`${l}.query.dimensions[0]`);Jt(A)&&s({code:"invalid_change",message:`${A.label||A.name} is an aggregate calculation, so it has one value, not rows.`,path:`${l}.query.dimensions[0]`,fix:`Send get: "aggregate" with measures: ["${A.name}"].`}),u.kind==="only"&&c.orderBy&&s({code:"invalid_change",message:"The only value has no order: it shows when exactly one row matches.",path:`${l}.query.orderBy`,fix:'Leave out orderBy, or send get: "first" to take the first by this order.'});let I;if(c.orderBy&&u.kind!=="only"){const D=c.orderBy.field;typeof D!="string"&&D.aggregate&&s({code:"invalid_change",message:"The order names a field, not an aggregate: the first value is ordered by the latest (desc) or earliest (asc) of that field per value.",path:`${l}.query.orderBy.field`,fix:'Send orderBy: { field: "<field>", direction }.'}),I=w(D,`${l}.query.orderBy.field`);}return F(Ot({...k,field:A,get:u.kind,...(I?{sortField:I}:{}),sortDirection:((V=c.orderBy)==null?void 0:V.direction)??"asc",...(u.kind==="list"&&u.limit?{listLimit:u.limit}:{}),...(u.kind==="list"&&u.separator!==void 0?{listSeparator:u.separator}:{})},t));function F(D){const O={...D,name:e.name},Y=_a(O,t);return Y.length&&a.refuseAll(Si(Y,l)),O;}}function Jr(e,t,a,s){var n,l;const i=typeof e=="string"?void 0:e.comparison;if(!(!i||i.kind==="off"))return(i.kind==="inherit"||i.kind==="target"||i.kind==="metric")&&s({code:"invalid_change",message:i.kind==="inherit"?"A variable doesn't follow the Date filter's comparison; it names its own.":`A variable compares with an earlier period, not ${i.kind==="target"?"a target":"another metric"}.`,path:a,fix:"Send comparison: { kind: 'shift', unit: 'period' } (the period before) or { kind: 'shift', unit: 'year' } (last year); put a target in the words, or on a KPI card."}),er(t)||s({code:"invalid_change",message:`${((n=t.field)==null?void 0:n.label)||((l=t.field)==null?void 0:l.name)} with ${String(t.get)} isn't a number, so it has no comparison.`,path:a,fix:"Compare a count, or a numeric field's total, average, lowest or highest; leave comparison out here."}),Io(i);}async function zr(e,t,a,s){var n;const i=await t.compileCardQuery({query:{domainId:e.domainId,datasetName:e.datasetName,measures:["__count"],filters:e.filters},chartType:"table"});return i.ok?((n=i.part.config)==null?void 0:n.filters)??null:s(i.problems.map(l=>({...l,path:l.path?`${a}.query.${l.path}`:`${a}.query.filters`})));}function Xr(e,t,a,s,i){const n=_i(t),l=Zn(e);n.kind==="aggregate"&&e.get.kind!=="aggregate"&&s.problem({code:"invalid_change",message:`${e.name} reads a field's rows; an aggregate needs its measure.`,path:`${i}.get`,fix:'Send query with measures: [{ name, aggregate }] and get: "aggregate".'}),n.kind!=="aggregate"&&e.get.kind==="aggregate"&&s.problem({code:"invalid_change",message:`${e.name} is an aggregate; a value, the first or a list reads a dimension.`,path:`${i}.get`,fix:"Send query with dimensions: [field] and the get."}),l.mode==="sql"&&n.kind!=="only"&&n.kind!=="first"&&s.problem({code:"invalid_change",message:"A SQL variable takes the only row or the first row of its result.",path:`${i}.get`,fix:'Send get: "only" or "first", or write the list in the SQL itself.'});const c=Ot({...l,...(n.kind==="aggregate"?{}:{get:n.kind}),...(n.kind==="list"?{listLimit:n.limit??l.listLimit,listSeparator:n.separator??l.listSeparator}:{listLimit:void 0,listSeparator:void 0})},a);return{query:c.query,get:c.get};}function Zr(e,t){const a=ii(e).filter(({ref:l})=>l.source==="data"&&l.variableId===t),s=l=>{var c;return`"${((c=(e.sheets??[]).find(u=>u.id===l))==null?void 0:c.title)??l}"`;},i=we(e);return{words:[...new Set(a.map(({place:l,where:c})=>{var u;return c.kind==="card"?`the card "${((u=i.find(r=>r.cardId===c.cardId))==null?void 0:u.card.title)??c.cardId}"`:c.kind==="section"?`a text section of ${s(l.sheetId)}`:`the ${c.kind} of ${s(l.sheetId)}`;}))].join(", "),places:a};}function ed(e,t,a,s,i){const{problem:n}=i;(!wa(a)||!a.document)&&n({code:"invalid_change",message:`"${a.title??a.id}" is not a Document sheet.`,path:`${s}.sheetId`,fix:"Name a Document sheet; a grid sheet's words are its text cards (card.update with text)."}),e.text===void 0&&e.style===void 0&&n({code:"invalid_change",message:"This document.text.update has neither text nor style.",path:s,fix:"Send text (the words), style ({ size, align }) or both."});const l=a.document,c=e.target;let u,r;if("sectionId"in c){const k=l.sections.find(A=>A.id===c.sectionId);k||n({code:"invalid_change",message:`No section ${c.sectionId} on "${a.title}".`,path:`${s}.target.sectionId`,fix:"Use a section id from the outline's textSections."}),k.type!=="text"&&n({code:"invalid_change",message:`Section ${c.sectionId} is a ${k.type} section, not text.`,path:`${s}.target.sectionId`,fix:"Name one of the outline's textSections."}),u=k.content,r=k.style;}else{const{region:k,role:A}=c;gs[k].includes(A)||n({code:"invalid_change",message:`The ${k} has ${k==="header"?"a title and a metadata line":"a note and a page info line"}, not a ${A} line.`,path:`${s}.target.role`,fix:`Send role: ${gs[k].map(F=>`"${F}"`).join(" or ")}.`}),e.style!==void 0&&!bo(A)&&n({code:"invalid_change",message:`The footer's ${A==="pageInfo"?"page info":A} line has no size or alignment; only the header's title and metadata lines and text sections do.`,path:`${s}.style`,fix:"Leave style out for a footer line."});const I=l[k]?xn(l[k].blocks,A):void 0;u=(I==null?void 0:I.content)??[],r=I==null?void 0:I.style;}const p=e.style!==void 0?yo(e.style):void 0,b=!p||Object.entries(p).every(([k,A])=>(r==null?void 0:r[k])===A);let w;if(e.text!==void 0){const k={kind:"document",sheetId:a.id},A={catalog:ua({dashboard:t,place:k}),inputs:t.inputs,variables:t.variables},I=JSON.stringify(Pt(u,A));if(JSON.stringify(vo(e.text))!==I){const F=$o(e.text,u,{dashboard:t,place:k,path:`${s}.text`,links:!0});F.ok||i.refuseAll(F.problems);const y=F.content;JSON.stringify(Pt(y,A))!==I&&(w=y);}}const g={...(w!==void 0?{content:w}:{}),...(p!==void 0&&!b?{style:p}:{})};return{edit:"sectionId"in c?{type:"updateText",sectionId:c.sectionId,...g}:{type:"updateRegionText",region:c.region,role:c.role,...g},unchanged:w===void 0&&b};}const td={matrix:"A Matrix",pie:"A pie chart",detail_table:"A detail table",text:"A text card"};class Ae extends Error{}const As="A text card takes title, description and text.",oa=e=>e.cards.some(t=>{var a,s;return((a=t.customCardPreferences)==null?void 0:a.visualType)==="multiple"||!!((s=t.customCardPreferences)!=null&&s.dataInputCardIds);}),pa=e=>(e??"").trim().toLowerCase(),yt=Ao,ga={measures:Vo,records:Mo,sql:Lo},St={measures:"a measures query (measures, with optional dimensions)",records:"a records query (columns)",sql:"a SQL query"};function xi(e,t){return t.path.reduce((a,s)=>typeof s=="number"?`${a}[${s}]`:`${a}.${s}`,e);}const ad={max:Zo,what:"A proposal",fix:"Split the changes into several proposals."},sd=e=>e==="needs_sql_access"?"Ask for SQL access.":e==="empty"?"Send a complete query: domainId, datasetName and measures (or columns), or connectionId and sql.":e==="not_expressible"||e==="type_not_supported"?Xs:"Tell the user to change it in the editor.",id=/* @__PURE__ */new Set(["op","cardId","title","description","customVisual"]);function od(e,t){var i;if(t===((i=ze(e))==null?void 0:i.type))return!0;const a=At(t);if(a===e.type)return!0;const s=Ys(e,a,{catalogLoading:!0});return s.status==="unchanged"||s.status==="changed"&&s.queryKept;}function nd(e){const t=Object.fromEntries(Object.entries(e).filter(([,s])=>s!=null)),a=yt(t);return!!(a&&ga[a].safeParse(t).success);}const rd=["string","number","boolean","date","datetime"],dd=e=>rd.find(t=>t===e);function Rs(e){return!e.description||e.description.trim()===`Calculated field: ${(e.label??e.name).trim()}`;}async function ql(e,t,a){return ki(e,t,a,{limit:ad});}async function ki(e,t,a,s){var La,Ma,Va,Ba,ja,Ka,Wa,Ua,Ga,Qa,Ha,Ya,Ja,za,Xa,Za,es,ts,as;const i=[],n=[],l=[],c=[],u=/* @__PURE__ */new Set(),r=[],p=/* @__PURE__ */new Map(),b={calendar:a.calendar},w=a.relationshipReach?{relationshipReach:a.relationshipReach}:{};let g=e,S,k=0,A=0;const{limit:I}=s;if(t.length>I.max)return{ok:!1,problems:[{code:"too_many_changes",message:`${I.what} takes at most ${I.max} changes; this one has ${t.length}.`,path:"changes",fix:I.fix}]};const F=[];if(t.forEach((d,o)=>{const f=_o.safeParse(d);if(f.success){F.push(f.data);return;}for(const h of f.error.issues){const m=Bn(h.message);i.push({code:"invalid_change",message:(m==null?void 0:m.message)??h.message,path:xi(`changes[${o}]`,h),fix:(m==null?void 0:m.fix)??"Send the change in the shape the tool schema gives."});}}),i.length)return{ok:!1,problems:i};const y=d=>{throw i.push(d),new Ae();},V=d=>{a.capabilities.sql||y({code:"capability_required",message:"This change creates, reads or changes a SQL card or variable, which needs SQL access.",path:d,fix:"Use a measures or records query (a semantic dataset for a variable), or ask an administrator for SQL access."}),u.add("sql");},D=d=>d==="table_sheet_no_card"||d==="table_sheet_extra_card"||d==="table_sheet_card_type"||d==="table_sheet_layout",O=(d,o)=>{const f=pt(g,[d],b);if(f.ok)g=f.dashboard,l.push(d);else{const h=D(f.failedAt.code)?f.failedAt.code:"invalid_change";y({code:h,message:f.failedAt.message,path:o,...(f.failedAt.fix?{fix:f.failedAt.fix}:{})});}},Y=async d=>{var oe,de,re,ie,he,He;const{cardId:o,index:f,path:h}=d,{settings:m={},highlights:v}=d.request,$=m.columns&&Object.keys(m.columns).length?m.columns:void 0,_=Object.entries(m).some(([ee,ke])=>ee!=="columns"&&ke!==void 0),x=!!((oe=v==null?void 0:v.add)!=null&&oe.length);if(!$&&!_&&!x&&!((de=v==null?void 0:v.remove)!=null&&de.length))return null;const C=fe(g,o).card,q=Object.values($??{}).some(ee=>ee.label===null),j=Object.values($??{}).some(ee=>ee.format!==void 0&&ee.format!==null),L={};if(q&&!((re=C.sql)!=null&&re.trim()))for(const ee of _r(C)){const ke=await a.loadCardSource(ee);ke&&(L[Da(ee)]=ke.fields);}let G;if(j&&!((ie=C.sql)!=null&&ie.trim())){const ee=a.readModelFormats?await a.readModelFormats({card:C}):null;G=ee?{status:"read",formats:ee}:{status:"unavailable"};}const Z=!!((he=m.columnOrder)!=null&&he.length);let W;if(($||x||Z)&&(He=C.sql)!=null&&He.trim()&&C.type!=="kpi"){const ee=a.readSqlResultColumns?await a.readSqlResultColumns({cardId:o,dashboard:g}):null;ee||y({code:"columns_unavailable",message:$||Z?`"${C.title||"Untitled"}" couldn't be run to read its columns, so their names can't be checked.`:`"${C.title||"Untitled"}" couldn't be run to read its columns, so the highlight's column can't be checked.`,path:$?`${h}.columns`:Z?`${h}.columnOrder`:`${h}.column`,fix:"Check that the card runs and returns rows, then propose again."}),W=ee;}const H=Br(C,{settings:{...m,...($?{columns:$}:{columns:void 0})},...(v?{highlights:v}:{})},{path:h,cardRef:d.cardRef,catalogs:L,newId:a.newId,...(G?{modelFormats:G}:{}),...(W?{sqlResultColumns:W}:{})});if(!H.ok)throw i.push(...H.problems),new Ae();for(const ee of H.labels){const ke=d.queryLabels.find(Ee=>Dt(Ee.key,ee.key)&&Ee.label!==ee.label);ke&&y({code:"value_invalid",message:`Two labels are stated for one column of "${C.title||"Untitled"}": "${ke.label}" in the query and "${ee.label}" in columns.`,path:`${h}.columns`,fix:"State the label once."});}return n.push(...H.warnings),H.labels.length&&us(C,H.labels).changed.length&&O({op:"card.update",cardId:o,update:{kind:"relabel",labels:H.labels},changeIndex:f},`${h}.columns`),H.settings&&O({op:"card.update",cardId:o,update:{kind:"settings",settings:H.settings},changeIndex:f},$?`${h}.columns`:h),H.settings;},R=/* @__PURE__ */new Set(),E=(d,o,f)=>{var x;const h=fe(g,d);h||y({code:"card_not_editable",message:"Cards in Document sections are changed in the editor.",path:`${o}.cardId`,fix:"Tell the user to change it in the editor.",details:{reason:"document_section"}});const m=Le(h.card,{sql:!0,calculatedFields:g.calculatedFields??[]});((x=m.source)==null?void 0:x.kind)==="sql"&&V(`${o}.cardId`);const v=!m.editable&&(m.reason==="not_expressible"||m.reason==="type_not_supported"),$=v&&(f==null?void 0:f.queryFree)===!0;$&&R.add(d);const _=v&&(f==null?void 0:f.replacesQuery)===!0;return _&&n.push({code:"query_replaced",message:`"${h.card.title}" used ${m.detail??"a query the MCP can't read"}; this change replaces its query.`,path:`${o}.query`,details:{cardIds:[d]}}),!m.editable&&m.reason!=="empty"&&!$&&!_&&y({code:"card_not_editable",message:m.message,path:`${o}.cardId`,fix:sd(m.reason),details:{reason:m.reason,...(m.detail?{detail:m.detail}:{})}}),h.frame.visualId&&n.push({code:"detaches_linked_visual",message:`"${h.card.title}" will stop following its library visual and become local to this dashboard.`,path:o,details:{cardIds:[d]}}),{card:h.card,read:m};},B=/* @__PURE__ */new Map(),U=(d,o,f)=>{var m;const h=ti("metric",((m=d.config)==null?void 0:m.metricColumns)??[]);return o.map(({index:v,calculations:$})=>({...$,measure:h[v]??{role:"metric",field:"",ordinal:v},path:`${f}.query.measures[${v}]`}));},N=async d=>{const o=fe(g,d.cardId).card,f=U(o,d.stated,d.path),h=f.some($=>{var _;return((_=$.comparison)==null?void 0:_.kind)==="shift";}),m=h&&a.readComparisonDates?await a.readComparisonDates({card:o,dashboard:g}):Ds(o),v=ds({card:o,stated:f,context:{path:d.path,cardRef:d.cardRef,dates:m}});if(!v.ok)throw i.push(...v.problems),new Ae();return n.push(...v.warnings),h&&B.set(d.cardId,d.path),v.update?(O({op:"card.update",cardId:d.cardId,update:{kind:"calculations",calculations:v.update},changeIndex:d.index},`${d.path}.query`),!0):!1;},J=(d,o,f)=>{const h=d==null?void 0:d.orderBy,m=o.measures??[];h!=null&&h.part&&h.field&&!m.some(v=>it(v)===it(h.field))&&y({code:"invalid_change",message:`orderBy.part ranks a measure by its change, and "${it(h.field)}" isn't one of this query's measures.`,path:`${f}.query.orderBy.part`,fix:"Sort a measure of the query by its change, or leave out part."});},P=(d,o,f)=>{var C,q;const h=o==null?void 0:o.orderBy;if(!(h!=null&&h.part))return;const m=fe(g,d).card,v=(q=(C=m.config)==null?void 0:C.sortByColumns)==null?void 0:q.find(j=>j.comparisonPart);if(v&&pn(m,v))return;const $=v&&m.config?Gs(m.config,v):void 0,_=h.field,x=($==null?void 0:$.label)||($==null?void 0:$.name)||(typeof _=="string"?_:_==null?void 0:_.name)||"this field";y({code:"invalid_change",message:`"${x}" has no comparison to sort this card by: only a table's measure that compares with a period or a target ranks by its change.`,path:`${f}.query.orderBy.part`,fix:"Leave out part, or give the measure a comparison on a table card."});},T=d=>Object.fromEntries(["columns",...vi].map(o=>[o,d[o]])),M=d=>Object.entries(T(d)).filter(([,o])=>o!==void 0).map(([o])=>o),Q=d=>(i.push(...d.slice(0,-1)),y(d[d.length-1])),K=(d,o,f,h)=>{const{card:m}=o,v=[...(d.type?["type"]:[]),...(d.query?["query"]:[]),...(d.matrix?["matrix"]:[]),...M(d)];v.length&&y({code:"invalid_change",message:`"${m.title}" is a text card, so it takes no ${qe(v)}.`,path:h,fix:"Change a card to or from text in the editor, or add a new card and remove this one."});const $=ei(m,{inputs:g.inputs,variables:g.variables});$.editable||y({code:"card_not_editable",message:$.message,path:`${h}.cardId`,fix:"Tell the user to change it in the editor.",details:{reason:"text"}});const _=$.editable&&($.form==="legacy_html"||$.form==="legacy_runs");_&&d.description!==void 0&&d.text===void 0&&y({code:"invalid_change",message:`"${m.title}" keeps its words in its description, so a description change would replace them.`,path:`${h}.description`,fix:"Send the words in text with it: they are stored as rich text, and the description becomes the subtitle."}),c.push({ref:d.cardId,kind:"card",id:m.id,title:d.title??m.title??"",changeIndex:f});let x=!1,C=!1;if(d.text!==void 0){const L=fs({text:d.text,card:m,context:{dashboard:g,place:{kind:"sheet",sheetId:o.sheet.id,cardId:m.id}},path:`${h}.text`,storeAsRichText:_&&d.description!==void 0});L.ok||Q(L.problems),L.ok&&!L.unchanged&&(O({op:"card.update",cardId:m.id,update:{kind:"text",richContent:L.richContent,clearsLegacy:L.clearsLegacy},changeIndex:f},h),x=!0,C=L.clearsLegacy);}const q=d.title!==void 0&&d.title!==m.title,j=d.description!==void 0&&(_?C:(d.description??void 0)!==(m.description??void 0));(q||j)&&(O({op:"card.update",cardId:m.id,update:{kind:"rename",...(q?{title:d.title}:{}),...(j?{description:d.description}:{})},changeIndex:f},h),x=!0),x&&o.frame.visualId&&n.push({code:"detaches_linked_visual",message:`"${m.title}" will stop following its library visual and become local to this dashboard.`,path:h,details:{cardIds:[m.id]}});},ne=(d,o)=>{if(d.startsWith("$")){const f=p.get(d);return(!f||f.kind!=="card")&&y({code:"handle_unknown",message:`${d} isn't a card handle defined earlier in this list.`,path:o,fix:"Define the handle with an earlier card.add, or use the card id from the outline."}),f.id;}return we(g).some(f=>f.cardId===d)||y({code:"card_not_found",message:`There's no card ${d} on this dashboard.`,path:o,fix:"Read the outline again and use its card ids."}),d;},X=(d,o)=>{if(d.startsWith("$")){const h=p.get(d);return(!h||h.kind!=="filter")&&y({code:"handle_unknown",message:`${d} isn't a filter handle defined earlier in this list.`,path:o,fix:"Define the handle with an earlier filter.add, or use the filter id from the outline."}),h.id;}return(Array.isArray(g.inputs)?g.inputs:[]).some(h=>h.id===d&&h.kind==="filter")||y({code:"filter_not_found",message:`There's no filter ${d} on this dashboard.`,path:o,fix:"Read the outline again and use its filter ids."}),d;},ge=(d,o,f)=>{o!==void 0&&(o!=="range"&&o!=="list"&&y({code:"invalid_change",message:`showAs is "range" or "list", not "${o}".`,path:f,fix:'Send showAs: "range" or "list".'}),Ht(d.dataType)||y({code:"invalid_change",message:"Only number fields show as a range or a list.",path:f,fix:"Leave showAs out for this field."}),Object.assign(d,No(d,o)),d.defaultValues===void 0&&delete d.defaultValues);},be=(d,o,f)=>{if(o===void 0)return;hs(d)||y({code:"invalid_change",message:"defaultCondition is for a number filter shown as a range.",path:f,fix:"Send showAs: 'range' with it; for a list use defaultValues (null clears), for a date filter defaultPeriod."});let h=null;if(o){const m=Zs(o);m.ok?h=m.condition:y({code:"invalid_change",message:m.message,path:f,fix:"State the condition with its numbers."});}Object.assign(d,Po(h)),d.defaultValues===void 0&&delete d.defaultValues;},_e=(d,o,f)=>{o&&hs(d)&&y({code:"invalid_change",message:"A range filter's default is a condition, not values to tick.",path:f,fix:"Send defaultCondition, or showAs: 'list' with defaultValues."});},Ce=()=>we(g).flatMap(d=>d.kind==="frameCard"?[d.card]:[]),Se=(d,o,f)=>{var $,_;const h=d.startsWith("$")?($=p.get(d))==null?void 0:$.id:d;if(!h)return;const m=o===void 0?void 0:ne(o,`${f}.cardId`),v=ci(Ce(),h,m);return v.kind==="ambiguous"&&y({code:"invalid_change",message:`The filter ${d} is pinned on ${v.cards.length} cards: ${v.cards.map(x=>`"${x.title}"`).join(", ")}.`,path:`${f}.filterId`,fix:"Send cardId: the card whose pinnedFilters list the filter.",details:{cardIds:v.cards.map(x=>x.id)}}),v.kind==="none"&&m!==void 0&&y({code:"invalid_change",message:`"${((_=fe(g,m))==null?void 0:_.card.title)??m}" has no pinned filter ${d}.`,path:`${f}.filterId`,fix:"Use a filterId from that card's pinnedFilters; leave cardId out for a dashboard filter."}),v.kind==="found"?v:void 0;},Te=(d,o,f,h)=>{o.selection&&!d.dateSelectionMode&&(d.type=o.selection);const m=o.showAs??(h&&o.defaultValues&&Ht(d.dataType)?"list":void 0);ge(d,m,`${f}.showAs`),be(d,o.defaultCondition,`${f}.defaultCondition`),o.defaultValues&&_e(d,o.defaultValues,`${f}.defaultValues`),o.defaultValues===null?delete d.defaultValues:o.defaultValues&&(d.defaultValues=o.defaultValues),o.defaultPeriod!==void 0&&(Object.assign(d,Tt(d,o.defaultPeriod===null?void 0:ra(o.defaultPeriod,{dataType:d.dataType},`${f}.defaultPeriod`,y))),o.defaultPeriod===null&&delete d.defaultDateFilter);},ce=(d,o,f,h,m=!1)=>{O({op:"pinnedFilters.set",cardId:d,filters:[...o],...(m?{unpins:!0}:{}),changeIndex:f},h);},tt=(d,o)=>{const f=d.startsWith("$")?void 0:Et(g,d);return f?f.id:ne(d,o);},xe={services:a,problem:y,refuseAll:Q,need:V},at=()=>(g.sheets??[]).filter(d=>Ca(d)),Fe=()=>at().map(d=>({sheetId:d.id,title:d.title??""})),Ke=(d,o,f)=>{let h=d;if(d.startsWith("$")){const v=p.get(d);(!v||v.kind!=="sheet")&&y({code:"handle_unknown",message:`${d} isn't a sheet handle defined earlier in this list.`,path:o,fix:"Define the handle with an earlier sheet.add, or use the sheet id from the outline."}),h=v.id;}const m=(g.sheets??[]).find(v=>v.id===h);return m||y({code:"sheet_not_found",message:`There's no sheet ${h} on this dashboard.`,path:o,fix:"Read the outline again and use its sheet ids.",details:{sheets:Fe()}}),f.grid&&wa(m)&&y({code:"sheet_not_a_grid",message:`"${m.title}" is a Document sheet.`,path:o,fix:"Add the card to a grid sheet; Document sheets are changed in the editor.",details:{sheets:Fe()}}),f.cards&&Yt(m)&&y({code:"sheet_holds_one_table",message:`"${m.title}" is a Table sheet: it holds one table, so it takes no other card and has no grid.`,path:o,fix:"Add the card to a dashboard sheet, or change this sheet's table with card.update.",details:{sheets:Fe()}}),m;},We=(d,o)=>Ke(d,o,{grid:!0,cards:!0}),vt=(d,o)=>Ke(d,o,{grid:!0}),ye=(d,o)=>d.map((f,h)=>vt(f,`${o}.sheetIds[${h}]`).id),Wt=async(d,o)=>{(d.text!==void 0||!d.query)&&y({code:"invalid_change",message:d.text!==void 0?`A ${d.type} card takes a query, not text.`:`A ${d.type} card needs a query.`,path:d.text!==void 0?`${o}.text`:`${o}.query`,fix:"Send query; text is for type text."});const f=na(d.query),h=f.query,m=d.type;dt(m,h,d.matrix,o),J(h,h,o);const v=await se(m,h,d.matrix,o),$={...Fn({id:a.newId(),title:d.title,...(d.description?{description:d.description}:{})}),type:v.type},_=cs($,v);_.ok||y({code:"invalid_change",message:_.message,path:o});const x=_.ok?_.card:$;Oe(x,h,d.matrix,o,d.title,v);const C={id:a.newId(),cards:[x],activeCardId:x.id};return{card:x,frame:C,query:h,calculations:f.calculations};},Ue=(d,o,f)=>{var v;if(d.type!=="custom_visual")return d.customVisual!==void 0&&y({code:"invalid_change",message:`A ${String(d.type).replace(/_/g," ")} card takes no customVisual.`,path:`${f}.customVisual`,fix:"customVisual is for type custom_visual."}),o;((v=d.customVisual)==null?void 0:v.html)===void 0&&y({code:"invalid_change",message:"A custom_visual card needs its HTML in customVisual.html.",path:`${f}.customVisual.html`,fix:"Call semaphor_get_extension_contract for the contract and the card's fields, write the visual, and send its HTML."});const h=ws({card:o.card,stated:d.customVisual,path:`${f}.customVisual`});if(!h.ok)return y(h.problem);const m=h.card;return{...o,card:m,frame:{...o.frame,cards:o.frame.cards.map($=>$.id===m.id?m:$)}};},Ge=async d=>{var C,q,j,L,G,Z;const o=(C=fe(g,d.cardId))==null?void 0:C.card;if(!o)return;const f=`${d.path}.customVisual`;if(o.type!=="customVisual"){d.stated&&y({code:"invalid_change",message:`"${o.title}" isn't a custom visual, so it takes no customVisual.`,path:f,fix:"Change its type to custom_visual in the same change, with the HTML."});return;}const h=d.stated??{};if(d.retyped&&h.html===void 0&&!((q=o.customVisual)!=null&&q.draft)&&!((j=o.customVisual)!=null&&j.version)&&y({code:"invalid_change",message:`"${o.title}" needs its visual's HTML to become a custom visual.`,path:`${f}.html`,fix:"Send customVisual.html with the type change (semaphor_get_extension_contract has the contract)."}),!d.stated)return;const m=h.html===void 0&&(Object.keys(h.slots??{}).length||Object.keys(h.settings??{}).length),v=o.customVisual,$=m?fi(o)??(v!=null&&v.extensionId&&v.version?(await((L=a.readExtensionManifest)==null?void 0:L.call(a,{extensionId:v.extensionId,version:v.version})))??void 0:void 0):void 0,_=(G=o.sql)!=null&&G.trim()&&h.slots?await((Z=a.readSqlResultColumns)==null?void 0:Z.call(a,{cardId:o.id,dashboard:g})):void 0,x=ws({card:o,stated:h,manifest:$,sqlColumns:_,path:f});if(!x.ok)return y(x.problem);x.card!==o&&(O({op:"card.update",cardId:o.id,update:{kind:"customVisual",customVisual:x.card.customVisual,wording:x.wording},changeIndex:d.index},f),r.includes(o.id)||r.push(o.id));},rt=async(d,o,f,h,m)=>{r.push(d.card.id),await N({cardId:d.card.id,cardRef:f,stated:d.calculations,index:h,path:m}),P(d.card.id,d.query,m),await Y({cardId:d.card.id,cardRef:f,request:{settings:T(o)},queryLabels:"sql"in d.query?[]:mt(d.query),index:h,path:m});},dt=(d,o,f,h)=>{var _;for(const x of Qs(o,f))y({...x,path:`${h}.${x.path}`});const m=ct[d],v=yt(o),$=o.dateField;if($&&typeof $!="string"&&$.label&&!o.timeGrain&&y({code:"invalid_change",message:"A label names a column, and the date field is a column only when the card groups by it.",path:`${h}.query.dateField.label`,fix:"Send timeGrain to group by the date, or leave the label out."}),!m.forms.includes(v)){const x=Object.keys(ct).filter(C=>ct[C].forms.includes(v));y({code:"type_not_supported",message:`A ${d.replace(/_/g," ")} card takes ${m.forms.map(C=>St[C]).join(" or ")}, not ${St[v]}.`,path:`${h}.query`,fix:`Send ${m.forms.map(C=>St[C]).join(" or ")}, or use a type this query fits: ${x.join(", ")}.`});}if(v==="measures"){const x=o,C=x.measures.length;m.measures&&(C<m.measures.min||m.measures.max!==void 0&&C>m.measures.max)&&y({code:"type_not_supported",message:`A ${d.replace(/_/g," ")} card shows exactly ${m.measures.max} measure.`,path:`${h}.query.measures`,fix:"Send one measure, or use a table or chart for several."}),!m.dimensions&&(_=x.dimensions)!=null&&_.length&&y({code:"type_not_supported",message:`A ${d.replace(/_/g," ")} card shows one number, so it has no dimensions.`,path:`${h}.query.dimensions`,fix:"Remove the dimensions, or use a table or chart."}),d==="matrix"&&(x.orderBy||x.limit)&&y({code:"type_not_supported",message:"A Matrix's sorting and top N are set in the editor.",path:`${h}.query`,fix:"Leave out orderBy and limit for a Matrix."});}if(m.matrixColumns&&!f&&y({code:"type_not_supported",message:"A Matrix needs matrix.columns: the query fields that run across the top.",path:`${h}.matrix`,fix:"Send matrix: { columns: [...] } naming dimensions or the date field of the query (an empty list puts nothing across the top)."}),!m.matrixColumns&&f&&y({code:"type_not_supported",message:"matrix.columns is only for Matrix cards.",path:`${h}.matrix`,fix:'Leave out matrix, or use type "matrix".'}),f&&v==="measures"){const x=o,C=x.datasetName,q=[...(x.dimensions??[]),...(x.timeGrain&&x.dateField?[x.dateField]:[])];q.length&&f.columns.length>=q.length&&q.every(L=>f.columns.some(G=>Re(G,C)===Re(L,C)))&&y({code:"type_not_supported",message:"A Matrix needs at least one field down the side.",path:`${h}.matrix.columns`,fix:"Leave one dimension or the date field out of matrix.columns."});const j=new Set([...(x.dimensions??[]),...(x.dateField?[x.dateField]:[])].map(L=>Re(L,C)));f.columns.forEach((L,G)=>{j.has(Re(L,C))||y({code:"type_not_supported",message:`"${it(L)}" isn't one of the query's dimensions or its date field.`,path:`${h}.matrix.columns[${G}]`,fix:"Name dimensions or the date field of the query in matrix.columns."});});}},$t=(d,o)=>y({code:d.code==="query_not_kept"?"card_not_editable":"invalid_change",message:d.message,path:`${o}.query`,fix:d.code==="query_not_kept"?"Tell the user to make this change in the editor.":"Read the outline again and propose again.",details:{reason:"not_expressible",...("parts"in d?{parts:d.parts}:{})}}),Oe=(d,o,f,h,m,v,$)=>{const _=Le(d,{sql:!0,calculations:!1,calculatedFields:g.calculatedFields??[]});_.editable||y({code:"card_not_editable",message:_.message,path:`${h}.query`,fix:_.reason==="needs_sql_access"?"Ask for SQL access.":"Tell the user to change it in the editor.",details:{reason:_.reason,...(_.detail?{detail:_.detail}:{})}});const x=Hr(d,o,f,v,$,_,g.calculatedFields??[]);if(!x.length)return;const C=o;if(x.length===1&&x[0]==="dateField"&&C.dateField&&!C.timeGrain&&!C.timeWindow){y({code:"value_invalid",message:`A dateField on its own doesn't change "${m}": it needs timeGrain to group by the date (a KPI's Trend By) or a timeWindow to filter by it.`,path:`${h}.query.dateField`,fix:'Add timeGrain (for example "month") or a timeWindow, or leave out dateField.'});return;}const q=x.join(", ");y({code:"card_not_editable",message:$?`As changed, "${m}" wouldn't hold ${q} as asked, so make this change in the editor.`:`"${m}" can't be built holding ${q} as asked.`,path:`${h}.query`,fix:$?"Tell the user to make this change in the editor.":`Leave out ${q}; the rest of the card can be added.`,details:{reason:"not_expressible",detail:`doesn't hold: ${q}`}});},lt=async(d,o,f)=>{var q,j,L;const m=(g.calculatedFields??[]).find(G=>G.name.toLowerCase()===d.name.toLowerCase()),v=()=>y({code:"calculated_field_not_found",message:`This dashboard has no calculated field named ${d.name}.`,path:`${f}.name`,fix:"Read the outline's calculatedFields."});if(d.op==="calculation.remove"){m||v();const G=Rt(m),Z=Js(g,G);Ro(Z)&&y({code:"calculated_field_in_use",message:Do(m,Z),path:`${f}.name`,fix:"Remove it from those cards and filters earlier in this proposal, or keep it.",details:{usedBy:[...Z.cards.map(W=>W.cardId),...Z.filters.map(W=>W.filterId),...Z.fields.map(W=>W.name)]}}),O({op:"calculatedField.remove",key:G,changeIndex:o},f);return;}d.op==="calculation.update"&&!m&&v();const $=d.op==="calculation.update"?m:void 0,_=$?zs($):void 0,x=d.op==="calculation.add"||d.expression!==void 0||d.inputs!==void 0;d.op==="calculation.update"&&!x&&d.label===void 0&&d.description===void 0&&y({code:"invalid_change",message:`calculation.update on ${d.name} changes nothing.`,path:f,fix:"Send label, description or expression."}),d.op==="calculation.add"&&m&&y({code:"calculated_field_name_taken",message:`This dashboard already has a calculated field named ${m.name}.`,path:`${f}.name`,fix:"Name it differently, or change it with calculation.update."});let C;if(x){const G=d.domainId??((j=(q=$==null?void 0:$.calculatedFormula)==null?void 0:q.inputFields)==null?void 0:j.map(ie=>{var he;return((he=ie.source)==null?void 0:he.kind)==="semantic"?ie.source.domainId:void 0;}).find(Boolean)),Z=d.dataset??(_?(L=Object.values(_.inputs)[0])==null?void 0:L.dataset:void 0);(!G||!Z)&&y({code:"invalid_change",message:"A dashboard field names its domainId and dataset, as a card query does.",path:f,fix:"Send the dataset's domainId and dataset name."});const W=d.inputs??(d.op==="calculation.update"&&d.expression===void 0?_==null?void 0:_.inputs:void 0);Object.values(W??{}).some(ie=>"metric"in ie||ie.dataset.toLowerCase()!==Z.toLowerCase())&&y({code:"invalid_change",message:"A dashboard field reads one dataset; add it to the domain.",path:`${f}.inputs`,fix:"Write the formula over this dataset's fields, or propose calculation.add to the domain with domainId."});const oe=await a.loadCardSource({domainId:G,datasetName:Z});oe||y({code:"field_not_found",message:`The dataset "${Z}" isn't available.`,path:`${f}.dataset`,fix:"Find datasets with semaphor_list_datasets."}),d.op==="calculation.add"&&oe.fields.some(ie=>ie.name.toLowerCase()===d.name.toLowerCase())&&y({code:"calculated_field_name_taken",message:`${d.name} is a field of ${Z} already.`,path:`${f}.name`,fix:"Name it differently, or use the field."}),a.compileCalculation||y({code:"invalid_change",message:"Calculated fields can't be compiled here.",path:f,fix:"Change it in the editor."}),$&&!_&&d.expression===void 0&&y({code:"invalid_change",message:`${$.label||$.name} reads another calculated field, so its formula can't be changed in part.`,path:f,fix:"Send its whole formula: expression and inputs, over the dataset's fields."});const de=($==null?void 0:$.role)==="groupby"?dd($.dataType):void 0,re=await a.compileCalculation({domainId:G,dataset:Z,name:$?$.id:d.name,...(d.label??($==null?void 0:$.label)?{label:d.label??($==null?void 0:$.label)}:{}),...(typeof d.description=="string"?{description:d.description}:{}),expression:d.expression??_.expression,...(W?{inputs:W}:{}),...(d.op==="calculation.add"&&d.use?{use:d.use}:$?{use:$.role==="metric"?"aggregate":"group_or_filter"}:{}),...(d.op==="calculation.add"&&d.dataType?{dataType:d.dataType}:de?{dataType:de}:{})});if(!re.ok)throw i.push(...re.problems.map(ie=>({...ie,path:ie.path?`${f}.${ie.path}`:f}))),new Ae();$&&re.kind==="dimension"!=($.role==="groupby")&&y({code:"invalid_change",message:`This formula would turn ${$.label||$.name} from a ${$.role==="groupby"?"dimension into a measure":"measure into a dimension"}.`,path:`${f}.expression`,fix:"Add a new field instead."}),C=Oo({compiled:re.field,kind:re.kind,stage:re.stage,catalog:oe.fields,name:($==null?void 0:$.name)??d.name,label:d.label??($==null?void 0:$.label),description:d.description===null?void 0:d.description??($&&!Rs($)?$.description:void 0),id:($==null?void 0:$.id)??`${re.kind==="dimension"?"calc_dim_":"calc_"}${a.newId().replace(/-/g,"").slice(-10)}`});}else C={...$,...(d.label!==void 0?{label:d.label}:{}),...(d.label!==void 0&&d.description===void 0&&Rs($)?{description:`Calculated field: ${d.label}`}:{}),...(d.description!==void 0?{description:d.description??void 0}:{})};O($?{op:"calculatedField.update",key:Rt($),field:C,changeIndex:o}:{op:"calculatedField.add",field:C,changeIndex:o},f);},z=(d,o,f)=>{var x;const h=g.calculatedFields??[];if(!h.length)return[];const m=/* @__PURE__ */new Map(),v=C=>{const q=typeof C=="string"?C:C==null?void 0:C.name,j=typeof C=="object"&&C?C.datasetName:void 0;if(typeof q!="string"||j&&j.toLowerCase()!==d.datasetName.toLowerCase())return;const L=Xo(q,{domainId:d.domainId,datasetName:d.datasetName},h);return L&&m.set(Rt(L),L),L;},$=v(d.dateField);$&&y({code:"invalid_change",message:`${$.label||$.name} is one of this dashboard's calculated fields; a date grouping on one is set in the editor.`,path:`${f}.query.dateField`,fix:"Group by a date field of the dataset, or set it in the editor."});const _=(C,q)=>C==null?void 0:C.forEach((j,L)=>{var W,H;const G=v(j);!G||(o==="matrixTable"&&y({code:"calculated_field_not_for_matrix",message:`${G.label||G.name} is one of this dashboard's calculated fields; a Matrix takes the domain's.`,path:`${f}.query.${q}[${L}]`,fix:"Use a domain calculation, or build it in the editor."}),(typeof j=="object"?j.aggregate:void 0)&&((W=G.calculatedFormula)==null?void 0:W.computeStage)!=="row"&&G.role==="metric"&&y({code:"invalid_change",message:`${G.label||G.name} aggregates already.`,path:`${f}.query.${q}[${L}].aggregate`,fix:"Leave out its aggregate."}),q==="measures")||(G.role==="metric"&&((H=G.calculatedFormula)==null?void 0:H.computeStage)!=="row"?y({code:"invalid_change",message:`${G.label||G.name} is a measure over aggregates; it can't group the card or be one of its columns.`,path:`${f}.query.${q}[${L}]`,fix:"Name it in measures."}):jt(G.dataType)&&y({code:"invalid_change",message:`${G.label||G.name} is one of this dashboard's calculated fields; a date grouping on one is set in the editor.`,path:`${f}.query.${q}[${L}]`,fix:"Group by a date field of the dataset, or set it in the editor."}));});return"measures"in d?(_(d.measures,"measures"),_(d.dimensions,"dimensions")):_(d.columns,"columns"),v((x=d.orderBy)==null?void 0:x.field),(d.filters??[]).forEach(C=>v(C.field)),[...m.values()];},se=async(d,o,f,h,m=!1)=>{const v=At(d);if("sql"in o)return V(`${h}.query`),{type:v,source:{kind:"sql",connectionId:o.connectionId,sql:o.sql}};"measures"in o&&o.timeGrain===jo&&(Ko({cardType:v,configBacked:!0,shelf:"groupBy",dataType:"date"}).ok||y(d==="kpi"?{code:"type_not_supported",message:"A KPI's query can't group by a grain that follows the dashboard date.",path:`${h}.query.timeGrain`,fix:'For a trend that follows the dashboard date, send trend: true and trendGrain: "automatic" with no Trend By.'}:{code:"type_not_supported",message:`${td[d]??`A ${d.replace(/_/g," ")}`} can't group by a grain that follows the dashboard date.`,path:`${h}.query.timeGrain`,fix:'Use a bar, line or area chart or a table, or send a fixed timeGrain such as "month".'}));const $=v==="matrixTable"||v==="detailTable"?"table":v,_=z(o,v,h),x=await a.compileCardQuery({query:o,chartType:$,...(_.length?{dashboardFields:_}:{})});if(x.ok&&_.length&&(x.part={...x.part,config:Wo(x.part.config??{},_)}),!x.ok)throw i.push(...x.problems.map(L=>({...L,path:L.path?`${h}.query.${L.path}`:`${h}.query`}))),new Ae();n.push(...x.warnings.map(L=>({...L,path:L.path??`${h}.query`})));const C=!m&&"timeWindow"in o&&o.timeWindow?bd(x.part.config):void 0;C&&"timeWindow"in o&&o.timeWindow&&Fi(o.timeWindow,{use:"cardFilter",columnHasTime:Us(C)},`${h}.query.timeWindow`,y);let q={...x.part,type:v};const j=q.config??{};if(v==="detailTable"){const L=Uo(Go("table","detailTable",j))??{};q={...q,config:cd(L)};}return v==="matrixTable"&&(q=await Qe(q,j,o,f,h)),ud(q,mt(o));},Qe=async(d,o,f,h,m)=>{var j;const v=await a.loadCardSource({domainId:f.domainId,datasetName:f.datasetName});if(v||y({code:"field_not_found",message:`The dataset "${f.datasetName}" isn't available.`,path:`${m}.query.datasetName`,fix:"Find datasets with semaphor_list_datasets."}),d.source.kind!=="semantic")throw new Ae();const $={id:"scratch",title:"",type:"table",dataSource:d.source.dataSource,config:o},_=Ho($,"matrixTable",{catalog:v.fields,createId:a.newId}),x=_.status==="changed"?(j=_.card.config)==null?void 0:j.matrix:void 0;(_.status!=="changed"||_.leftOut.length||!x)&&y({code:"type_not_supported",message:_.status==="changed"&&_.leftOut.length?`These fields can't run in a Matrix: ${_.leftOut.join(", ")}.`:"This query can't be shown as a Matrix.",path:`${m}.query`,fix:"Use plain dataset fields for a Matrix, or use a table."});let C=x;const q=f.datasetName;for(const[L,G]of h.columns.entries()){const Z=[...C.spec.rows,...C.spec.columns].find(W=>Nt(W.field)===Re(G,q));Z||y({code:"type_not_supported",message:`"${it(G)}" isn't a level of this Matrix.`,path:`${m}.matrix.columns[${L}]`,fix:"Name dimensions or the date field of the query in matrix.columns."}),C=Yo(C,Jo(C.spec,Z.id,"columns")).config;}return{...d,config:{matrix:C}};},Ut=/* @__PURE__ */new Map(),wt=/* @__PURE__ */new Map(),Pa=/* @__PURE__ */new Map(),qa=(d,o,f)=>{o.defaultValues===void 0&&o.defaultPeriod===void 0&&o.defaultCondition===void 0||wt.set(`pinned:${d.cardId}:${d.filterId}`,{pinned:d,values:o.defaultValues,period:o.defaultPeriod,...(o.defaultCondition!==void 0?{condition:o.defaultCondition}:{}),changeIndex:f});};for(const[d,o]of F.entries()){const f=`changes[${d}]`;try{switch(o.op){case"card.add":{const h=o.position&&typeof o.position=="object"?(()=>{const C=ne(o.position.after,`${f}.position.after`),q=we(g).find(j=>j.cardId===C&&j.kind==="frameCard");return!q||q.kind!=="frameCard"?y({code:"card_not_found",message:`${o.position.after} isn't a card on a grid sheet.`,path:`${f}.position.after`,fix:"Use a cardId from semaphor_get_dashboard_details on the same sheet, or a handle from this proposal."}):(o.sheetId&&We(o.sheetId,`${f}.sheetId`).id!==q.sheetId&&y({code:"invalid_change",message:`position.after names a card on another sheet than ${o.sheetId}.`,path:`${f}.position.after`,fix:"Leave out sheetId, or name the card's sheet."}),{sheetId:q.sheetId,frameId:q.frameId});})():void 0,m=h?We(h.sheetId,`${f}.position.after`):o.sheetId?We(o.sheetId,`${f}.sheetId`):(()=>{const C=at();return C.length!==1&&y({code:C.length?"sheet_required":"sheet_not_a_grid",message:C.length?"This dashboard has several grid sheets; say which one gets the card.":"This dashboard has no grid sheet to add a card to.",path:`${f}.sheetId`,fix:C.length?"Send sheetId: one of details.sheets.":"Add a sheet with sheet.add earlier in this list.",details:{sheets:Fe()}}),C[0];})(),v=h?{after:h.frameId}:typeof o.position=="string"?o.position:void 0,$=v||o.width?{...(v?{position:v}:{}),...(o.width?{width:o.width}:{})}:void 0,_=C=>{const q=o.handle??`$card_${++k}`;return p.has(q)&&y({code:"invalid_change",message:`The handle ${q} is defined twice.`,path:`${f}.handle`,fix:"Give each new card, filter or sheet its own handle."}),p.set(q,{kind:"card",id:C.id,title:o.title}),c.push({ref:q,kind:"card",id:C.id,title:o.title,changeIndex:d}),q;};if(o.type==="text"){const C=[...(o.query?["query"]:[]),...(o.matrix?["matrix"]:[]),...M(o)];C.length&&y({code:"invalid_change",message:`A text card takes no ${qe(C)}.`,path:f,fix:As}),o.text===void 0&&y({code:"invalid_change",message:"A text card needs its words in text.",path:`${f}.text`,fix:As});const q=fs({text:o.text,context:{dashboard:g,place:{kind:"sheet",sheetId:m.id}},path:`${f}.text`});q.ok||Q(q.problems);const j=Tn({id:a.newId(),title:o.title,...(o.description?{description:o.description}:{}),richContent:q.ok&&!q.unchanged?q.richContent:{version:1,blocks:[{type:"paragraph",children:[]}]}});O({op:"card.add",sheetId:m.id,frame:{id:a.newId(),cards:[j],activeCardId:j.id},...($?{placement:$}:{}),changeIndex:d},f),_(j);break;}const x=Ue(o,await Wt(o,f),f);O({op:"card.add",sheetId:m.id,frame:x.frame,...($?{placement:$}:{}),changeIndex:d},f),await rt(x,o,_(x.card),d,f);break;}case"card.update":{const h=ne(o.cardId,`${f}.cardId`),m=fe(g,h);if((m==null?void 0:m.card.type)==="text"){K(o,m,d,f);break;}o.text!==void 0&&y({code:"invalid_change",message:`"${(m==null?void 0:m.card.title)??h}" isn't a text card, so it takes no text.`,path:`${f}.text`,fix:"Change its query; text is for text cards."});const v=(La=fe(g,h))==null?void 0:La.card,_=(o.type===void 0||v!==void 0&&od(v,o.type))&&Object.entries(o).every(([H,oe])=>id.has(H)||H==="type"||oe===void 0),x=o.query!==void 0&&nd(o.query),{card:C,read:q}=E(h,f,{queryFree:_,replacesQuery:x});o.query!==void 0&&o.type===void 0&&!ze(C)&&y({code:"type_not_supported",message:`"${C.title}" is a ${Ft(C.type).replace(/_/g," ")} card, whose query is replaced together with a type.`,path:`${f}.type`,fix:"Send type (bar, line, table, kpi, …) with the complete query."});const j=!q.editable&&(q.reason==="empty"||x);let L=!1,G=[];const Z=o.type&&o.type!==((Ma=ze(C))==null?void 0:Ma.type)?At(o.type):void 0;if(Z&&Z!==C.type&&!xo(Z)&&m&&Yt(m.sheet)&&y({code:"table_sheet_card_type",message:`"${C.title}" is the table of the Table sheet "${m.sheet.title}", so it stays a table, a detail table or a Matrix.`,path:`${f}.type`,fix:"Use type table, detail_table or matrix, or add the chart to a dashboard sheet with card.add."}),Z&&Z!==C.type){const H=q.editable?q.source:void 0,oe=ko(C,Z),de=oe&&H&&H.kind==="semantic"?(Va=await a.loadCardSource({domainId:H.domainId,datasetName:H.datasetName}))==null?void 0:Va.fields:oe&&j?[]:void 0,re=[],ie=Ys(C,Z,{...(de?{catalog:de}:{}),...(oe&&!de?{catalogLoading:!0}:{}),createId:()=>{const he=a.newId();return re.push(he),he;}});if(ie.status==="refused"&&y({code:"type_not_supported",message:"The card's dataset fields couldn't be loaded for a change to or from a Matrix.",path:`${f}.type`,fix:"Send a complete query with the type change."}),ie.status==="changed"){const he=Array.from(/* @__PURE__ */new Set([...ie.leftOut,...ie.droppedFields,...ie.droppedPreferences]));he.length&&n.push({code:"type_change_drops",message:`Changing "${C.title}" to ${o.type.replace(/_/g," ")} leaves out ${he.join(", ")}.`,path:`${f}.type`,details:{dropped:he}}),O({op:"card.update",cardId:h,update:{kind:"retype",type:Z,...(de?{catalog:de}:{}),newIds:re},changeIndex:d},`${f}.type`),L=!0;}}const W=o.query?na(o.query):void 0;if(o.query||o.matrix){const H=fe(g,h).card,oe=Le(H,{sql:!0,calculations:!1,calculatedFields:g.calculatedFields??[]}),de=oe.editable?na(oe.query).query:void 0,re=de,ie=pd(re,(W==null?void 0:W.query)??{},`${f}.query`,$e=>{if($e.code==="query_form_mismatch"&&W!=null&&W.calculations.length){const Ye=U(H,W.calculations,f),st=ds({card:H,stated:Ye,context:{path:f,cardRef:o.cardId,dates:Ds(H)}});if(!st.ok)throw i.push(...st.problems),new Ae();}return y($e);});G=md((W==null?void 0:W.query)??{},ie);const he=((Ba=ze(H))==null?void 0:Ba.type)??Ft(H.type),He=o.matrix??(oe.editable?oe.matrix:void 0);dt(he,ie,He,f),J(W==null?void 0:W.query,ie,f);const ee=oe.editable&&de?To(de,ie,oe.matrix,He):void 0,ke=!ee||ee.aspects.length>0,Ee=ee&&!("sql"in ie)?mt(ie).filter($e=>!ls(ee,$e.key.role)):[],ss=Fo(H,ee,Ee.map($e=>$e.key.role));ss&&$t(ss,f);let Gt=ie;if(ee&&!("sql"in ie)&&ie.orderBy&&!ee.aspects.includes("order")&&["metric","group_by","detail"].some($e=>ls(ee,$e))){const{orderBy:$e,...Ye}=ie;Gt=Ye;}let is;if(ke){const $e=!!(re&&Ti(re,(W==null?void 0:W.query)??{})&&ee!=null&&ee.keptWindow),Ye=await se(he,Gt,He,f,$e),st=Ye.type===At(he)?{...Ye,type:H.type}:Ye;is=st;const os=ee?{...st,change:ee}:st,Je=cs(H,os);if(Je.ok||$t(Je,f),Je.ok&&Je.droppedBindings.length&&n.push({code:"control_binding_dropped",message:`"${H.title}" loses the controls bound to the levels or measures this change removes; they stop changing this card.`,path:`${f}.query`,fix:"Keep those fields in the query, or tell the user the controls no longer apply to this card.",details:{controlIds:Je.droppedBindings}}),Je.ok)for(const It of Je.keptLabels)n.push({code:"label_kept_after_change",message:`"${H.title}" keeps the label "${It.label}" on ${It.field}, whose aggregate or time grain changed.`,path:`${f}.query`,fix:"State a new label on the field ref if the old one no longer fits.",details:{columns:[{label:It.label,field:It.field}]}});O({op:"card.update",cardId:h,update:{kind:"requery",query:os},changeIndex:d},`${f}.query`),L=!0;}Ee.length&&us(fe(g,h).card,Ee).changed.length&&O({op:"card.update",cardId:h,update:{kind:"relabel",labels:Ee},changeIndex:d},`${f}.query`),(ke||Ee.length)&&Oe(fe(g,h).card,Gt,He,f,H.title??"",is,ee);}(o.query||Z)&&(await N({cardId:h,cardRef:o.cardId,stated:(W==null?void 0:W.calculations)??[],index:d,path:f}))&&(L=!0),P(h,o.query,f),(o.title!==void 0||o.description!==void 0)&&O({op:"card.update",cardId:h,update:{kind:"rename",...(o.title!==void 0?{title:o.title}:{}),...(o.description!==void 0?{description:o.description}:{})},changeIndex:d},f),await Y({cardId:h,cardRef:o.cardId,request:{settings:T(o)},queryLabels:G,index:d,path:f}),await Ge({cardId:h,stated:o.customVisual,retyped:Z==="customVisual",index:d,path:f}),L&&!r.includes(h)&&r.push(h),c.push({ref:o.cardId,kind:"card",id:h,title:C.title??"",changeIndex:d});break;}case"card.remove":{const h=ne(o.cardId,`${f}.cardId`),m=fe(g,h);m||y({code:"card_not_editable",message:"Cards in Document sections are removed in the editor.",path:`${f}.cardId`,fix:"Tell the user to remove it in the editor.",details:{reason:"document_section"}}),oa(m.frame)&&m.frame.cards.length>1&&y({code:"card_not_editable",message:"This card is an input of a custom visual; remove it in the editor.",path:`${f}.cardId`,fix:"Tell the user to remove it in the editor.",details:{reason:"custom"}}),Yt(m.sheet)&&y({code:"table_sheet_no_card",message:`"${m.card.title}" is the table of the Table sheet "${m.sheet.title}", which can't be left without it.`,path:`${f}.cardId`,fix:"Remove the sheet instead, or change the sheet's table with card.update."}),m.frame.visualId&&m.frame.cards.length>1&&n.push({code:"detaches_linked_visual",message:`Removing "${m.card.title}" makes the rest of its tile local to this dashboard; it stops following its library visual.`,path:f,details:{cardIds:m.frame.cards.filter(v=>v.id!==h).map(v=>v.id)}}),O({op:"card.remove",cardId:h,changeIndex:d},f),c.push({ref:o.cardId,kind:"card",id:h,title:m.card.title??"",changeIndex:d});break;}case"filter.add":{const h=o.cardId;h!==void 0&&o.sheetIds&&y({code:"invalid_change",message:"A filter pinned on a card shows on that card, not on sheets.",path:`${f}.sheetIds`,fix:"Send cardId or sheetIds, not both."}),h===void 0&&o.position!==void 0&&y({code:"invalid_change",message:"position orders a card's pinned filters.",path:`${f}.position`,fix:"Send it with cardId, or leave it out."});const m=await a.loadCardSource({domainId:o.domainId,datasetName:o.datasetName});m||y({code:"field_not_found",message:`The dataset "${o.datasetName}" isn't available in this domain.`,path:`${f}.datasetName`,fix:"Find datasets with semaphor_list_datasets."});const v=Vt(m.fields,o.field,o.datasetName);if(v||y({code:"field_not_found",message:`"${o.field}" isn't a field of ${o.datasetName}.`,path:`${f}.field`,fix:"Use one of details.available, or read semaphor_get_dataset_schema.",details:{available:m.fields.slice(0,20).map(L=>L.name)}}),h!==void 0){const L=ne(h,`${f}.cardId`),G=fe(g,L);(!G||!Hn(G.card.type))&&y({code:"invalid_change",message:"This card doesn't take pinned filters.",path:`${f}.cardId`,fix:"Pin filters on a chart or a table."});const Z=(ja=G.card.dataSource)==null?void 0:ja.semanticDomainId;Z&&Z!==o.domainId&&y({code:"invalid_change",message:`"${G.card.title}" reads another domain; pin a field from ${Z}.`,path:`${f}.domainId`,fix:"Use the card's domainId from the outline."});const W=G.card.inlineFilters??[];W.some(re=>So(re,v))&&y({code:"invalid_change",message:`"${G.card.title}" already has a pinned filter on ${o.field}.`,path:`${f}.field`,fix:"Change that filter with filter.update and its id from the card's pinnedFilters."});const H=Yn({id:a.newId(),field:v,dataSource:G.card.dataSource??m.dataSource,connectionId:m.connectionId});H.title=o.label;const oe=vd(G.card,o.datasetName,H,a.relationshipReach);oe&&y({code:"invalid_change",message:oe,path:`${f}.datasetName`,fix:"Pin a field of the card's dataset, a dataset it joins, or one related to it (the outline's queries name them)."}),Te(H,o,f,!0);const de=[...W,H];ce(L,o.position===void 0?de:vs(de,H.id,o.position),d,f),qa({cardId:L,filterId:H.id},o,d),o.handle&&(p.has(o.handle)&&y({code:"invalid_change",message:`The handle ${o.handle} is defined twice.`,path:`${f}.handle`,fix:"Give each new card, filter or sheet its own handle."}),p.set(o.handle,{kind:"filter",id:H.id,title:o.label})),c.push({ref:o.handle??H.id,kind:"filter",id:H.id,title:o.label,changeIndex:d});break;}const $=o.sheetIds?ye(o.sheetIds,f):void 0,_=Os($),x=ri({field:v,dataSource:m.dataSource,connectionId:m.connectionId,connectionType:m.connectionType,scope:_,dashboard:g,createId:a.newId,label:o.label}),C={...x.filter};C.dateSelectionMode||(C.type=o.selection??"multiple");const q=o.showAs??(o.defaultValues&&Ht(C.dataType)?"list":void 0);ge(C,q,`${f}.showAs`),be(C,o.defaultCondition,`${f}.defaultCondition`),_e(C,o.defaultValues,`${f}.defaultValues`),o.defaultValues&&(C.defaultValues=o.defaultValues),o.defaultPeriod&&Object.assign(C,Tt(C,ra(o.defaultPeriod,v,`${f}.defaultPeriod`,y))),O({op:"filter.add",input:{...x,filter:C},changeIndex:d},f),Ut.set(x.id,{sheetIds:$??"all",changeIndex:d}),(o.defaultValues!==void 0||o.defaultPeriod!==void 0||o.defaultCondition!==void 0)&&wt.set(x.id,{values:o.defaultValues,period:o.defaultPeriod,...(o.defaultCondition!==void 0?{condition:o.defaultCondition}:{}),changeIndex:d});const j=o.handle;j&&(p.has(j)&&y({code:"invalid_change",message:`The handle ${j} is defined twice.`,path:`${f}.handle`,fix:"Give each new card, filter or sheet its own handle."}),p.set(j,{kind:"filter",id:x.id,title:o.label})),c.push({ref:j??x.id,kind:"filter",id:x.id,title:o.label,changeIndex:d});break;}case"filter.update":{const h=Se(o.filterId,o.cardId,f);if(h){o.sheetIds!==void 0&&y({code:"invalid_change",message:"A pinned filter shows on its card, not on sheets.",path:`${f}.sheetIds`,fix:"Leave sheetIds out for a pinned filter."});const W={...h.filter};o.label!==void 0&&(W.title=o.label),Te(W,o,f,!1);const H=(h.card.inlineFilters??[]).map(oe=>oe.id===W.id?W:oe);ce(h.card.id,o.position===void 0?H:vs(H,W.id,o.position),d,f),qa({cardId:h.card.id,filterId:W.id},o,d),c.push({ref:o.filterId,kind:"filter",id:W.id,title:W.title,changeIndex:d});break;}o.position!==void 0&&y({code:"invalid_change",message:"position orders a card's pinned filters.",path:`${f}.position`,fix:"Leave it out for a dashboard filter."});const m=X(o.filterId,`${f}.filterId`),v=Ve(g,m,void 0,w);v!=null&&v.editable||y({code:"filter_not_editable",message:v&&!v.editable?v.notEditable.message:"This filter can't be changed through the MCP.",path:`${f}.filterId`,fix:"Tell the user to change it in the editor; removing or excluding it works."});const $=(g.inputs??[]).find(W=>W.id===m);if(($==null?void 0:$.kind)!=="filter"||!$.filter)throw new Ae();const _={...$.filter};let x=!1;o.selection&&(_.type=o.selection);const C=ca(_),q=JSON.stringify([_.operation,_.defaultValues??null]);ge(_,o.showAs,`${f}.showAs`),o.defaultCondition!==void 0&&be(_,o.defaultCondition,`${f}.defaultCondition`),o.defaultValues&&_e(_,o.defaultValues,`${f}.defaultValues`);const j=ca(_)!==C;if(JSON.stringify([_.operation,_.defaultValues??null])!==q&&(x=!0),o.defaultValues!==void 0&&(x=!0,o.defaultValues===null?delete _.defaultValues:_.defaultValues=o.defaultValues),o.defaultPeriod!==void 0){x=!0;const W=Tt(_,o.defaultPeriod===null?void 0:ra(o.defaultPeriod,{dataType:_.dataType},`${f}.defaultPeriod`,y));Object.assign(_,W),o.defaultPeriod===null&&delete _.defaultDateFilter;}let L;if(o.defaultComparison!==void 0){const W=Co.nullable().safeParse(o.defaultComparison);W.success||y({code:"invalid_change",message:`defaultComparison: ${W.error.issues.map(oe=>[...oe.path,oe.message].join(" ")).join("; ")}.`,path:`${f}.defaultComparison`,fix:'Send { kind: "shift", unit: "period" | "day" | "week" | "month" | "quarter" | "year", offset?: n, matchWeekdays?: true with "year" }, or null for none.'}),Nn($)||y({code:"invalid_change",message:"defaultComparison is for a dashboard date filter that compares.",path:`${f}.defaultComparison`,fix:"Leave it out; a measure compares through its own comparison on card.update."});const H=o.defaultComparison===null?null:Ta(W.data);L={defaultComparisonSelection:H?{mode:"period",spec:H}:null};}const G=o.sheetIds===void 0?void 0:o.sheetIds?ye(o.sheetIds,f):"all",Z={...(o.label!==void 0?{label:o.label}:{}),...(o.selection!==void 0||x||j?{definition:_}:{}),...(G?{scope:vn($.scope,Os(G==="all"?void 0:G),new Set([...ka(g).values()].filter(W=>W.sheetKind==="document").map(W=>W.sheetId)))}:{}),...(x||L?{values:{...(x?{defaultChanged:!0}:{}),...L,target:{}}}:{})};O({op:"filter.update",filterId:m,settings:Z,changeIndex:d},f),G&&Ut.set(m,{sheetIds:G,changeIndex:d}),(x||L)&&Pa.set(m,{changeIndex:d,statedComparison:!!(L!=null&&L.defaultComparisonSelection)}),x&&wt.set(m,{values:o.defaultValues,period:o.defaultPeriod,...(o.defaultCondition!==void 0?{condition:o.defaultCondition}:{}),changeIndex:d}),c.push({ref:o.filterId,kind:"filter",id:m,title:$.label,changeIndex:d});break;}case"filter.remove":{const h=Se(o.filterId,o.cardId,f);if(h){ce(h.card.id,(h.card.inlineFilters??[]).filter($=>$.id!==h.filter.id),d,f,!0),c.push({ref:o.filterId,kind:"filter",id:h.filter.id,title:h.filter.title,changeIndex:d});break;}const m=X(o.filterId,`${f}.filterId`),v=((Ka=(g.inputs??[]).find($=>$.id===m))==null?void 0:Ka.label)??"";O({op:"filter.remove",filterId:m,changeIndex:d},f),c.push({ref:o.filterId,kind:"filter",id:m,title:v,changeIndex:d});break;}case"filter.bind":{const h=X(o.filterId,`${f}.filterId`),m=Ve(g,h,void 0,w);m!=null&&m.editable||y({code:"filter_not_editable",message:m&&!m.editable?m.notEditable.message:"This filter can't be changed through the MCP.",path:`${f}.filterId`,fix:"Tell the user to change it in the editor; removing or excluding it works."});const v=tt(o.cardId,`${f}.cardId`),$=xa(g,v).card,_=Ie(g).findFilterInput({inputId:h}),x=_&&Xe(_.input,$,w).reach==="relationshipApplied",C=await yd($,o.field,a,`${f}.field`,y,x?m.label:void 0);O({op:"filter.bind",filterId:h,cardId:v,binding:{kind:"bound",cardId:v,bindingId:a.newId(),target:C},changeIndex:d},f),c.push({ref:o.filterId,kind:"filter",id:h,title:m.label,changeIndex:d});break;}case"layout.arrange":{const h=o.sheetId?We(o.sheetId,`${f}.sheetId`):(()=>{const m=at();return m.length!==1&&y({code:m.length?"sheet_required":"sheet_not_a_grid",message:m.length?"This dashboard has several grid sheets; say which one to arrange.":"This dashboard has no grid sheet to arrange.",path:`${f}.sheetId`,fix:m.length?"Send sheetId: one of details.sheets.":"Add a sheet with sheet.add earlier in this list.",details:{sheets:Fe()}}),m[0];})();O({op:"layout.arrange",sheetId:h.id,...(o.keepOrder?{keepOrder:!0}:{}),changeIndex:d},f);break;}case"layout.tabs":{const h=o.cardIds.map((j,L)=>ne(j,`${f}.cardIds[${L}]`)),m=(j,L,G=`${f}.cardIds`)=>y({code:"layout_invalid",message:j,path:G,fix:L});new Set(h).size!==h.length&&m("Each card is named once in tabs.","Name two or more different cards, each once.");const v=h.map((j,L)=>fe(g,j)??m("A Document section's card can't be a tab.","Name cards on a grid sheet.",`${f}.cardIds[${L}]`)),$=v[0].sheet;v.some(j=>j.sheet.id!==$.id)&&m("Tabs are cards on one sheet.","Name cards on one sheet; a card moves to another sheet in the editor."),v.some(j=>oa(j.frame)&&j.frame.cards.length>1)&&m("A custom visual's inputs stay in its spot.","Name cards that aren't a custom visual's inputs, or arrange them in the editor.");const _=v[0].frame,x=v[0].card;c.push({ref:o.cardIds[0],kind:"card",id:x.id,title:x.title??"",changeIndex:d});const C=Hs(_);if(h.every((j,L)=>C[L]===j))break;const q=[...new Map(v.map(j=>[j.frame.id,j.frame])).values()].filter(j=>j.visualId);q.length&&n.push({code:"detaches_linked_visual",message:"Moving these cards makes the tiles they leave or join local to this dashboard; they stop following their library visuals.",path:f,details:{cardIds:q.flatMap(j=>j.cards.map(L=>L.id))}}),x.type==="kpi"&&v.slice(1).some(j=>j.card.type==="text")&&n.push({code:"tabs_show_as_kpi_info",message:`A text card in ${Ne(x.title)}'s spot shows as the KPI's info, not as a tab.`,path:f,fix:"Put another card first if the text should be a tab of its own."}),O({op:"layout.tabs",sheetId:$.id,cardIds:h,changeIndex:d},f);break;}case"layout.untab":{const h=ne(o.cardId,`${f}.cardId`),m=fe(g,h);if(m||y({code:"layout_invalid",message:"A Document section's card has no spot of its own.",path:`${f}.cardId`,fix:"Name a card on a grid sheet."}),oa(m.frame)&&m.frame.cards.length>1&&y({code:"layout_invalid",message:"A custom visual's inputs stay in its spot.",path:`${f}.cardId`,fix:"Arrange a custom visual in the editor."}),c.push({ref:o.cardId,kind:"card",id:h,title:m.card.title??"",changeIndex:d}),m.frame.cards.length<2)break;m.frame.visualId&&n.push({code:"detaches_linked_visual",message:`Taking "${m.card.title}" out of its tabs makes them local to this dashboard; they stop following their library visual.`,path:f,details:{cardIds:m.frame.cards.map(v=>v.id)}}),O({op:"layout.untab",cardId:h,newFrameId:a.newId(),changeIndex:d},f);break;}case"filter.exclude":{const h=X(o.filterId,`${f}.filterId`),m=tt(o.cardId,`${f}.cardId`),v=((Wa=(g.inputs??[]).find($=>$.id===h))==null?void 0:Wa.label)??"";O({op:"filter.exclude",filterId:h,cardId:m,changeIndex:d},f),c.push({ref:o.filterId,kind:"filter",id:h,title:v,changeIndex:d});break;}case"highlight.add":case"highlight.remove":{const h=ne(o.cardId,`${f}.cardId`),{card:m}=E(h,f),{op:v,cardId:$,..._}=o,x=await Y({cardId:h,cardRef:o.cardId,request:{highlights:o.op==="highlight.add"?{add:[_]}:{remove:[o.ruleId]}},queryLabels:[],index:d,path:f}),C=(Ga=(Ua=x==null?void 0:x.highlights)==null?void 0:Ua.add)==null?void 0:Ga[0];c.push({ref:o.cardId,kind:"card",id:h,title:m.title??"",changeIndex:d,...(C?{ruleId:C.id}:{})});break;}case"sheet.add":{const h=a.newId();o.kind!=="table"&&o.card&&y({code:"invalid_change",message:"Only a Table sheet is added with a card.",path:`${f}.card`,fix:'Send kind "table", or add the card with card.add after the sheet.'}),o.kind==="table"&&!o.card&&y({code:"table_sheet_no_card",message:"A Table sheet is added with its table.",path:`${f}.card`,fix:"Send card: the table, as card.add takes it (type table, detail_table or matrix)."});const m=o.kind==="table"?o.card:void 0,v=m?await Wt(m,`${f}.card`):void 0;O({op:"sheet.add",sheet:{id:h,title:o.title,...(v?{kind:"table"}:{})},...(v?{frame:v.frame}:{}),changeIndex:d},f);const $=o.handle??`$sheet_${++A}`;if(p.has($)&&y({code:"invalid_change",message:`The handle ${$} is defined twice.`,path:`${f}.handle`,fix:"Give each new card, filter or sheet its own handle."}),p.set($,{kind:"sheet",id:h,title:o.title}),c.push({ref:$,kind:"sheet",id:h,title:o.title,changeIndex:d}),v&&m){const _=m.handle??`$card_${++k}`;p.has(_)&&y({code:"invalid_change",message:`The handle ${_} is defined twice.`,path:`${f}.card.handle`,fix:"Give each new card, filter or sheet its own handle."}),p.set(_,{kind:"card",id:v.card.id,title:m.title}),c.push({ref:_,kind:"card",id:v.card.id,title:m.title,changeIndex:d}),await rt(v,m,_,d,`${f}.card`);}break;}case"sheet.update":{const h=Ke(o.sheetId,`${f}.sheetId`,{grid:!1});(h.title??"")!==o.title&&O({op:"sheet.update",sheetId:h.id,title:o.title,changeIndex:d},f),c.push({ref:o.sheetId,kind:"sheet",id:h.id,title:o.title,changeIndex:d});break;}case"dashboard.update":{const h=o.title!==void 0&&o.title!==g.title?o.title:void 0,m=o.description===null?g.description?null:void 0:o.description!==g.description?o.description:void 0;(h!==void 0||m!==void 0)&&O({op:"dashboard.update",...(h!==void 0?{title:h}:{}),...(m!==void 0?{description:m}:{}),changeIndex:d},f);break;}case"dashboard.style":{const{op:h,...m}=o;S??(S=a.readOrganizationAppearance?a.readOrganizationAppearance():Promise.resolve(null));const{style:v,organizationAppearance:$}=ai(g,await S),_=kn({style:v,edit:m,layers:{organizationAppearance:$}});if(_.ok)_.sentences.length&&O({op:"dashboard.style",style:_.style,sentences:_.sentences,changeIndex:d},f);else{const{refusal:x}=_;y({code:x.code,message:x.message,path:x.field==="edit"?f:`${f}.${x.field}`,fix:x.fix});}break;}case"variable.add":{Et(g,o.name)&&y({code:"variable_name_taken",message:`A variable named ${o.name} is already on this dashboard.`,path:`${f}.name`,fix:"Choose another name, or change it with variable.update."});const h=await Fs({id:a.newId(),name:o.name,...(o.label?{label:o.label}:{}),query:o.query,get:o.get,...(o.presentation?{presentation:o.presentation}:{}),...(o.emptyText?{emptyText:o.emptyText}:{}),path:f},g,xe);O({op:"variable.add",variable:h,changeIndex:d},f),c.push({ref:o.name,kind:"variable",id:h.id,title:h.name,changeIndex:d});break;}case"variable.update":{const h=Yr(g,o.name,`${f}.name`,xe),m=o.rename??h.name,v={...(o.rename!==void 0?{name:o.rename}:{}),...(o.label!==void 0?{label:o.label}:{}),...(o.presentation!==void 0?{presentation:o.presentation}:{}),...(o.emptyText!==void 0?{emptyText:o.emptyText}:{})},$={...g,variables:(g.variables??[]).filter(C=>C.id!==h.id)};if(o.query){const C=await Fs({id:h.id,name:m,label:o.label===null?void 0:o.label??h.label,query:o.query,get:o.get??h.get,presentation:o.presentation===null?void 0:o.presentation??h.presentation,emptyText:o.emptyText===null?void 0:o.emptyText??h.emptyText,path:f},$,xe);v.query=C.query,v.get=C.get;}else if(o.get!==void 0){const C=Xr(h,o.get,$,xe,f);v.query=C.query,v.get=C.get;}Object.keys(v).length||y({code:"invalid_change",message:`variable.update on ${h.name} changes nothing.`,path:f,fix:"Send rename, label, query, get, presentation or emptyText."});const _={...h,...Object.fromEntries(Object.entries(v).map(([C,q])=>[C,q??void 0])),id:h.id},x=_a(_,{...$,variables:[...$.variables,_]});x.length&&Q(Si(x,f)),O({op:"variable.update",variableId:h.id,patch:v,changeIndex:d},f),c.push({ref:o.name,kind:"variable",id:h.id,title:m,changeIndex:d});break;}case"variable.remove":{const h=Et(g,o.name);h||y(Ci(g,o.name,`${f}.name`));const m=h,v=Zr(g,m.id);v.places.length&&y({code:"variable_in_use",message:`${m.name} is shown in ${v.words}.`,path:`${f}.name`,fix:"Remove its chips first (card.update with text, or document.text.update), or ask the user whether the chips should read as missing.",details:{places:v.places}}),O({op:"variable.remove",variableId:m.id,changeIndex:d},f),c.push({ref:o.name,kind:"variable",id:m.id,title:m.name,changeIndex:d});break;}case"document.text.update":{const h=Ke(o.sheetId,`${f}.sheetId`,{grid:!1}),{edit:m,unchanged:v}=ed(o,g,h,f,xe);if(c.push({ref:o.sheetId,kind:"sheet",id:h.id,title:h.title??"",changeIndex:d}),v)break;O({op:"document.text",sheetId:h.id,edit:m,changeIndex:d},f);break;}case"calculation.add":case"calculation.update":case"calculation.remove":await lt(o,d,f);break;default:{const h=o;throw new Error(`Unhandled change ${JSON.stringify(h)}`);}}}catch(h){if(!(h instanceof Ae))throw h;}}if(i.length)return{ok:!1,problems:i};const ue=pt(e,l,{...b,...w});if(!ue.ok)return{ok:!1,problems:[{code:"invalid_change",message:ue.failedAt.message,path:`changes[${((Qa=l[ue.failedAt.index])==null?void 0:Qa.changeIndex)??0}]`,fix:"Read the outline again and propose again."}]};for(const d of r){if(R.has(d))continue;const o=fe(ue.dashboard,d);if(!o)continue;const f=((Ha=l.find($=>Oa($)===d))==null?void 0:Ha.changeIndex)??0,h=Le(o.card,{sql:!0,calculatedFields:ue.dashboard.calculatedFields??[]}),m=((Ya=ze(o.card))==null?void 0:Ya.type)??Ft(o.card.type);h.editable&&("sql"in h.query?!!h.query.sql:"measures"in h.query?h.query.measures.length>0:h.query.columns.length>0)&&((Ja=ct[m])==null?void 0:Ja.forms.includes(yt(h.query)))||i.push({code:"type_not_supported",message:`As changed, "${o.card.title}" would have no query a ${m.replace(/_/g," ")} can run.`,path:`changes[${f}]`,fix:`Send a complete query with the type change: ${((za=ct[m])==null?void 0:za.forms.map($=>St[$]).join(" or "))??"a measures query"}.`});}if(i.push(...fd(e,ue.dashboard,l,Ut,w)),i.push(...hd(ue.dashboard,wt,a.calendar)),i.push(...mr(ue.dashboard,Pa,a.calendar)),i.length)return{ok:!1,problems:i};for(const d of l){if(d.op!=="filter.add"&&!(d.op==="filter.update"&&d.settings.scope))continue;const o=d.op==="filter.add"?d.input.id:d.filterId,f=Ve(ue.dashboard,o,void 0,w);if(!(f!=null&&f.editable))continue;const h=async _=>{const x=[];for(const C of _){const q=C.datasetName?await a.findRelationshipFields({domainId:f.domainId,fromDataset:f.datasetName,field:f.field,toDataset:C.datasetName}):[];x.push({...C,suggestedFields:q});}return x;},m=_=>_.map(x=>`"${x.title}"`).join(", "),v=f.notReached.filter(_=>_.reason==="sql_no_filter_reference"),$=f.notReached.filter(_=>_.reason!=="sql_no_filter_reference");if(v.length&&n.push({code:"filter_not_reaching_cards",message:`"${f.label}" doesn't reach ${v.length} SQL card${v.length===1?"":"s"} whose SQL doesn't use dashboard filters: ${m(v)}.`,path:`changes[${d.changeIndex??0}]`,fix:"To filter a SQL card, add {{ filters | where }} to its SQL (or {{ filters | and }} after an existing WHERE) with card.update, or leave it unfiltered.",details:{cards:v}}),$.length){const _=await h($);n.push({code:"filter_not_reaching_cards",message:`"${f.label}" doesn't reach ${_.length} card${_.length===1?"":"s"} on its sheets: ${m(_)}.`,path:`changes[${d.changeIndex??0}]`,fix:"Add filter.bind with one of the suggested fields to reach a card, or leave it unfiltered.",details:{cards:_}});}if((Xa=f.sqlPending)!=null&&Xa.length&&n.push({code:"filter_reach_through_sql",message:`"${f.label}" may reach ${f.sqlPending.length} SQL card${f.sqlPending.length===1?"":"s"} as ${f.sqlPending.length===1?"its":"their"} SQL decides: ${m(f.sqlPending)}.`,path:`changes[${d.changeIndex??0}]`,fix:"Read the card's SQL to tell the user whether it uses this filter.",details:{cards:f.sqlPending}}),(Za=f.relationshipPending)!=null&&Za.length){const _=await h(f.relationshipPending);n.push({code:"filter_reach_through_relationships",message:`"${f.label}" may reach ${_.length} card${_.length===1?"":"s"} on its sheets through the domain's relationships: ${m(_)}. Whether it applies is decided when each card runs.`,path:`changes[${d.changeIndex??0}]`,fix:"Add filter.bind with one of the suggested fields to make it certain, or leave it to the relationships.",details:{cards:_}});}}if(a.readComparisonDates){const d=a.readComparisonDates,o=/* @__PURE__ */new Map(),f=v=>{const $=o.get(v.dashboard)??/* @__PURE__ */new Map();o.set(v.dashboard,$);const _=$.get(v.card.id);if(_)return _;const x=d(v);return $.set(v.card.id,x),x;};for(const[v,$]of B){const _=(es=fe(ue.dashboard,v))==null?void 0:es.card;if(!_)continue;const x=await f({card:_,dashboard:ue.dashboard});x.dateWindow==="none"&&n.push({code:"comparison_without_date_window",message:`"${_.title||"Untitled"}" compares with an earlier period only while a date range applies to ${((ts=x.comparisonDate)==null?void 0:ts.label)??"its date"}; none does yet.`,path:$,fix:"Add a timeWindow on that date, or a dashboard date filter that reaches the card."});}const h=/* @__PURE__ */new Map();for(const v of l){const $="cardId"in v?v.cardId:"variableId"in v?v.variableId:v.op==="variable.add"?v.variable.id:void 0;typeof $=="string"&&!h.has($)&&h.set($,v.changeIndex??0);}const m=((as=l.find(v=>v.op.startsWith("filter.")))==null?void 0:as.changeIndex)??0;n.push(...(await pr({before:e,after:ue.dashboard,changeIndexOf:v=>h.get(v)??m,readComparisonDates:f})));}n.push(...Qr({before:e,after:ue.dashboard,operations:l,context:{...b,...w},reachOptions:w}));const Ei=ld(ue.dashboard,l,ue.descriptions,w);return{ok:!0,operations:l,context:b,dashboard:ue.dashboard,detaches:ue.detaches,refs:c,descriptions:Ei,changedCardIds:r,requires:[...u],warnings:n};}function ld(e,t,a,s){const i=t.filter(u=>u.op==="card.add"||u.op==="sheet.add"&&u.frame);if(!i.length)return[...a];const n=Ra(e,void 0,s);if(!n.length)return[...a];const l=u=>qe(u.map(r=>`"${r}"`)),c=/* @__PURE__ */new Map();for(const u of i){const r=Oa(u);if(!r||u.changeIndex===void 0)continue;const p=n.filter(I=>I.reaches.includes(r)).map(I=>I.label),b=I=>n.filter(F=>{var y;return"notReached"in F&&((y=F.notReached)==null?void 0:y.some(V=>V.cardId===r&&V.reason==="sql_no_filter_reference"===I));}).map(F=>F.label),w=b(!1),g=b(!0),S=n.filter(I=>{var F;return(F=I.relationshipPending)==null?void 0:F.some(y=>y.cardId===r);}).map(I=>I.label),k=n.filter(I=>{var F;return(F=I.sqlPending)==null?void 0:F.some(y=>y.cardId===r);}).map(I=>I.label),A=[...(p.length?[`The dashboard's ${l(p)} filter${p.length===1?" applies":"s apply"} to it.`]:[]),...(w.length?[`${l(w)} ${w.length===1?"doesn't":"don't"} reach it.`]:[]),...(g.length?[`${l(g)} ${g.length===1?"doesn't":"don't"} reach it: its SQL doesn't use dashboard filters.`]:[]),...(S.length?[`${l(S)} may reach it through the domain's relationships.`]:[]),...(k.length?[`${l(k)} may apply through its SQL.`]:[])];A.length&&c.set(u.changeIndex,A.join(" "));}return a.map(u=>{const r=u.changeIndex===void 0?void 0:c.get(u.changeIndex);return r?{...u,sentence:`${u.sentence} ${r}`}:u;});}function Oa(e){var t,a,s;if(e.op==="card.update"||e.op==="card.remove")return e.cardId;if(e.op==="card.add")return(t=e.frame.cards[0])==null?void 0:t.id;if(e.op==="sheet.add")return(s=(a=e.frame)==null?void 0:a.cards[0])==null?void 0:s.id;}function cd(e){return Object.fromEntries(Qo.flatMap(t=>e[t]===void 0?[]:[[t,e[t]]]));}function ud(e,t){if(!t.length||!e.config)return e;const a={...e.config},s=[];if(a.matrix){const n=a.matrix,l=zo(n),c=[...n.spec.rows,...n.spec.columns],u={...n.presentation.levelLabels},r={...n.presentation.measureLabels};for(const{key:p,label:b}of t){if(p.role==="metric"){const w=l.measures.findIndex(g=>Dt(g,p));if(w<0)continue;r[n.spec.measures[w].id]=b;}else{const w=l.levels.findIndex(g=>Dt(g,p));if(w<0)continue;u[c[w].id]=b;}s.push(p);}return a.matrix={...n,presentation:{...n.presentation,levelLabels:u,measureLabels:r}},{...e,config:a,statedLabels:s};}const i={metric:"metricColumns",group_by:"groupByColumns",detail:"detailColumns"};for(const{key:n,label:l}of t){const c=[...(a[i[n.role]]??[])],u=ti(n.role,c).findIndex(r=>Dt(r,n));u<0||(c[u]=Pn(c[u],l),a[i[n.role]]=c,s.push(n));}return{...e,config:a,statedLabels:s};}function fd(e,t,a,s,i){var A;const n=[],l=new Map(we(t).map(I=>[I.cardId,I])),c=ka(t),u=Ie(t),r=I=>{var F,y;return((y=(F=t.sheets)==null?void 0:F.find(V=>V.id===I))==null?void 0:y.title)??I;},p=(I,F)=>{var y;return((y=[...a].reverse().find(V=>Oa(V)===F||"filterId"in V&&V.filterId===I))==null?void 0:y.changeIndex)??0;},b=(I,F)=>{const y=u.findFilterInput({inputId:I}).input,V=l.get(F),D=`"${V.card.title??""}"`,O=`"${y.label}"`;if(V.kind==="documentSectionCard")return{reason:"document_section",message:`${D} is in a Document section, which takes only the filters its Document sheet shows.`,fix:"Tell the user to change where the filter shows in the editor."};const Y=c.get(V.sheetId);if(Y&&!si(y,Y))return{reason:"outside_sheets",message:`${O} isn't shown on "${r(V.sheetId)}", so it can't filter ${D}.`,fix:"Show it on that sheet first with filter.update sheetIds (null for every sheet), in the same proposal."};const R=Ia(y,V.card);switch(R.status){case"incompatible":return{reason:"incompatible_field",message:`${D} can't take ${O}'s values on that field: their types differ.`,fix:"Bind a field of the same type (filter.bind)."};case"stale":return{reason:"field_not_on_card",message:`${D} doesn't have the field ${O} is bound to.`,fix:"Bind a field the card has (filter.bind), or exclude the card (filter.exclude), in the same proposal."};case"ambiguous":return{reason:"ambiguous_field",message:`${D} has more than one field ${O} could filter.`,fix:"Bind the field it should use (filter.bind), or exclude the card (filter.exclude), in the same proposal."};case"relationship":{const E=Xe(y,V.card,i);return E.reach==="blocked"?{reason:"relationship_route_changed",message:`The relationships ${D} used for ${O} changed in the domain.`,fix:"Tell the user to choose the relationship again in the filter's Cards tab."}:E.reason==="relationship_ambiguous"?{reason:"relationship_ambiguous",message:`${O} connects to ${D} through more than one path.`,fix:"Tell the user to choose a path in the filter's Cards tab, or bind a field the card has (filter.bind)."}:{reason:"relationship_pending",message:`${O} may reach ${D} through the domain's relationships; whether it applies is decided when the card runs.`,fix:"Bind a field the card has (filter.bind) to make it certain, or leave it to the relationships."};}case"excluded":case"bound":case"unsupportedTarget":case"sql":case"automatic":case"passthrough":case"notApplicable":return{reason:"filter_settings_override",message:`${O} still wouldn't filter ${D}: its settings leave that card out.`,fix:"Tell the user to change the filter's settings in the editor."};default:{const E=R;throw new Error(`Unhandled filter card target ${String(E.status)}`);}}},w=/* @__PURE__ */new Set(),g=/* @__PURE__ */new Map();for(const I of a)(I.op==="filter.bind"||I.op==="filter.exclude")&&g.set(`${I.filterId}|${I.cardId}`,I);for(const I of g.values()){const F=Ve(t,I.filterId,void 0,i),y=l.get(I.cardId);if(!F||!y)continue;const V=F.reaches.includes(I.cardId);if(I.op==="filter.bind"?V:!V)continue;w.add(`${I.filterId}|${I.cardId}`);const D=I.op==="filter.bind"?b(I.filterId,I.cardId):{reason:"filter_settings_override",message:`"${F.label}" would still filter "${y.card.title??""}".`,fix:"Tell the user to change the filter's settings in the editor."};n.push({code:"filter_not_editable",message:D.message,path:`changes[${I.changeIndex??0}]`,fix:D.fix,details:{reason:D.reason,cardId:I.cardId}});}for(const[I,F]of s){const y=Ve(t,I,void 0,i);if(!y)continue;const V=y.editable&&((A=y.exceptSheetIds)==null?void 0:A.some(Y=>{var R;return((R=c.get(Y))==null?void 0:R.sheetKind)==="dashboard";})),D=y.editable&&!V?y.sheetIds:void 0,O=F.sheetIds==="all"?"all":[...F.sheetIds].sort();Me(D==="all"||!D?D:[...D].sort(),O)||n.push({code:"filter_not_editable",message:`"${y.label}" wouldn't show on the sheets asked for. Change where it shows in the editor.`,path:`changes[${F.changeIndex}].sheetIds`,fix:"Tell the user to change the filter's sheets in the editor.",details:{reason:"filter_settings_override",...(D?{sheetIds:D}:{})}});}const S=Ie(e),k=I=>I==="blocked"||I==="ambiguous";for(const I of u.inputs){const F=I.input.id;for(const y of u.reachedCards({inputId:F})){if(w.has(`${F}|${y.cardId}`)||!k(Xe(I.input,y.card,i).reach))continue;const V=S.findFilterInput({inputId:F}),D=V&&S.reachedCards({inputId:F}).find(Y=>Y.cardId===y.cardId);if(V&&D&&k(Xe(V.input,D.card,i).reach))continue;const O=b(F,y.cardId);n.push({code:"invalid_change",message:`${O.message} The card would stop showing data while "${I.input.label}" has a value.`,path:`changes[${p(F,y.cardId)}]`,fix:O.fix,details:{reason:O.reason,filterId:F,cardId:y.cardId}});}}return n;}function hd(e,t,a){const s=[],i=Ie(e),n=we(e).flatMap(l=>l.kind==="frameCard"?[l.card]:[]);for(const[l,c]of t){const u=c.pinned?void 0:i.findFilterInput({inputId:l}),r=c.pinned?ci(n,c.pinned.filterId,c.pinned.cardId):void 0,p=(r==null?void 0:r.kind)==="found"?r:void 0;if(!u&&!p)continue;const b=u?u.input.filter:p.filter,w=u?u.input.label:p.filter.title,g=u?Bt({dashboard:e,target:{kind:"dashboardInput",input:u.input,scope:{}},calendar:a}).value:Bs(p.filter,a),S=b.dateSelectionMode,k=S==="day"?"its date picker takes one day":S==="months"?"its month picker takes one whole month":void 0,A=(I,F)=>s.push({code:"filter_not_editable",message:I,path:`changes[${c.changeIndex}]`,fix:F,details:{reason:"default_not_applied",...(S?{datePicker:S}:{})}});if(c.condition!==void 0){const I=c.condition?Zs(c.condition):void 0,F=I!=null&&I.ok?I.condition:null,y=g&&g.operation!=="in"&&g.operation!=="not in"?{operation:g.operation,values:(g.values??[]).map(Number)}:null;JSON.stringify(F)!==JSON.stringify(y)&&A(F?`"${w}" wouldn't load with that default condition.`:`"${w}" would still load with a default.`,"Tell the user to change the filter's default in the editor.");continue;}if(c.period){const I=Fa(g&&"relativeMeta"in g?g.relativeMeta:void 0);(!I||jn(c.period)||!li(I,c.period))&&A(`"${w}" wouldn't load with that default${k?`: ${k}`:""}.`,k?"Ask for a default the picker can take, or tell the user to make it a date range in the editor.":"Tell the user to change the filter's default in the editor.");}else if(c.values){const I=F=>JSON.stringify((F??[]).map(String).sort());(!g||I(g.values)!==I(c.values))&&A(`"${w}" wouldn't load with those values.`,"Tell the user to change the filter's default in the editor.");}else(jt(b.dataType)?c.period===null:c.values===null)&&g&&A(`"${w}" would still load with a default.`,"Tell the user to change the filter's default in the editor.");}return s;}function na(e){const t=e.measures;if(!Array.isArray(t))return{query:e,calculations:[]};const a=[],s=t.map((i,n)=>{if(!i||typeof i!="object")return i;const{comparison:l,transform:c,...u}=i;return l===void 0&&c===void 0?i:(a.push({index:n,calculations:{...(l!==void 0?{comparison:l}:{}),...(c!==void 0?{transform:c}:{})}}),Object.keys(u).length===1&&typeof u.name=="string"?u.name:u);});return{query:{...e,measures:s},calculations:a};}function Ds(e){var a,s;const t=(s=(a=e.config)==null?void 0:a.groupByColumns)==null?void 0:s.find(i=>Bo(i.dataType||"")==="date");return{comparisonDate:t?{name:t.name,label:t.label||t.name}:null,dateWindow:"unknown"};}function md(e,t){if("sql"in t)return[];const a=e,s=(...n)=>new Set(n.flatMap(l=>Array.isArray(l)?l:l?[l]:[]).map(l=>Re(l,t.datasetName))),i={metric:s(a.measures),group_by:s(a.dimensions,a.dateField),detail:s(a.columns)};return mt(t).filter(n=>i[n.key.role].has(n.key.field));}function pd(e,t,a,s){const i=Object.fromEntries(Object.entries(t).filter(([,b])=>b!=null)),n=yt(i),l=yt(e),c=b=>ga[b].safeParse(i);if(!e||n&&n!==l){const b=n??l,w=b?c(b):void 0;return w!=null&&w.success?w.data:s({code:e?"query_form_mismatch":"type_not_supported",message:e?"This patch changes the query's form (measures, records or SQL) without a complete query.":"This card's current query can't be patched; send a complete query.",path:a,fix:"Send a complete query of the new form: domainId, datasetName and measures (or columns), or connectionId and sql."});}const u={...e};for(const[b,w]of Object.entries(t))w!==void 0&&(w===null?delete u[b]:u[b]=w);const r=Ti(e,t);r&&delete u.timeWindow;const p=ga[l].safeParse(u);if(!p.success){const b=p.error.issues[0];return s({code:(b==null?void 0:b.code)==="unrecognized_keys"?"query_form_mismatch":"invalid_change",message:(b==null?void 0:b.message)??"The merged query is not valid.",path:b?xi(a,b):a,fix:"Patch only keys of the card's query form, or send a complete query of a new form."});}return r?{...p.data,timeWindow:r}:p.data;}function Ti(e,t){if(!(!e||"sql"in e||t.timeWindow!==void 0))return e.timeWindow;}function Os(e){return e?{kind:"sheets",sheetIds:e}:{kind:"allSheets",sheetKinds:["dashboard"]};}function ra(e,t,a,s){return["date","datetime","timestamp"].some(l=>pa(t.dataType).includes(l))||s({code:"invalid_change",message:"defaultPeriod is for date filters.",path:a,fix:"Use defaultValues for this field."}),Fi(e,{use:"filterDefault",columnHasTime:gd(t)},a,s);}function Fi(e,t,a,s){const i=di(e,t);return i.ok?i.window:s({code:"invalid_change",message:i.refusal.message,fix:i.refusal.fix,path:i.refusal.path?`${a}.${i.refusal.path}`:a});}function gd(e){return js({dataType:e.dataType})==="datetime";}function bd(e){var t,a,s;return(s=(a=(t=e==null?void 0:e.filters)==null?void 0:t.conditions)==null?void 0:a.find(i=>i.relativeMeta))==null?void 0:s.field;}async function yd(e,t,a,s,i,n){const l=Eo(e),c=l.kind==="config"?l.executableSources:l.kind==="sql"?l.pinnedCatalogSources.map(k=>k.source):[],u=Pe(e),r=typeof t=="string"?(u==null?void 0:u.kind)==="semantic"?u.datasetName:void 0:t.datasetName,p=c.find(k=>k.kind==="semantic"&&pa(k.datasetName)===pa(r));if((!p||p.kind!=="semantic")&&n)return i({code:"field_not_found",message:`"${n}" already filters "${e.title}" through the domain's relationships, so it needs no binding; the card doesn't read ${r?`the dataset ${r}`:"that dataset"}.`,path:s,fix:"Leave out this filter.bind: the filter applies to the card as it is."});if(!p||p.kind!=="semantic")return i({code:"field_not_found",message:`"${e.title}" doesn't read ${r?`the dataset ${r}`:"a dataset"}.`,path:s,fix:"Name a field of the card's own dataset, or { name, datasetName } for a dataset its query joins."});const b=await a.loadCardSource({domainId:p.domainId,datasetName:p.datasetName}),w=typeof t=="string"?t:t.name,g=b?Vt(b.fields,w,p.datasetName):void 0,S=g?An(p,{column_name:g.name,data_type:g.dataType,...(g.sourceField?{sourceField:g.sourceField}:{})}):void 0;return S||i({code:"field_not_found",message:`"${w}" isn't a field of ${p.datasetName}.`,path:s,fix:"Use one of details.available, or read semaphor_get_dataset_schema.",details:{available:((b==null?void 0:b.fields)??[]).slice(0,20).map(k=>k.name)}});}function vd(e,t,a,s){const i=br(gr(a),e,{relationshipReach:s});if(i.reached||i.reach==="relationship"||i.reach==="sqlTemplate")return;const n=e.title||"This card";if(i.reach==="blocked"||i.reach==="ambiguous")return`A filter on ${t} would stop "${n}" from running${i.message?`: ${i.message}`:""}.`;const l=qo(e),c=i.reason==="sql_no_filter_reference"?"its SQL uses no filter":i.reason?Rn(i.reason,l?{name:l.name,label:l.label}:void 0).toLowerCase():`it doesn't read ${t} or reach it through a relationship`;return`A filter on ${t} would never filter "${n}": ${c}.`;}const $d={max:ms,what:"A proposal that creates a dashboard",fix:`Create with the first ${ms}, then change the new dashboard in a second proposal.`};async function Ll(e,t){const a=c=>c&&typeof c=="object"?c.op:void 0,s=e.changes.flatMap((c,u)=>a(c)==="dashboard.update"?[{code:"invalid_change",message:"A create names its dashboard in create, not with dashboard.update.",path:`changes[${u}].op`,fix:"State the title and description in create."}]:[]);if(s.length)return{ok:!1,problems:s};const i=Id(e,t),n=await ki(i,e.changes,t,{limit:$d});if(!n.ok)return n;const l=wd(n,e.changes);return{...l,seed:i,sentence:_d(l.dashboard)};}function wd(e,t){if(t.some(n=>{if(!n||typeof n!="object")return!1;const{op:l}=n;return l==="layout.arrange"||l==="card.add"&&("width"in n||"position"in n);}))return e;const s=(e.dashboard.sheets??[]).filter(n=>Ca(n)&&(n.frames??[]).length>0).map(n=>({op:"layout.arrange",sheetId:n.id}));if(!s.length)return e;const i=pt(e.dashboard,s,e.context);if(!i.ok)throw new Error(`Arranging a new dashboard failed: ${i.failedAt.code}`);return{...e,operations:[...e.operations,...s],dashboard:i.dashboard,descriptions:[...e.descriptions,...i.descriptions]};}function Id(e,t){const a=e.changes.some(s=>s&&typeof s=="object"&&s.op==="sheet.add");return{id:e.dashboardId,title:e.create.title,...(e.create.description?{description:e.create.description}:{}),interactionDefaults:{clickToFilter:"on"},inputs:[],sheets:a?[]:[{id:t.newId(),title:"Sheet 1"}]};}const da=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function _d(e){const t=e.sheets??[],a=t.reduce((n,l)=>n+(l.frames??[]).reduce((c,u)=>{var r;return c+(((r=u.cards)==null?void 0:r.length)??0);},0),0),s=(e.inputs??[]).filter(n=>n.kind==="filter").length,i=[da(t.length,"sheet"),da(a,"card"),...(s?[da(s,"filter")]:[])];return`Creates a private dashboard ${Ne(e.title)} with ${qe(i)}.`;}const Cd=50;function Ml(e,t){var D,O,Y;const a=(D=t.sheetIds)!=null&&D.length?new Set(t.sheetIds):void 0,s=(O=t.cardIds)!=null&&O.length?new Set(t.cardIds):void 0,i=(e.sheets??[]).filter(R=>!a||a.has(R.id)),n=we(e).filter(R=>(!a||a.has(R.sheetId))&&(!s||s.has(R.cardId))),l=n.length>(t.maxQueryCards??Cd),c=new Map((e.sheets??[]).flatMap(R=>(R.frames??[]).map(E=>[E.id,E]))),u=/* @__PURE__ */new Map(),r=R=>{(R==null?void 0:R.kind)==="semantic"&&u.set(`${R.domainId}|${R.datasetName}`,{domainId:R.domainId,datasetName:R.datasetName});},p=new Map((e.sheets??[]).map(R=>[R.id,ua({dashboard:e,place:{kind:R.kind==="document"?"document":"sheet",sheetId:R.id}})])),b=R=>({catalog:R,inputs:e.inputs,variables:e.variables}),w=R=>b(p.get(R)),g=/* @__PURE__ */new Map(),S=(R,E)=>{if(R.kind==="document")return w(R.id);const B=ua({dashboard:e,place:{kind:"sheet",sheetId:R.id,cardId:E}});return g.set(`${R.id}:${E}`,B),b(B);},k=i.map(R=>({sheetId:R.id,title:R.title??"",kind:en(R),...(R.kind==="document"?xd(R,w(R.id)):Ca(R)?{layout:Fd(R)}:{}),cards:n.filter(E=>E.sheetId===R.id).map(E=>{var M,Q;const B=E.card,U=E.kind==="frameCard"?(M=c.get(E.frameId))==null?void 0:M.visualId:void 0,N=U?{linkedVisualId:U}:{},J={cardId:E.cardId,title:B.title??""};if(E.kind!=="frameCard"){const K=Pe(B);return r(K),{...J,...xt(B),...(K?{source:K}:{}),editable:!1,notEditable:E.kind==="documentSectionCard"?{reason:"document_section",message:"Cards in Document sections can't be changed through the MCP yet. Change them in the editor."}:{reason:"not_expressible",message:"This card isn't in a tile, so it can't be changed through the MCP. Change it in the editor.",detail:"a card outside a tile"}};}if(B.type==="text"){const K=ei(B,S(R,B.id));return K.editable?{...J,type:"text",...N,editable:!0,text:K.text,...(K.editorOnly.length?{editorOnly:K.editorOnly}:{})}:{...J,...xt(B),...N,editable:!1,notEditable:{reason:"text",message:K.message}};}const P=Le(B,{sql:t.sql,calculatedFields:e.calculatedFields??[]});if(r(P.source),!P.editable)return{...J,...xt(B),...(P.source?{source:P.source}:{}),...N,editable:!1,notEditable:{reason:P.reason,message:P.reason==="not_expressible"||P.reason==="type_not_supported"?`${P.message} ${Xs}`:P.message,...(P.detail?{detail:P.detail}:{})},...(B.type==="customVisual"&&!l?{visual:Is(B,t.customVisualNames)}:{})};const T=l?void 0:$a(B);return{...J,...xt(B),type:P.type,source:P.source,...N,editable:!0,...(l?{}:{query:P.query,...(P.matrix?{matrix:P.matrix}:{}),...(P.timeWindowReadOnly?{timeWindowReadOnly:P.timeWindowReadOnly}:{}),...((Q=B.inlineFilters)!=null&&Q.length?{pinnedFilters:wr(B,qt(t.calendar,t.updatedAt))}:{}),...(B.type==="customVisual"?{visual:Is(B,t.customVisualNames)}:{})}),...T};})})),A=Ra(e,qt(t.calendar,t.updatedAt),{...(t.relationshipReach?{relationshipReach:t.relationshipReach}:{})});for(const R of A)R.editable&&u.set(`${R.domainId}|${R.datasetName}`,{domainId:R.domainId,datasetName:R.datasetName});const I=kd(e,t,new Map([...p,...g]));for(const R of e.variables??[]){const E=ma(R);(E==null?void 0:E.kind)==="semantic"&&u.set(`${E.domainId}|${E.datasetName}`,{domainId:E.domainId,datasetName:E.datasetName});}const F=(e.variables??[]).filter(R=>{var E;return((E=ma(R))==null?void 0:E.kind)==="physical";}).map(R=>R.name),y=(e.sheets??[]).some(R=>{var E;return(E=R.document)==null?void 0:E.sections.some(B=>{var U,N;return B.type==="text"&&(((U=B.style)==null?void 0:U.fontWeight)||((N=B.style)==null?void 0:N.color));});}),V=[...(F.length?[`a variable on a table or view source (${F.join(", ")}): changed in the editor`]:[]),...(y?["a Document text section's weight or color: changed in the editor"]:[]),"a dashboard calculated field over more than one dataset: built in the editor, or added to the domain","a calculated field on a Matrix: use a domain calculation, or build it in the editor","a date grouping on a dashboard calculated field, or a condition on a dashboard calculated measure: set in the editor","click to filter (turning clicks on or off, which fields a click carries, binding a field, excluding a card): changed in the editor","a date before or after a point measured from today, on a card filter or a filter default: changed in the editor","a filter's option list (where its values come from, Connect filters through): changed in the editor","a card on a database table instead of a dataset, or a card with joins set in the editor (Join a table, Set up join): built and changed in the editor"];return{dashboardId:t.dashboardId,title:e.title??"",...(e.description?{description:e.description}:{}),updatedAt:t.updatedAt,access:t.access,datasets:[...u.values()],sheets:k,filters:A,variables:I,style:Sd(e,t),...((Y=e.calculatedFields)!=null&&Y.length?{calculatedFields:Ad(e)}:{}),editorOnly:V,...(l?{truncated:!0}:{})};}function Sd(e,t){const{style:a,organizationAppearance:s}=ai(e,t.organizationAppearance);return{set:cr(a),shows:On({organizationAppearance:s,dashboardStyle:a},"light").shows};}function Es(e,t){const a=sn(t);return a?{...e,style:a}:e;}function xd(e,t){const a=e.document;if(!a)return{};const s=i=>{var n;return(((n=a[i])==null?void 0:n.blocks)??[]).flatMap(l=>l.type==="text"&&l.role?[Es({role:l.role,text:Pt(l.content,{...t,documentInputs:a.inputs})},l.style)]:[]);};return{header:s("header"),footer:s("footer"),textSections:a.sections.flatMap(i=>i.type==="text"?[Es({sectionId:i.id,text:Pt(i.content,{...t,documentInputs:a.inputs})},i.style)]:[])};}function kd(e,t,a){const s=ii(e),i=r=>s.filter(({ref:p})=>r(p)).map(({place:p,where:b})=>({sheetId:p.sheetId,where:b.kind,id:b.kind==="card"?b.cardId:b.kind==="section"?b.sectionId:b.blockId})),n=/* @__PURE__ */new Map();for(const r of a.values())for(const p of r.entries){const b=n.get(p.name);(!b||b.kind==="report"&&p.kind!=="report")&&n.set(p.name,p);}const l=[...n.values()].filter(r=>r.kind==="input").map(r=>({name:r.name,kind:"input",words:r.input.kind==="control"?`The ${r.label} control's value`:`The ${r.label} filter's value`,parts:[...r.parts],usedIn:i(p=>p.source==="input"&&p.inputId===r.input.id||p.source==="dashboardInputAlias"&&p.variableName===r.name),editable:!1})),c=[...n.values()].filter(r=>r.kind==="report").map(r=>({name:r.name,kind:"report",words:Td[r.reportKey],parts:[],usedIn:i(p=>p.source==="documentMeta"&&p.key===r.reportKey),editable:!1})),u=(e.variables??[]).map(r=>{const p=Ii(r,{sql:t.sql}),b=_a(r,e)[0],w=tn(r.presentation);return{name:r.name,kind:"data",words:Dn(r),parts:$n(r),...(w?{presentation:w}:{}),usedIn:i(g=>g.source==="data"&&g.variableId===r.id),editable:p.editable,...(p.editable?{}:{notEditable:{reason:p.reason,message:p.message}}),...(b?{broken:`${b.message} ${b.fix}`}:{})};});return[...l,...c,...u];}const Td={generatedAt:"When the report was generated",pageNumber:"The page number (Documents)",pageCount:"The page count (Documents)"};function xt(e){const t=ze(e);return t?{type:t.type,...t.properties}:{type:Ft(e.type)};}function Fd(e){const t=new Map((e.frames??[]).map(a=>[a.id,a]));return Qn(e).rows.map(a=>({tiles:a.tiles.map(s=>{const i=t.get(s.frameId);return{cardIds:i?Hs(i):[],width:s.width};})}));}function Ad(e){return(e.calculatedFields??[]).flatMap(t=>{const a=zs(t),s=an(t);if(!a||!s)return[];const i=Js(e,Rt(t));return[{domainId:s.domainId,dataset:s.datasetName,name:a.name,...(a.label?{label:a.label}:{}),...(a.description&&a.description!==`Calculated field: ${a.label}`?{description:a.description}:{}),expression:a.expression,inputs:Object.fromEntries(Object.entries(a.inputs).map(([n,l])=>{var c;return[n,{dataset:l.dataset,field:l.field,...(t.role==="metric"&&((c=t.calculatedFormula)==null?void 0:c.computeStage)!=="row"&&l.aggregate?{aggregate:l.aggregate}:{})}];})),use:a.use,dataType:a.dataType,usedBy:[...i.cards.map(n=>n.cardId),...i.filters.map(n=>n.filterId)]}];});}function me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e);}function De(e,t){return me(e)&&Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0;}const ve=De,Rd=["metricColumns","groupByColumns","detailColumns","pivotByColumns","sortByColumns"],Dd=["xAxisConfig","yAxisConfig","secondaryYAxisConfig","tooltipConfig","dataLabelsConfig"],Od='`format` on the matching column in `config.metricColumns`, `groupByColumns` or `detailColumns`; for a SQL or Python card, `preferences.sqlColumns["<column>"].format`',kt="`preferences.conditionalFormatting`, with columns named by card column id";function Ed(e){return gt(String(e.type))??Aa;}function ht(e,t,a){if(a===void 0)return;const s=me(a)?Ed(a).safeParse(a):Aa.safeParse(a);if(!s.success)for(const i of s.error.issues){const n=i.code==="unrecognized_keys"?i.keys:[i.path.length?String(i.path[i.path.length-1]):"type"];for(const l of n)e.push({path:[t,...i.path.map(String),...(i.code==="unrecognized_keys"?[l]:[])].join("."),field:l,replacement:l==="locale"?"nothing: the viewer's locale applies":i.code==="unrecognized_keys"?"nothing: the stored format type has no such key":`a value the stored format type accepts (${i.message})`});}}function la(e,t,a){if(me(a)){for(const s of["dateFormat","customFormat"])ve(a,s)&&e.push({path:`${t}.${s}`,field:s,replacement:"`format` on this column (a temporal bucket or date format)"});ht(e,`${t}.format`,a.format);}}function Ai(e,t){const a=[],s=e.config;for(const S of Rd){const k=s==null?void 0:s[S];Array.isArray(k)&&k.forEach((A,I)=>la(a,`${t}.config.${S}[${I}]`,A));}const i=me(s==null?void 0:s.matrix)?s.matrix:void 0,n=me(i==null?void 0:i.presentation)?i.presentation:void 0;for(const S of["measureFormats","levelFormats"]){const k=n==null?void 0:n[S];if(me(k))for(const[A,I]of Object.entries(k))ht(a,`${t}.config.matrix.presentation.${S}.${A}`,I);}ve(n,"conditionalFormatting")&&a.push({path:`${t}.config.matrix.presentation.conditionalFormatting`,field:"conditionalFormatting",replacement:kt});const l=e.interactionConfig,c=l==null?void 0:l.drillHierarchies;Array.isArray(c)&&c.forEach((S,k)=>{me(S)&&(la(a,`${t}.interactionConfig.drillHierarchies[${k}].baseField`,S.baseField),Array.isArray(S.steps)&&S.steps.forEach((A,I)=>{me(A)&&la(a,`${t}.interactionConfig.drillHierarchies[${k}].steps[${I}].field`,A.field);}));});const u=e.preferences;if(!u)return a;const r=`${t}.preferences`;if(ve(u,"formatNumber")){const S=u.formatNumber,k=me(S)&&Object.keys(S).every(A=>A==="colorRanges");a.push(k?{path:`${r}.formatNumber.colorRanges`,field:"colorRanges",replacement:`${kt} (a rule on the KPI's value)`}:{path:`${r}.formatNumber`,field:"formatNumber",replacement:"`format` on each measure in `config.metricColumns`; for a SQL KPI, `preferences.sqlKpiValue.format`"});}ve(u,"numberAxisFormat")&&a.push({path:`${r}.numberAxisFormat`,field:"numberAxisFormat",replacement:"`valueFormat` on `preferences.yAxisConfig` (or the axis it formats)"}),ve(u,"columnSettings")&&a.push({path:`${r}.columnSettings`,field:"columnSettings",replacement:"`preferences.tablePrefs.columnSettingsMap`, keyed by column"});const p=u.kpiVisualOptions;ve(p,"formatOptions")&&a.push({path:`${r}.kpiVisualOptions.formatOptions`,field:"formatOptions",replacement:"`format` on each measure in `config.metricColumns`; for a SQL KPI, `preferences.sqlKpiValue.format`"}),ve(p,"queryComparisonPolarity")&&a.push({path:`${r}.kpiVisualOptions.queryComparisonPolarity`,field:"queryComparisonPolarity",replacement:"`preferences.sqlKpiValue.comparisonPolarity`"});const b=u.tablePrefs;ve(b,"conditionalFormatting")&&a.push({path:`${r}.tablePrefs.conditionalFormatting`,field:"conditionalFormatting",replacement:kt});const w=b==null?void 0:b.columnSettingsMap;if(me(w))for(const[S,k]of Object.entries(w)){if(!me(k))continue;const A=`${r}.tablePrefs.columnSettingsMap.${S}`;for(const I of["numberFormat","dateFormat","inheritMetricFormat"])ve(k,I)&&a.push({path:`${A}.${I}`,field:I,replacement:I==="inheritMetricFormat"?"nothing: a column follows its `format`":Od});ve(k,"colorRanges")&&a.push({path:`${A}.colorRanges`,field:"colorRanges",replacement:kt});}for(const S of Dd){const k=u[S];if(me(k)){for(const A of["formatMode","mode","formatOptions"])ve(k,A)&&a.push({path:`${r}.${S}.${A}`,field:A,replacement:`\`preferences.${S}.valueFormat\` (absent means the column's format)`});S==="dataLabelsConfig"&&ve(k,"format")&&a.push({path:`${r}.${S}.format`,field:"format",replacement:"`preferences.dataLabelsConfig.valueFormat`"}),ht(a,`${r}.${S}.valueFormat`,k.valueFormat);}}const g=u.sqlColumns;if(me(g))for(const[S,k]of Object.entries(g))me(k)&&ht(a,`${r}.sqlColumns.${S}.format`,k.format);return me(u.sqlKpiValue)&&ht(a,`${r}.sqlKpiValue.format`,u.sqlKpiValue.format),a;}function Nd(e){const t=`sheets[id=${e.sheetId}]`;switch(e.kind){case"sheetCard":return`${t}.cards[id=${e.cardId}]`;case"frameCard":return`${t}.frames[id=${e.frameId}].cards[id=${e.cardId}]`;case"documentSectionCard":return`${t}.document.sections[id=${e.sectionId}].cards[id=${e.cardId}]`;}}function Ri(e){if(!me(e))return[];if(Array.isArray(e.sheets))return we(e).map(a=>({card:a.card,at:Nd(a)}));const t=e;return Array.isArray(t.cards)?t.cards.map(a=>({card:a,at:`cards[id=${a.id}]`})):[];}function Vl(e){return Ri(e).flatMap(({card:t,at:a})=>Ai(t,a));}function Pd(e,t){var n;const a=(n=e.preferences)==null?void 0:n.conditionalFormatting;if(a===void 0)return[];const s=`${t}.preferences.conditionalFormatting`,i=on.safeParse(a);return i.success?nn(e).map(l=>({code:"invalid_conditional_formatting",path:`${s}.rules[id=${l.ruleId}].${l.path}`,message:l.message})):i.error.issues.map(l=>({code:"invalid_conditional_formatting",path:[s,...l.path.map(c=>typeof c=="number"?`[${c}]`:c)].join(".").replace(/\.\[/g,"["),message:l.message}));}function Bl(e){return Ri(e).flatMap(({card:t,at:a})=>[...Ai(t,a).map(s=>({code:"retired_presentation_field",path:s.path,message:`\`${s.field}\` is retired: use ${s.replacement}.`})),...Pd(t,a)]);}const Ea=["metricColumns","groupByColumns","detailColumns","pivotByColumns","sortByColumns"],qd=["xAxisConfig","yAxisConfig","secondaryYAxisConfig","tooltipConfig","dataLabelsConfig"];function le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e);}function Di(e,t){return JSON.stringify(e)===JSON.stringify(t);}function et(e,t){const a=s=>le(s)?Object.fromEntries(Object.keys(s).sort().map(i=>[i,a(s[i])])):s;return Di(a(e),a(t));}function Lt(e){const t=Kn(e);return t==="date"||t==="datetime";}function Oi(e){var t,a;return!!((t=e.sql)!=null&&t.trim()||(a=e.python)!=null&&a.trim());}function Ld(e){return e.type==="kpi"&&mn(e);}function ba(e){return e.type==="table"||e.type==="detailTable";}function pe(e,t){var s;const a=(s=e.config)==null?void 0:s[t];return Array.isArray(a)?a:[];}function Md(e,t){for(const a of Ea){const s=pe(e,a).indexOf(t);if(s>=0)return`config.${a}[${s}]`;}}function nt(e,t){let a=!1;for(const s of t)Object.prototype.hasOwnProperty.call(e,s)&&(delete e[s],a=!0);return a;}function Mt(e,t,a,s){t.format=a,t.formatOrigin="override",e.changes.push({path:s,action:"moved",to:`${Md(e.card,t)??"config"}.format`});}function Na(e){if(le(e))return bt(e);}function ya(e,t,a){if(!(!De(t,"dateFormat")&&!De(t,"customFormat"))){if(Lt(t.dataType)&&t.format==null&&t.dateFormat!=null){const s=fn({fieldId:t.id,dataType:t.dataType,granularity:t.granularity,dateFormat:t.dateFormat,customFormat:t.customFormat});s.ok&&(t.format=s.format,t.formatOrigin="override",e.changes.push({path:`${a}.dateFormat`,action:"moved",to:`${a}.format`}));}nt(t,["dateFormat","customFormat"])&&e.changes.push({path:`${a}.dateFormat`,action:"removed"});}}function Vd(e,t,a){if(!De(t,"dateFormat")&&!De(t,"customFormat"))return;const s=t.dateFormat==="custom"?t.customFormat:t.dateFormat;e.card.type==="detailTable"&&Lt(t.dataType)&&!t.format&&typeof s=="string"&&s.trim()?(t.format={type:"date",pattern:s},t.formatOrigin="override",e.changes.push({path:`${a}.dateFormat`,action:"moved",to:`${a}.format`})):e.card.type==="detailTable"&&Lt(t.dataType)&&t.format&&typeof s=="string"&&s.trim()&&!et(t.format,{type:"date",pattern:s})&&e.unconverted.push({path:`${a}.dateFormat`,reason:"detail_date_beside_format",detail:"A detail date pattern on a column that has a format of its own."}),nt(t,["dateFormat","customFormat"])&&e.changes.push({path:`${a}.dateFormat`,action:"removed"});}function Bd(e,t,a,s){if(t.format!==void 0){const i=Na(t.format);i?et(i,t.format)||(t.format=i,e.changes.push({path:`${s}.format`,action:"cleaned"})):(delete t.format,e.changes.push({path:`${s}.format`,action:"removed"}));}a==="groupByColumns"||a==="pivotByColumns"?ya(e,t,s):a==="detailColumns"?Vd(e,t,s):nt(t,["dateFormat","customFormat"])&&e.changes.push({path:`${s}.dateFormat`,action:"removed"});}function jd(e,t){for(const a of Ea)pe(e.card,a).forEach((s,i)=>{var l;if(!s.format||s.formatOrigin)return;const n=(l=t.modelFormatFor)==null?void 0:l.call(t,s);s.formatOrigin=n&&et(bt(n),s.format)?"semantic":"override",e.changes.push({path:`config.${a}[${i}].formatOrigin`,action:"marked"});});}function Kd(e){var a;const t=(a=e.card.interactionConfig)==null?void 0:a.drillHierarchies;Array.isArray(t)&&t.forEach((s,i)=>{if(!le(s))return;const n=`interactionConfig.drillHierarchies[${i}]`;le(s.baseField)&&ya(e,s.baseField,`${n}.baseField`),Array.isArray(s.steps)&&s.steps.forEach((l,c)=>{if(le(l)&&le(l.field)){const u=l.field,r=`${n}.steps[${c}].field`;if(u.format!==void 0){const p=Na(u.format);p&&!et(p,u.format)&&(u.format=p,e.changes.push({path:`${r}.format`,action:"cleaned"}));}ya(e,u,r);}});});}const Wd=["numberFormat","dateFormat","inheritMetricFormat","colorRanges"];function Ud(e,t){const a=i=>i==null?void 0:i.trim().toLowerCase(),s=a(t);return[e.id,e.alias,e.name,e.qualifiedFieldName,e.label,e.role==="metric"?qn(e):void 0].some(i=>i!==void 0&&a(i)===s);}function Ns(e,t){const a=hn(e,{columnId:t});if(a)return a;const s=[...pe(e,"detailColumns"),...pe(e,"metricColumns"),...pe(e,"groupByColumns")].filter(i=>Ud(i,t));return s.length===1?s[0]:void 0;}function Gd(e){return e.type==="number"&&le(e.numberFormat)&&e.inheritMetricFormat!==!0;}function Qd(e,t){var a;return Lt(t.dataType)?pe(e,"detailColumns").includes(t)?e.type==="detailTable":Gn(t.granularity)||((a=t.format)==null?void 0:a.type)==="temporal_bucket"||t.semanticTemporalPresentation!=null:!1;}function Ps(e,t,a,s){var l;const i=(l=e.card).preferences??(l.preferences={}),n=i.sqlColumns??(i.sqlColumns={});n[t]={...n[t],format:a},e.changes.push({path:s,action:"moved",to:`preferences.sqlColumns[${JSON.stringify(t)}].format`});}function Hd(e){const[t,...a]=e;if(!t)return;const s=Object.fromEntries(Object.entries(t).filter(([i,n])=>a.every(l=>Di(l[i],n))));return Aa.safeParse(s).success?s:void 0;}function Yd(e,t){const a=e.card,s=wn({groupByColumns:pe(a,"groupByColumns"),metricColumns:pe(a,"metricColumns"),pivotByColumns:pe(a,"pivotByColumns"),detailColumns:a.type==="detailTable"?pe(a,"detailColumns"):[]});for(const[i,n]of t){const l=n.find(u=>u.key===s.get(i)),c=l??n[0];if(Mt(e,i,c.format,c.from),!l)for(const u of n)u!==c&&!et(u.format,c.format)&&e.unconverted.push({path:u.from,reason:"ambiguous_column_setting",detail:`"${u.key}" and "${c.key}" both name ${i.id}.`});}}function Jd(e,t){var n;if(!t.length)return;const a=pe(e.card,"metricColumns"),s=a.length===1?a[0]:void 0,i=s&&!s.format?Hd(t.map(l=>l.format)):void 0;s&&i&&Mt(e,s,i,t[0].from);for(const l of t)if(!(s!=null&&s.format&&et(l.format,s.format))){if(!a.length){e.unconverted.push({path:l.from,reason:"generated_count_pivot_format",detail:`"${l.key}" is one pivot value's column on a table with no measure; it formats the row count the query adds.`});continue;}e.unconverted.push(((n=s==null?void 0:s.format)==null?void 0:n.type)===l.format.type?{path:l.from,reason:"pivot_value_format_difference",detail:`"${l.key}" is one pivot value's column; its format differs from its measure's, which every pivot value now shows.`}:{path:l.from,reason:"per_pivot_value_format",detail:`"${l.key}" is one pivot value's column; a card column holds one format for every pivot value.`});}}function zd(e){var u;const t=(u=e.card.preferences)==null?void 0:u.tablePrefs,a=t==null?void 0:t.columnSettingsMap;if(!le(a))return;const s=e.card,i=Oi(s),n=pe(s,"pivotByColumns").length>0,l=/* @__PURE__ */new Map(),c=[];for(const[r,p]of Object.entries(a)){if(!le(p))continue;const b=p,w=`preferences.tablePrefs.columnSettingsMap[${JSON.stringify(r)}]`;if(Gd(b)){const g=rn(b.numberFormat);if(g&&i)Ps(e,r,g,`${w}.numberFormat`);else if(g&&ba(s)){const S=Ns(s,r),k={key:r,format:g,from:`${w}.numberFormat`};S?l.set(S,[...(l.get(S)??[]),k]):n?c.push(k):e.unconverted.push({path:k.from,reason:"unmatched_column_setting",detail:`"${r}" names no card column.`});}else g&&s.type!=="matrixTable"&&s.type!=="kpi"&&pe(s,"metricColumns").some(k=>k.comparison!=null)&&e.unconverted.push({path:`${w}.numberFormat`,reason:"chart_comparison_column_setting",detail:`"${r}" formats this chart's comparison tooltip only.`});}if(le(b.dateFormat)){const g=b.type==="date";if(g&&i)Ps(e,r,dn(b.dateFormat),`${w}.dateFormat`);else if(g&&ba(s)){const S=Ns(s,r);(!S||!Qd(s,S))&&e.unconverted.push({path:`${w}.dateFormat`,reason:"config_column_date_setting",detail:`"${r}"'s download formats its dates with this setting.`});}}for(const g of Wd)Object.prototype.hasOwnProperty.call(b,g)&&(delete b[g],e.changes.push({path:`${w}.${g}`,action:"removed"}));}Yd(e,l),Jd(e,c);}function Xd(e){return Object.keys(e).some(t=>t!=="enabled"&&t!=="colorRanges"&&e[t]!==void 0);}function Zd(e){return(e==null?void 0:e.enabled)===!1||(e==null?void 0:e.enabled)==="false";}function el(e){const t=e.card,a=t.preferences;if(!a)return;const s=a.kpiVisualOptions,i=le(s==null?void 0:s.formatOptions)?s.formatOptions:void 0,n=a,l=le(n.formatNumber)?n.formatNumber:void 0,c=i?bt(ln(i)):void 0,u=l&&Xd(l)?bt(cn(l)):void 0;if(t.type==="kpi"){if(Zd(l)&&e.unconverted.push({path:"preferences.formatNumber.enabled",reason:"raw_display",detail:"Formatting is switched off on this KPI."}),Ld(t)){const r=c??u,p=s==null?void 0:s.queryComparisonPolarity;(r||p)&&(a.sqlKpiValue={...a.sqlKpiValue,...(r?{format:r}:{}),...(p?{comparisonPolarity:p}:{})},e.changes.push({path:c?"preferences.kpiVisualOptions.formatOptions":"preferences.formatNumber",action:"moved",to:"preferences.sqlKpiValue"}));}else pe(t,"metricColumns").forEach(p=>{c?Mt(e,p,c,"preferences.kpiVisualOptions.formatOptions"):u&&!p.format&&Mt(e,p,u,"preferences.formatNumber");});tl(e,l);}else if(u){const r=pe(t,"metricColumns");Oi(t)?e.unconverted.push({path:"preferences.formatNumber",reason:"sql_card_wide_format",detail:"A card-wide number format on a SQL or Python card."}):!ba(t)&&t.type!=="matrixTable"&&r.some(p=>!p.format)&&e.unconverted.push({path:"preferences.formatNumber",reason:"chart_card_wide_format",detail:"A card-wide number format on a chart measure without a format of its own."});}if(!l&&De(n,"formatNumber")&&(delete n.formatNumber,e.changes.push({path:"preferences.formatNumber",action:"removed"})),l){const r=l.colorRanges;Array.isArray(r)&&r.length>0?n.formatNumber={colorRanges:r}:delete n.formatNumber,e.changes.push({path:"preferences.formatNumber",action:"removed"});}s&&nt(s,["formatOptions","queryComparisonPolarity"])&&(e.changes.push({path:"preferences.kpiVisualOptions.formatOptions",action:"removed"}),Object.keys(s).length===0&&delete a.kpiVisualOptions);for(const r of["numberAxisFormat","columnSettings"])nt(a,[r])&&e.changes.push({path:`preferences.${r}`,action:"removed"});}function tl(e,t){var n;const a=t==null?void 0:t.decimalPlaces,s=e.card.preferences;if(typeof a!="number"||((n=s.comparisonPresentation)==null?void 0:n.precision)!==void 0)return;const i=In(a);i!==void 0&&(s.comparisonPresentation={...s.comparisonPresentation,precision:i},e.changes.push({path:"preferences.formatNumber.decimalPlaces",action:"moved",to:"preferences.comparisonPresentation.precision"}));}const al=/* @__PURE__ */new Set(["number","currency","percent","scientific","date","duration"]);function sl(e){const t=e.card.preferences;if(t)for(const a of qd){const s=t[a];if(!le(s))continue;const i=`preferences.${a}`,n=le(s.formatOptions)?s.formatOptions:void 0,l=a==="dataLabelsConfig"&&typeof s.format=="string"?s.format:void 0,c=s.formatMode==="override"||s.formatMode==="inherit"?s.formatMode:s.mode==="override"||s.mode==="inherit"?s.mode:void 0,u=c??(l==="none"?"raw":l&&l!=="auto"||n?"override":"inherit");if(u==="raw"||c===void 0&&l==="none")e.unconverted.push({path:`${i}.format`,reason:"raw_display",detail:"Data labels show raw values."});else if(u==="override"){const r=n&&n.type?n:l&&al.has(l)?{...n,type:l}:n,p=r?bt(un(r,{preserveOmittedProperties:!0})):void 0;p&&(s.valueFormat=p,e.changes.push({path:`${i}.formatOptions`,action:"moved",to:`${i}.valueFormat`}));}nt(s,["formatMode","mode","formatOptions",...(a==="dataLabelsConfig"?["format"]:[])])&&e.changes.push({path:`${i}.formatMode`,action:"removed"});}}function il(e){var s;const t=(s=e.card.config)==null?void 0:s.matrix,a=le(t)&&le(t.presentation)?t.presentation:void 0;if(a)for(const i of["measureFormats","levelFormats"]){const n=a[i];if(le(n))for(const[l,c]of Object.entries(n)){const u=Na(c);u&&!et(u,c)&&(n[l]=u,e.changes.push({path:`config.matrix.presentation.${i}[${JSON.stringify(l)}]`,action:"cleaned"}));}}}function ol(e,t={}){const a={card:structuredClone(e),changes:[],unconverted:[]};for(const s of Ea)pe(a.card,s).forEach((i,n)=>{le(i)&&Bd(a,i,s,`config.${s}[${n}]`);});return Kd(a),zd(a),el(a),sl(a),il(a),jd(a,t),a.changes.length===0&&a.unconverted.length===0?{card:e,changes:[],unconverted:[]}:a;}const nl="__semaphor_unassigned_trigger__",rl="__NULL__";function dl(e){var t,a;return!!((t=e.sql)!=null&&t.trim()||(a=e.python)!=null&&a.trim());}function ll(e){const t=e.config;return t?e.type==="detailTable"?t.detailColumns??[]:[...(t.detailColumns??[]),...(t.metricColumns??[]),...(t.groupByColumns??[])]:[];}function qs(e){return[e.id,e.alias,e.name,e.qualifiedFieldName,e.label];}function cl(e,t){var r,p;const a=((r=e.config)==null?void 0:r.metricColumns)??[],s=((p=e.config)==null?void 0:p.pivotByColumns)??[];if(a.length!==1||s.length!==1)return{reason:"pivot_key_form"};const i=a[0],n=s[0],l=i.aliasTemplate??"",c=l.includes(`{{${n.name}}}`)||l.includes(`{{${n.entityName}.${n.name}}}`),u=!!(i.valueAliases&&Object.keys(i.valueAliases).length);return c||u||/["'`\t\n\r]/.test(t)||t.startsWith("col_")?{reason:"pivot_key_form"}:{ref:{kind:"pivot",metricId:i.id,members:[{fieldId:n.id,value:t===rl?null:t}]}};}function ul(e,t){var l,c;if(t===nl)return{reason:"unassigned_trigger"};if(dl(e))return{ref:{kind:"result",key:t}};const a=ll(e),s=a.filter(u=>qs(u).includes(t)),i=s.length?s:a.filter(u=>qs(u).some(r=>(r==null?void 0:r.trim().toLowerCase())===t.trim().toLowerCase())),n=[...new Set(i.map(u=>u.id))];return n.length===1?{ref:{kind:"field",fieldId:n[0]}}:n.length>1?{reason:"ambiguous_column"}:(c=(l=e.config)==null?void 0:l.pivotByColumns)!=null&&c.length?cl(e,t):{reason:"no_matching_column"};}function Ls(e,t,a,s,i){const n=(Y,R,E)=>{s.push({ruleId:e.id,name:e.name,enabled:e.enabled!==!1,path:`${a}.${Y}`,reference:R,reason:E});},l=e.condition.columnId??"",c=t(l);if(!("ref"in c))return n("condition.columnId",l,c.reason);const u=e.target.level,r=u==="row"?e.target.applyToColumnIds:e.target.columnIds;if(u==="cell"&&!(r!=null&&r.length)&&e.enabled!==!1)return n("target.columnIds","","every_column");const p=[];for(const[Y,R]of(r??[]).entries()){const E=t(R);if(!("ref"in E))return n(`target.${u==="row"?"applyToColumnIds":"columnIds"}[${Y}]`,R,E.reason);p.push(E.ref);}const{columnIds:b,applyToColumnIds:w,conditionColumnId:g,matrix:S,rowRoles:k,depth:A,includeTotals:I,includeSubtotals:F,...y}=e.target,{columnId:V,...D}=e.condition,O={...y,...(p.length?{columns:p}:{}),...(i?{...(S!==void 0?{matrix:S}:{}),...(k!==void 0?{rowRoles:k}:{}),...(A!==void 0?{depth:A}:{}),...(I!==void 0?{includeTotals:I}:{}),...(F!==void 0?{includeSubtotals:F}:{})}:{})};return{...e,condition:{...D,column:c.ref},target:O};}function fl(e,t){var i;const a=(i=Ws(e))==null?void 0:i.value;if(!a)return[];const s=n=>n===null?0:typeof n=="number"||typeof n=="string"||typeof n=="boolean"?Number(n):NaN;return t.flatMap((n,l)=>{if(!n||typeof n!="object")return[];const{start:c,end:u,color:r}=n,p=s(c),b=s(u);if(Number.isNaN(p)||Number.isNaN(b)||p>b||p===1/0||b===-1/0)return[];const w=p===-1/0?void 0:p,g=b===1/0?void 0:b,S=w!==void 0&&g!==void 0?{kind:"between",column:a,min:w,max:g,inclusive:!0}:w!==void 0?{kind:"comparison",column:a,operator:"gte",value:w}:g!==void 0?{kind:"comparison",column:a,operator:"lte",value:g}:{kind:"blank",column:a,isBlank:!1},k=typeof r=="string"?r:"";return[{id:`kpi-color-range-${l+1}`,condition:S,target:{level:"cell"},style:{textColor:k}}];}).reverse();}function hl(e){var p,b,w,g,S,k,A;const t=structuredClone(e),a=[],s=[],i=[],n=I=>{a.some(F=>F.from.startsWith(I))||a.push({ruleId:"",action:"removed",from:I});},l=(p=t.preferences)==null?void 0:p.tablePrefs;if(l&&De(l,"conditionalFormatting")){const I=l.conditionalFormatting,F="preferences.tablePrefs.conditionalFormatting",y=t.type==="table"||t.type==="detailTable";((I==null?void 0:I.rules)??[]).forEach((V,D)=>{var Y;if(!y||((Y=V.target)==null?void 0:Y.matrix)!==void 0){a.push({ruleId:V.id,action:"removed",from:`${F}.rules[${D}]`});return;}const O=Ls(V,R=>ul(t,R),`${F}.rules[${D}]`,s,!1);O&&(i.push(O),a.push({ruleId:V.id,action:"moved",from:`${F}.rules[${D}]`}));}),delete l.conditionalFormatting,s.some(V=>V.path.startsWith(F))||n(F);}const c=(w=(b=t.config)==null?void 0:b.matrix)==null?void 0:w.presentation;if(c&&De(c,"conditionalFormatting")){const I=c.conditionalFormatting,F="config.matrix.presentation.conditionalFormatting",y=new Set((S=(g=t.config)==null?void 0:g.matrix)==null?void 0:S.spec.measures.map(V=>V.id));((I==null?void 0:I.rules)??[]).forEach((V,D)=>{const O=Ls(V,Y=>y.has(Y)?{ref:{kind:"matrixMeasure",measureId:Y}}:{reason:"no_matching_column"},`${F}.rules[${D}]`,s,!0);O&&(i.push(O),a.push({ruleId:V.id,action:"moved",from:`${F}.rules[${D}]`}));}),delete c.conditionalFormatting,s.some(V=>V.path.startsWith(F))||n(F);}const u=t.preferences,r=u==null?void 0:u.formatNumber;if(r&&De(r,"colorRanges")){const I=Array.isArray(r.colorRanges)?r.colorRanges:[];if(t.type==="kpi"){const F=fl(t,I);i.push(...F),F.forEach(y=>a.push({ruleId:y.id,action:"moved",from:"preferences.formatNumber.colorRanges"}));}delete r.colorRanges,Object.keys(r).length===0&&delete u.formatNumber,a.some(F=>F.from==="preferences.formatNumber.colorRanges")||a.push({ruleId:"",action:"removed",from:"preferences.formatNumber.colorRanges"});}if(!a.length&&!s.length)return{card:e,changes:[],unresolved:[]};if(i.length){const I=((A=(k=t.preferences)==null?void 0:k.conditionalFormatting)==null?void 0:A.rules)??[],F=new Set(I.map(y=>y.id));t.preferences={...t.preferences,conditionalFormatting:{version:1,rules:[...I,...i.filter(y=>!F.has(y.id))]}};}return{card:t,changes:a,unresolved:s};}function jl(e,t={}){const{only:a,...s}=t,i=a==="rules"?void 0:ol(e,s),n=a==="formats"?void 0:hl((i==null?void 0:i.card)??e);return{card:(n==null?void 0:n.card)??(i==null?void 0:i.card)??e,formats:i,rules:n};}function Kl(e){return e.kind==="metric"?e.resultId:e.measureId;}function ml(e){if(e.op==="dashboard.update"||e.op==="dashboard.style"||e.op==="sheet.update")return!0;if(e.op!=="card.update")return!1;switch(e.update.kind){case"relabel":return!0;case"settings":return e.update.settings.totals===void 0&&e.update.settings.trend!==!0&&e.update.settings.trendGrain===void 0;default:return!1;}}function Wl(e){return e.impact.length||e.detaches?"needed":e.operations.length>0&&e.operations.every(ml)?"not_needed":"needed";}export{Ql as AGGREGATES,Hl as AUTOMATIC_FALLBACK_GRAIN,Yl as AUTOMATIC_TEMPORAL_BUCKET_FORMAT,jo as AUTOMATIC_TIME_GRAIN,Jl as CALCULATED_FIELDS_GROUP_ID,zl as CALCULATED_FIELDS_GROUP_NAME,Xl as CALCULATION_CHANGE_OPS,Zl as CARD_CONFIG_KEY_CLASSES,ec as CARD_FIELD_SHELVES,tc as CARD_FILTER_FOLDER_ROLES,ac as CARD_KEY_CLASSES,Qo as CARD_QUERY_CONFIG_KEYS,ob as CARD_QUERY_REQUEST_DESCRIPTIVE_FIELDS,nb as CARD_QUERY_REQUEST_EXECUTED_FIELDS,sc as CARD_SURFACES,ic as CARD_TYPES,ct as CARD_TYPE_RULES,_t as CHART_COLORS_BOUNDS,oc as CHIP_VALUE_COLUMN,nc as COLUMN_KEY_CLASSES,rc as COLUMN_PRESENTATION_KEYS,dc as COMPARISON_POLARITIES,Hb as COMPARISON_SIGN_WORDS,lc as CONTROL_BINDING_MAPPING_MISSING_ERROR_CODE,cc as CONTROL_BINDING_TARGET_INVALID_ERROR_CODE,uc as CONTROL_BINDING_VALUE_INVALID_ERROR_CODE,fc as CONTROL_CONTEXT_UNSUPPORTED_ERROR_CODE,hc as CONTROL_DEFINITION_DUPLICATE_ERROR_CODE,mc as CONTROL_DEFINITION_INVALID_ERROR_CODE,pc as CONTROL_PLACEHOLDER_QUOTED_ERROR_CODE,gc as CONTROL_REFERENCE_MISSING_ERROR_CODE,bc as CONTROL_VALUE_INVALID_ERROR_CODE,yc as CONTROL_VALUE_MISSING_ERROR_CODE,vc as CORNER_STEPS,rb as CardQueryRequestError,$c as ControlResolutionError,wc as DASHBOARD_CHANGE_OPS,Ic as DASHBOARD_DEFAULT_OPTION_DEPENDENCIES,Yb as DASHBOARD_FILTER_OPERATIONS,_c as DASHBOARD_INPUT_RUNTIME_SCOPE_KINDS,Cn as DASHBOARD_STYLE_NUMBER_BOUNDS,Cc as DEFAULT_DETAIL_DATE_STYLE,Sc as DETAIL_BACKUP_SHELVES,xc as DETAIL_DATE_STYLES,Jb as DOCUMENT_KPI_SECTION_MAX_CARDS,zb as DOCUMENT_KPI_SECTION_MAX_TILES,kc as DOMAIN_EDIT_CHANGE_OPS,Tc as DYNAMIC_TEXT_MESSAGE,Fc as DashboardFilterMappingContractError,Ac as ExecutionControlContractError,Rc as FILTER_OPERATORS,rs as FORMAT_WORDS,Dc as FilterModelError,Oc as KPI_MEASURES_SHOWN,t$ as KPI_TREND_GRAINS,a$ as KPI_TREND_PERIODS,Ec as LEGACY_TABLE_CARD_TYPES,Ky as LEGACY_TABLE_ROUTING_ID_NAMESPACE,Nc as MATCH_WEEKDAYS_ONLY_BY_YEARS,ms as MAX_CREATE_CHANGES,Pc as MAX_DATE_GRAIN_POINTS,qc as MAX_NEXT_STEP_CHARS,Zo as MAX_PROPOSED_CHANGES,Lc as MAX_QUERY_LIMIT,Mc as MAX_TEXT_WORDS,Vc as MEASURE_CALCULATION_SUMMARIES,yv as NEW_CARD_TYPE,Bc as NON_ADDITIVE_SUM_OF_ROWS_HINT,jc as NUMBER_CONDITION_GROUPS,Kc as NUMBER_CONDITION_SPECS,Wc as PUBLIC_TRANSFORM_KIND,Uc as QUERY_ASPECTS,Gc as QUERY_CONFIG_KEY_ASPECTS,vv as RELATIONSHIP_ROUTE_CHANGED_MESSAGE,Qc as RESERVED_VARIABLE_NAMES,Hc as SEE_RECORDS_CARD_TYPES,Yc as SEE_RECORDS_LIMITS,Jc as SEE_RECORDS_MAX_PAGE,$v as SEE_RECORDS_MESSAGES,zc as SEMAPHOR_CARTESIAN_CHART_TYPES,Xc as SETTINGS_BY_KIND,o$ as SHELF_FIELD_KEYS,Zc as SPACING_STEPS,eu as TABLE_SHEET_CARD_TYPES,tu as TIME_GRAINS,au as TOOLBAR_FILTER_REACH_FIELDS,su as TO_DATE_IS_AUTOMATIC,Xs as UNREADABLE_CARD_TAKES,Xb as VARIABLE_CARD_TYPE,Zb as VARIABLE_COMPARISON_PARTS,iu as VARIABLE_GETS,ey as VARIABLE_LIST_CAP,ty as VARIABLE_LIST_SHOWN,ou as VARIABLE_NAME_PATTERN,ay as VARIABLE_VALUE_PART,nu as WINDOW_ERROR_CODES,ru as WINDOW_WARNING_CODES,du as acceptedColumnRefKinds,lu as acceptsGrainThatRan,cu as addCalculatedField,db as addCardJoin,uu as adoptCalculatedFields,fu as analyticsFilterSchema,hu as appliedBindingControlValue,mu as applyCalculatedFieldOperation,Wy as applyCardReferenceRemapping,pu as applyCardSettings,pt as applyDashboardOperations,gu as applyFilterApplicability,wv as applyFilterSettingsChange,Uy as applyGroupByOverride,bu as applyLinkedClickToFilterOverrides,yu as applyMeasureCalculations,vu as applyOptionDependencyOverride,$u as applyVariableChange,wu as asDateDefaultPointCondition,Iu as automaticDateGrain,Ko as automaticGrainSupport,_u as blockClause,Cu as blockSentence,u$ as bookmarkImpactSentence,Su as buildCalculatedFieldDefinition,Iv as buildCardExportFormatOptions,Gy as buildCardExportQueryContext,_v as buildCardExportRequest,Cv as buildCardExportRequestFromOptions,xu as buildCardFilterDefinition,Sv as buildCardRecordsCsv,lb as buildColumnCatalog,ku as buildControlDefinitionIndex,Eo as buildDashboardCardSourceIndex,cb as buildEntityColumnGroup,xv as buildFilterInputFromDefinition,ri as buildFilterInputFromField,Tu as buildLinkedClickToFilterOverrides,Fu as buildMetricInputFieldsForExpression,Au as buildProposeChangeInputSchema,kv as buildRecordsCsv,Ru as buildSavedEditorCard,Tv as buildTableExportFormatOptions,Fv as buildTableFileCsv,Du as calculatedColumnMatchesField,Ou as calculatedFieldDomainId,Do as calculatedFieldInUseMessage,Eu as calculatedFieldListOperations,an as calculatedFieldSemanticSource,Js as calculatedFieldUsage,Nu as calculationAddSchema,Pu as calculationChangeSchemas,qu as calculationRemoveSchema,Lu as calculationUpdateSchema,Mu as calculationsRemovedWords,Ht as canShowAsRange,qo as cardBaseEntity,Vu as cardBaseSource,Av as cardColumnRefForKey,Bu as cardColumnRefSchema,on as cardConditionalFormattingSchema,ju as cardConfigAsRan,Ku as cardFieldFolders,Wu as cardFieldsInPlaces,Uu as cardQueryPatchSchema,Gu as cardReachesDatasetThroughRelationships,Qu as cardReadsOnlyOwnJoins,Hu as cardSelectedEntities,Xi as cardSettingsKind,Ji as cardTypeSentenceName,Yu as carryColumnSettings,Ho as changeCardType,Ju as changeMatrixEditor,zu as checkCalculatedColumnDefinitions,Xu as checkCalculatedFieldList,nn as checkConditionalRuleColumns,_a as checkDataVariable,Zu as checkDetailDateFormat,Bl as checkPresentationStores,ef as checkSheetShapes,tf as chipOverVariable,af as classifyCalculatedColumn,sf as clearedCardShelves,of as clickToFilterSettingsSchema,nf as collectJoinPlanIdentifiers,ii as collectVariableReferences,rf as columnConditionalRules,va as columnDataset,Nt as columnFieldKey,ti as columnKeys,df as columnRefIssue,ns as columnRefKey,lf as columnSettingsInputSchema,cf as comparesMetricPair,sy as comparisonPartPresentation,Co as comparisonShiftSchema,ub as comparisonSortLabel,Qy as composeCardReferenceRemapping,uf as conditionalRuleSchema,Wl as confirmClassFor,ff as contextChangeSchema,hf as controlBindingExecutionSchema,mf as controlDefinitionExecutionSchema,Fo as controlRefusal,Pl as convertLegacyStyle,pf as createCalculatedDimension,gf as createCalculatedField,bf as createDashboardFilterBindingId,uv as createMatrixAuthoringDraft,fv as createMatrixConfig,Fn as createNewCard,yf as createTargetSchema,Tn as createTextCard,vf as customDetailDateFormat,$f as customGroupedDateFormat,wf as dashboardCardFilterSourceInventoryContains,_o as dashboardChangeSchema,If as dashboardCopiesOn,Oo as dashboardFieldFromCompiled,_f as dashboardFilterTargetMatchesLogicalValue,iy as dashboardFilterValueTypeForDataType,yn as dashboardInputScopeIncludesDocumentSheets,cr as dashboardStyleAsEdit,Cf as dashboardStyleChangeSchema,ai as dashboardStyleLayers,Sf as dateDefaultPointCondition,xf as decideClickToFilterCardLevel,kf as decideClickToFilterField,Tf as defaultClickToFilterSettings,Xn as defaultVariableGet,n$ as defaultVariableName,f$ as describeBookmarkImpact,Ff as describeDashboardFilterCardReach,Xe as describeDashboardFilterCardReachDetail,Rv as describeDateWindow,Dv as describeFilterReachEntry,Ov as describeKpiDateSection,Ev as describeKpiTileDate,s$ as describeKpiTrendRow,Af as describeMeasureCalculations,Rf as describeNumberCondition,Df as describeNumberConditionDefault,To as describeQueryChange,Nv as describeRelationshipRoute,Rn as describeRelationshipSkip,Of as describeTableColumnTotal,Ef as detailDateDisplayFormat,Nf as detailDateFormatProblem,Pf as detailDateTwelveHourAvailable,oy as documentInputTextUsage,ny as doesDashboardInputApplyToTarget,ry as doesDashboardInputReachFilterTarget,dy as doesDashboardInputSurviveCarriedContext,qf as doesToolbarFilterReachTab,fb as domainCalculatedFields,Lf as domainEditChangeSchema,Mf as domainEditChangeSchemas,r$ as draftBlocker,hb as draftFromJoin,Zn as draftFromVariable,Vf as drawsDetailDatesInBrowser,Bf as dropMatrixEditorField,m$ as editBrandStyle,kn as editDashboardStyle,Pv as encodeTableExportCsv,jf as estimateDateGrainPoints,Kf as evaluateConditionalRules,Wf as explicitComparisonSchema,Uf as fieldAsRan,Gf as fieldDatasets,Qf as fieldFolderTree,go as fieldIdentityKey,Hf as fieldRef,Yf as fieldRefSchema,Jf as fillFrameSemanticCardDomains,zf as fillSemanticCardDomain,Xf as fillSemanticCardDomains,Zf as filterApplicabilityContextForCard,mb as filterFieldCalculatedCandidates,pb as filterFieldCatalog,gb as filterFieldFolders,bb as filterFieldReachCard,yb as filterFieldReachCards,vb as filterFieldTables,$b as filterFieldTrees,wb as filterFolderDataSource,Ib as filterFolderKey,_b as filterFolderPlacement,Cb as filterReachCount,gr as filterReachInput,Sb as filterReachLine,br as filterReachOnCard,qv as filterReachPreviewAnswers,eh as filterValueReachForCard,th as filterValueSemanticDataset,xb as filterableCards,ah as findBorrowedSelectionBinding,Vt as findCatalogField,sh as findDashboardCardExecutableSource,ih as findDashboardCardPinnedCatalogSource,xa as findDashboardFilterTarget,oh as findDashboardSqlPinnedCatalogSource,Ai as findRetiredCardPresentationFields,Vl as findRetiredPresentationFields,Gs as findSortedColumn,kb as flattenEntityColumns,nh as foldPrototypeDocumentInputs,rh as folderParentHintFromJoin,dh as folderParentHintFromStep,lh as formatFilterModelIssues,ch as formatResolvedPrimaryDateFieldIssues,uh as formatSkippedFilterWarnings,fh as fromEditableRules,hh as getCalculatedFieldAggregateOverrides,mh as getCalculatedFieldComparableKey,Rt as getCalculatedFieldIdentityKey,ph as getCalculatedFieldNamespace,gh as getCalculatedFieldParameters,bh as getCalculatedFieldShelfOverrides,yh as getCardDefinition,Lv as getClickContextFromTable,vh as getColumnCatalogFieldId,$h as getDashboardFilterSubscriptionHint,wh as getDashboardGlobalDateFilter,ly as getDocumentKpiSectionShapeIssues,cy as getDocumentSectionCards,Ih as getDomainCalculatedSelectionOverrides,_h as getFieldAggregationOptions,Ch as getMatrixBindingTargets,hv as getMatrixLevelLabel,mv as getMatrixMeasureLabel,Sh as getStableDomainCalculatedFieldId,xh as getTemporalBucketAuthoringOptions,kh as getTemporalBucketAuthoringSelection,Th as grainChoicePatch,Fh as grainControlApplies,Ah as groupedDateDisplayFormat,no as groupedDateDisplayPatterns,Rh as handleSchema,Dh as hasDashboardFilterSubscription,Mv as hasSeeRecordsMeasureFilter,De as hasStoredKey,Oh as hasTextCardRichWords,Eh as hasToolbarFilterReachField,Hy as hostFilterValueFor,Yy as hostFilterValuesToSlots,Nh as indexOfToken,Ph as indexTypedTokens,qh as inferSemanticDomainIdFromSelectedEntities,Lh as initialNumberFilterSearchMode,Mh as inputScopeKindOf,Vh as inspectMatrixCardConfig,Jy as isAdHocFilterValueOnTab,$s as isAggregateGet,Bh as isAllowedDashboardInputScopeCombination,jh as isCalculatedColumn,Ro as isCalculatedFieldInUse,Kh as isCardType,Wh as isCompleteOwnedFilter,uy as isDashboardFilterOperationCompatible,si as isDashboardInputOnTab,fy as isDashboardInputOwnedBySheet,hy as isDashboardInputScopeEmpty,my as isDashboardTargetIdTaken,Uh as isDatabaseEntityReference,Vs as isFilterCardReached,Ca as isGridSheet,Gh as isGroupedDate,oo as isGroupedTimeGrain,Qh as isLegacyTableCard,Bi as isNumberConditionOperation,Hh as isPresentationCurrencyBinding,Yh as isSeeRecordsCardType,Jh as isSemanticAutoJoinCard,zh as isSemaphorCartesianChartType,mn as isSqlKpi,Xh as isStructuralControlBinding,Yt as isTableSheet,xo as isTableSheetCardType,Zh as isTextCardRichContent,em as isValidControlOptionPresentation,py as isVariableComparisonPart,tm as isWhenRun,am as joinEntityName,sm as joinEqualityPairs,Tb as joinFromDraft,Fb as joinMatches,Ab as joinTableReference,Rb as joinTargetRefusal,im as kpiSegmentMetricId,om as kpiShowsTrend,Yi as kpiTrendBy,Vv as kpiTrendByHint,po as labelAt,nm as layoutArrangeSchema,zy as legacyTableRoutingIds,Xy as legacyTableRoutingTarget,rm as linkedClickToFilterOverridesSchema,Zy as listAdHocFilterValuesOnTab,we as listDashboardCardLocations,dm as listDashboardFilterDefinitions,lm as listDashboardFilterInputsOnTab,Sa as listDashboardFilterTargets,gy as listDashboardInputReachKeys,gn as listDashboardInputScopeExceptedCardIds,bn as listDashboardInputScopeExceptedSheetIds,cm as listDashboardInputsTolerantly,ka as listDashboardTabTargets,by as listDataVariablePlaces,ev as listFilterInputValueTargets,yy as listFilterTargetScopeTargets,vy as listReachedVariableTargets,$y as listReferencedDataVariableIds,um as listStoredFilterDefinitions,wy as listVariableScopeTargets,fm as mapCardFieldPlaces,Iy as mapDashboardCards,_y as mapDocumentSectionCards,hm as mapFormulaTokens,mm as mapRuleColumns,pm as matchColumns,tv as matrixCatalogSources,zo as matrixColumnKeys,gm as matrixColumnsSchema,bm as matrixDefinitionFieldRefs,ym as matrixDefinitionFields,vm as matrixDefinitionSources,$m as matrixEditorCatalogFromFields,av as matrixExecutionSources,wm as measureCalculationOptions,Im as measureComparisonSchema,_m as measureKeepsBareInputs,Cm as measureRefSchema,Sm as measureStageOnEdit,xm as measureTransformSchema,pv as mergeMatrixSorts,Vo as metricCardQuerySchema,Jo as moveMatrixLevel,d$ as newVariableDraft,l$ as newVariableId,km as normalizeCalculatedFieldId,Tm as normalizeClickToFilterSettings,Fm as normalizeDashboardInputs,Am as normalizeLegacyLinkedTargetOverrides,Rm as numberConditionProblem,Dm as numberConditionSpec,mo as numberConditionSpecForAgent,Om as occurrenceKeys,qt as outlineCalendar,Ml as outlineDashboard,Ve as outlineFilter,Ra as outlineFilters,wr as outlinePinnedFilters,Jt as ownsItsAggregate,Db as parseCardQueryRequest,Ob as parseCardQueryRequestContext,Eb as parseCardQueryRequestExtras,Em as parseColumnRefKey,Nb as parseDashboardStyle,Nm as parseExecutionControlBindingsShallow,Pm as parseExecutionControlContext,qm as parseExecutionControlContract,Wo as placeDashboardFieldCopies,Lm as placedFieldLabel,us as planCardLabels,cs as planCardRequery,Bv as pluralDatasetLabel,sv as prepareLoadedDashboard,Mm as previewTemporalBucketAuthoringFormat,Cy as projectDataVariableToCard,Vm as pruneCardFields,Bm as pruneUnrelatedCalculatedFilters,Ao as queryForm,jm as queryMeasureSchema,Km as reachedDatasetEntity,Zs as readAgentNumberConditionDefault,Wm as readBraceSpans,zs as readCalculatedFieldDefinition,Um as readCardConditionalRules,Le as readCardQuery,$a as readCardSettings,Pe as readCardSource,ze as readCardTypeProperties,Pb as readComparisonDates,Ie as readDashboardFilterModel,qb as readDefaultComparisonDates,Gm as readDetailDateChoice,Qm as readExactDomainCalculatedFieldReference,Lb as readFilterFieldReachResponse,jv as readFilterReachResponse,iv as readFilterValueList,Hm as readFormulaTokens,Ym as readGroupedDateChoice,Kv as readKpiDateContext,Jm as readKpiFigure,zm as readKpiNumber,Xm as readMatrixCardConfig,Zm as readMeasureCalculations,ep as readNumberConditionDefault,ca as readNumberFilterShowAs,tp as readSqlFilterUse,ap as readStoredComparison,sp as readStoredTransform,Mb as readTableViewerSwitch,ei as readTextCardWords,Pt as readTextWords,ip as readTransform,Sy as readVariableAnswer,Ii as readVariableEditability,ma as readVariableSource,tn as readablePresentation,op as rebindDashboardOptionDependencyInputId,ls as rebuildsRole,np as reconcileMatrixSpecStructure,rp as reconcileTemporalBucketAuthoringFormat,Mo as recordsCardQuerySchema,wo as refDataset,Re as refKey,it as refName,dp as refusalOfCalculatedFieldOperations,lp as registeredCalculationChangeSchemas,cp as registeredDomainEditChangeSchemas,up as relationshipAddSchema,fp as relationshipRouteTarget,hp as remapClickToFilterReferences,mp as remapLinkedClickToFilterOverrides,pp as removeCalculatedField,Vb as removeCardJoin,Li as requireNormalizedDashboardInputs,gp as resolveBindingControlValue,Xo as resolveCalculatedFieldName,xy as resolveCanonicalDetailResultRawKey,ky as resolveCanonicalResultOutputKey,wn as resolveCanonicalResultOutputKeys,Ty as resolveCanonicalResultRawKey,Wv as resolveCardColumnRef,bp as resolveCardFieldCopies,Br as resolveCardSettings,Uv as resolveConditionalRules,ql as resolveDashboardChanges,Ll as resolveDashboardCreate,yp as resolveDashboardEntitySource,vp as resolveDashboardFieldCopies,$p as resolveDashboardFieldCopiesIn,wp as resolveDashboardFilterAutomaticTarget,Ip as resolveDashboardFilterInheritedTarget,_p as resolveDashboardOptionDependencies,Cp as resolveDashboardOptionPopulation,Sp as resolveDashboardSqlFilterTarget,On as resolveDashboardStyle,Gv as resolveDashboardTemporalPresentation,xp as resolveDatasetName,kp as resolveDetailTableRawTemporalPresentation,Fy as resolveDistinctDetailRawKeys,Tp as resolveFieldSelectedSource,Fp as resolveGroupByFieldTarget,Ap as resolveKpiLayout,Ws as resolveKpiShape,Rp as resolveKpiValueStyle,ov as resolveMatrixControlBindings,gv as resolveMatrixDefinition,ds as resolveMeasureCalculations,Dp as resolveMeasureTransform,Op as resolveMetricFieldTarget,Ep as resolveScalarMappedValue,Np as resolveTableColumnTotal,Pp as resolveTemporalBucketAuthoringFormat,qp as resolveTemporalResultOwner,fs as resolveTextCardWords,Lp as resolveValueStyle,Mp as respondsToSelectionsSchema,Vp as retainConditionalRules,Bp as retainedMatrixPath,Ay as rewriteDashboardInputScopeIds,jp as rewriteFieldMeta,nv as routeLegacyTableCard,rv as routeLegacyTableCards,dv as routeLegacyTableFrame,Kp as sameBaseEntity,Dt as sameColumnKey,Wp as sameSource,Up as sameWords,Gp as sanitizeTextCardUrl,Qv as seeRecordsAvailability,Hv as seeRecordsCardAvailability,Kl as seeRecordsMeasureId,Yv as seeRecordsMeasureKind,Jv as seeRecordsReasonHidesOffer,Qp as seeRecordsRequestSchema,zv as seeRecordsRowField,Hp as selectDashboardOptionDependencyInputIds,Yp as selectionFieldFromExplorerField,Xv as selectionTupleFromClickContext,Jp as semanticDomainIdsOfSelectedEntities,Bb as setMeasureCalculations,zp as settableCardType,Xp as sharedCardPreferences,Zp as sharedTableDialect,eg as sheetChangeSchemas,en as sheetKindOf,tg as simulateCalculatedFieldOperations,pn as sortCanRankByChange,Lo as sqlCardQuerySchema,ag as sqlKpiResultKeys,sg as stageChangeRefusal,jb as startCardOver,ig as statedCardBaseEntity,mt as statedLabelsOf,Ki as storedCardTypeFor,og as storedRunPresentation,Ry as storedTextRefs,ng as stripInstanceTargetsForLibrarySave,rg as structuralControlOverride,Kb as suggestJoinCondition,mi as summarizeFilter,dg as supportsCanonicalDashboardTemporalResult,lg as supportsMetricTransform,cg as switchCardBase,ug as tabChangeSchemas,fg as tableColumnTotalLabel,hg as tableSheetCard,Wb as tableViewerSwitches,mg as textCardExcerpt,pg as textCardWordingClauses,ua as textCatalogAt,ji as toAgentNumberConditionDefault,At as toChartType,gg as toEditableRules,bg as toFiniteKpiNumber,yg as toIndexedTokens,vg as toNamedTokens,Ft as toPublicCardType,Io as toStoredComparison,$g as toolbarFilterInputFields,wg as toolbarFilterScope,Ig as transformComparisonDocument,_g as transformGroupings,Cg as transformOrderSchema,Sg as updateCalculatedField,Ub as updateCardJoin,Yo as updateMatrixConfig,ol as upgradeCardFormats,jl as upgradeCardPresentation,hl as upgradeConditionalFormatting,lv as upgradeToStoredDashboard,xg as validateAndResolveWindowTransforms,kg as validateControlValue,Dy as validateDashboardFilterValues,Tg as validateNumberConditionDefault,Fg as validateResolvedPrimaryDateFieldShape,Oy as variableCardKeepsComparison,Ey as variableComparison,Ot as variableFromDraft,zn as variableGetOptions,Ny as variablePartCell,Py as variablePartType,$n as variableParts,qy as variableQueryResponseOf,Zv as variableSourceWords,er as variableTakesComparison,Dn as variableWords,Ag as withCardConditionalRules,Rg as withCardConfigSqlDatePatterns,Ly as withCardExcludedFromScope,My as withCardIncludedInScope,Dg as withColumnConditionalRules,Og as withDashboardOptionDependencyOverride,Eg as withDefinitionFormula,Ng as withDetailSqlDatePattern,Vy as withDistinctDetailColumnAliases,By as withDraftCard,Pg as withFolderParents,qg as withFormatOverride,Lg as withGrainChoice,Mg as withReadDatasetsSelected,Vg as withSqlDatePattern,Bg as withStartingGrain,jg as withStoredResultKey,vn as withUnstatedScopeParts,Kg as withoutRemovedFieldCopies,Wg as withoutSqlDatePattern,Ug as withoutToolbarFilterReachFields,Gg as wordingBlocks,Qg as wordingClauses,Hg as writeColumnFormat,Yg as writeColumnPolarity,Jg as writeComparisonDisplay,zg as writeComparisonPresentation,En as writeCustomVisual,Tt as writeDateFilterDefault,Xg as writeDateSelectionMode,Zg as writeInheritComparison,eb as writeInputAggregates,Po as writeNumberConditionDefault,No as writeNumberFilterShowAs,tb as writeSeeRecords,ab as writeTableColumnFilters,sb as writeTableSearch,Gb as writeTableViewerSwitch,$o as writeTextWords};