@duckcodeailabs/dql-cli 1.14.1 → 1.14.3-rc.1
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.
- package/dist/args.d.ts +4 -0
- package/dist/args.d.ts.map +1 -1
- package/dist/args.js +16 -0
- package/dist/args.js.map +1 -1
- package/dist/assets/dql-notebook/assets/{AgentLogPage-BPz-UWFh.js → AgentLogPage-Jbyb4so-.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiBuildDialog-BEl53WA_.js → AiBuildDialog-Du07X1qO.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiBuildResult-B4yfGTTZ.js → AiBuildResult-xKtGthWv.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiSidePanel-CSZAAvuD.js → AiSidePanel-CE_L04dK.js} +1 -1
- package/dist/assets/dql-notebook/assets/AnalyticsHome-CiUE10uF.js +6 -0
- package/dist/assets/dql-notebook/assets/{AppsView-DQOwU9Cg.js → AppsView-DlNaTuwD.js} +30 -35
- package/dist/assets/dql-notebook/assets/AskObservabilityPage-DracZPI9.js +1 -0
- package/dist/assets/dql-notebook/assets/AskTracePage-CSMoMw9a.js +8 -0
- package/dist/assets/dql-notebook/assets/{BlockStudio-B4ap0GdY.js → BlockStudio-DQS5Hcq9.js} +9 -14
- package/dist/assets/dql-notebook/assets/BusinessArtifactView-CqV4i9l_.js +1 -0
- package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-D72byb2g.js → DbtFirstModelingPage-JKhB_Y2H.js} +3 -3
- package/dist/assets/dql-notebook/assets/{GitPage-lQb1uXH2.js → GitPage-DjaNp0o3.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GlobalAiRail-CVECf6Xj.js → GlobalAiRail-CsV3zlc8.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GovernedContextPage-trOyMCY6.js → GovernedContextPage-uXUHUOIJ.js} +3 -3
- package/dist/assets/dql-notebook/assets/{HelpDocsPage-D8hLS5lE.js → HelpDocsPage-Hbh9IeYB.js} +1 -1
- package/dist/assets/dql-notebook/assets/{HomePage-eIkfBIep.js → HomePage-CRRl-R_v.js} +1 -1
- package/dist/assets/dql-notebook/assets/LineageDAG-OMUP2sbl.js +1 -0
- package/dist/assets/dql-notebook/assets/LineageDetailView-C964BLuV.js +1 -0
- package/dist/assets/dql-notebook/assets/LineageDrawer-CzY0nfpD.js +1 -0
- package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-CviIf8PN.js → LineagePathBreadcrumb-0Gi-Fm1B.js} +1 -1
- package/dist/assets/dql-notebook/assets/MiniLineageGraph-wn0wLc9m.js +1 -0
- package/dist/assets/dql-notebook/assets/{NewBlockModal-DbCQg-pj.js → NewBlockModal-kMAzk91d.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NewNotebookModal-5Vp6XiuK.js → NewNotebookModal-D_cWd_6M.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NotebookEditor-DjqJS44s.js → NotebookEditor-Bax0lxaz.js} +25 -30
- package/dist/assets/dql-notebook/assets/{ReadinessPage-BHGrC5ho.js → ReadinessPage-DEUIXQQY.js} +1 -1
- package/dist/assets/dql-notebook/assets/{SetupOnboarding-BfS9Tdx-.js → SetupOnboarding-CyE-Ex41.js} +1 -1
- package/dist/assets/dql-notebook/assets/{SkillsPage-BFH21wSj.js → SkillsPage-QgvKGPxE.js} +1 -1
- package/dist/assets/dql-notebook/assets/{TrustBadge-zm6g_SxZ.js → TrustBadge-D5CGp0cu.js} +1 -1
- package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-BjsTE6yf.js +89 -0
- package/dist/assets/dql-notebook/assets/{answer-to-notebook-DPhxIEzF.js → answer-to-notebook-tACdCsTV.js} +1 -1
- package/dist/assets/dql-notebook/assets/{arrow-left-DNEb86Xc.js → arrow-left-CF6wxXU5.js} +1 -1
- package/dist/assets/dql-notebook/assets/{arrow-right-DpPWbwaD.js → arrow-right-C7G3M_S8.js} +1 -1
- package/dist/assets/dql-notebook/assets/{book-open-text-D7s5jo4X.js → book-open-text-DDBO8G7L.js} +1 -1
- package/dist/assets/dql-notebook/assets/chevron-left-DxajrX2v.js +6 -0
- package/dist/assets/dql-notebook/assets/{circle-x-Db3dXKg7.js → circle-x-HBvXjnT6.js} +1 -1
- package/dist/assets/dql-notebook/assets/clock-3-CJIdsPLt.js +6 -0
- package/dist/assets/dql-notebook/assets/dagre.esm-B6nvU4OB.js +1 -0
- package/dist/assets/dql-notebook/assets/{external-link-BxwXitO_.js → external-link-WciAU8Bu.js} +1 -1
- package/dist/assets/dql-notebook/assets/{grip-vertical-Dt4lkWRi.js → grip-vertical-DVu7ok6x.js} +1 -1
- package/dist/assets/dql-notebook/assets/index-B_kaoARS.css +1 -0
- package/dist/assets/dql-notebook/assets/{index-DKo-bwNw.js → index-D3wnucQC.js} +133 -128
- package/dist/assets/dql-notebook/assets/{link-2-Dfo2P6wi.js → link-2-C6uQx50X.js} +1 -1
- package/dist/assets/dql-notebook/assets/{list-tree-DiTmIWAL.js → list-tree-DapsIuQB.js} +1 -1
- package/dist/assets/dql-notebook/assets/{minimize-2-CMTAkPzL.js → minimize-2-BlVoipnT.js} +1 -1
- package/dist/assets/dql-notebook/assets/{panel-right-open-DwYr7FW4.js → panel-right-open-DcnKWxfx.js} +1 -1
- package/dist/assets/dql-notebook/assets/{play-BXhHYQ4x.js → play-CNuRuaAs.js} +1 -1
- package/dist/assets/dql-notebook/assets/{rotate-ccw-BNi6F8pl.js → rotate-ccw-B2p953Zh.js} +1 -1
- package/dist/assets/dql-notebook/assets/{semantic-fields-CNOGysAy.js → semantic-fields-2fWgkTJc.js} +1 -1
- package/dist/assets/dql-notebook/assets/{sliders-horizontal-Ec5MUMUW.js → sliders-horizontal-DwRTu1w4.js} +1 -1
- package/dist/assets/dql-notebook/assets/{star-B9leDkp_.js → star-Cbaj4F3i.js} +1 -1
- package/dist/assets/dql-notebook/assets/style-NlN9F6JE.js +23 -0
- package/dist/assets/dql-notebook/assets/{triangle-alert-BefTYCzx.js → triangle-alert-BPHvH1wA.js} +1 -1
- package/dist/assets/dql-notebook/assets/{upload-SPiOM2tQ.js → upload-DIqK0KE1.js} +1 -1
- package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-C4foXeiQ.js → usePersistedAgentThreadId-DpQXOEDw.js} +1 -1
- package/dist/assets/dql-notebook/assets/{user-round-comGmyw-.js → user-round-DukNupB_.js} +1 -1
- package/dist/assets/dql-notebook/assets/{wand-sparkles-BffR4dF8.js → wand-sparkles-CAwLX0b9.js} +1 -1
- package/dist/assets/dql-notebook/assets/{workflow-ChmPTEzH.js → workflow-bOT-NqdO.js} +1 -1
- package/dist/assets/dql-notebook/assets/{wrench-DovaG_ze.js → wrench-1m0_kcza.js} +1 -1
- package/dist/assets/dql-notebook/assets/{x-nRx91AgW.js → x-fp82BETM.js} +1 -1
- package/dist/assets/dql-notebook/index.html +2 -2
- package/dist/commands/agent-eval-cassette.d.ts +97 -6
- package/dist/commands/agent-eval-cassette.d.ts.map +1 -1
- package/dist/commands/agent-eval-cassette.js +165 -22
- package/dist/commands/agent-eval-cassette.js.map +1 -1
- package/dist/commands/agent-eval-runtime.d.ts +23 -2
- package/dist/commands/agent-eval-runtime.d.ts.map +1 -1
- package/dist/commands/agent-eval-runtime.js +19 -2
- package/dist/commands/agent-eval-runtime.js.map +1 -1
- package/dist/commands/agent-trace.d.ts +3 -0
- package/dist/commands/agent-trace.d.ts.map +1 -0
- package/dist/commands/agent-trace.js +169 -0
- package/dist/commands/agent-trace.js.map +1 -0
- package/dist/commands/agent.d.ts +37 -5
- package/dist/commands/agent.d.ts.map +1 -1
- package/dist/commands/agent.js +534 -84
- package/dist/commands/agent.js.map +1 -1
- package/dist/commands/compile.d.ts +13 -1
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +36 -4
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/notebook.d.ts +2 -0
- package/dist/commands/notebook.d.ts.map +1 -1
- package/dist/commands/notebook.js +4 -0
- package/dist/commands/notebook.js.map +1 -1
- package/dist/commands/sync.d.ts.map +1 -1
- package/dist/commands/sync.js +11 -3
- package/dist/commands/sync.js.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/llm/providers/dql-agent-provider.d.ts +29 -2
- package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
- package/dist/llm/providers/dql-agent-provider.js +1008 -144
- package/dist/llm/providers/dql-agent-provider.js.map +1 -1
- package/dist/llm/types.d.ts +48 -1
- package/dist/llm/types.d.ts.map +1 -1
- package/dist/local-runtime.d.ts +271 -33
- package/dist/local-runtime.d.ts.map +1 -1
- package/dist/local-runtime.js +3658 -546
- package/dist/local-runtime.js.map +1 -1
- package/dist/package.json +10 -10
- package/dist/providers/oauth/claude-oauth.d.ts.map +1 -1
- package/dist/providers/oauth/claude-oauth.js +52 -18
- package/dist/providers/oauth/claude-oauth.js.map +1 -1
- package/dist/providers/oauth/codex-oauth.d.ts.map +1 -1
- package/dist/providers/oauth/codex-oauth.js +72 -44
- package/dist/providers/oauth/codex-oauth.js.map +1 -1
- package/dist/providers/subscription-cli.d.ts +20 -0
- package/dist/providers/subscription-cli.d.ts.map +1 -1
- package/dist/providers/subscription-cli.js +69 -11
- package/dist/providers/subscription-cli.js.map +1 -1
- package/package.json +10 -10
- package/dist/assets/dql-notebook/assets/AnalyticsHome-D5P6Ujwi.js +0 -6
- package/dist/assets/dql-notebook/assets/BusinessArtifactView-BIfNI-0S.js +0 -1
- package/dist/assets/dql-notebook/assets/LineageDAG-CSqcbDrE.js +0 -1
- package/dist/assets/dql-notebook/assets/LineageDetailView-DJZZjZu-.js +0 -1
- package/dist/assets/dql-notebook/assets/LineageDrawer-BcIipIc3.js +0 -1
- package/dist/assets/dql-notebook/assets/MiniLineageGraph-vH_MY_Ju.js +0 -1
- package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel--oxmjlgr.js +0 -88
- package/dist/assets/dql-notebook/assets/dagre.esm-C7pppQ1a.js +0 -23
- package/dist/assets/dql-notebook/assets/index-B3shyZsg.css +0 -1
- /package/dist/assets/dql-notebook/assets/{dagre-BZV40eAE.css → style-BZV40eAE.css} +0 -0
|
@@ -1,25 +1,20 @@
|
|
|
1
|
-
import{c as
|
|
1
|
+
import{c as $o,r as c,j as e,a5 as Ao,h as Ot,i as _o,k as Wo,a6 as Fo,t as qt,a7 as fn,a8 as Oo,a as W,a9 as vt,aa as qo,e as bn,D as vn,T as tn,P as No,S as Lt,f as kt,l as Ho,L as Ze,ab as Qo,ac as Uo,ad as ue,ae as $t,af as At,ag as Ri,ah as Ei,ai as Ko,b as Go,aj as Vo,B as Jt,A as Li,ak as $i,al as Ai,am as Yo,an as Si,ao as Ke,z as Xo,ap as _i,Q as Wi,aq as Zo,ar as Jo,as as er,w as tr,E as hn,x as nr,y as ir,H as ki}from"./index-D3wnucQC.js";import{S as or,a as rr,b as ji}from"./LineagePathBreadcrumb-0Gi-Fm1B.js";import{u as sr,a as lr,T as Fi,b as ar,d as dr,P as cr,E as ur,C as Oi}from"./usePersistedAgentThreadId-DpQXOEDw.js";import{M as pr}from"./MiniLineageGraph-wn0wLc9m.js";import{b as qi,U as fr,B as hr}from"./UnifiedAgentRunPanel-BjsTE6yf.js";import{a as mr,A as gr}from"./AiSidePanel-CE_L04dK.js";import{C as xr}from"./chevron-left-DxajrX2v.js";import{P as Ni,B as yr}from"./play-CNuRuaAs.js";import{T as ft}from"./triangle-alert-BPHvH1wA.js";import{P as br}from"./panel-right-open-DcnKWxfx.js";import{X as vr}from"./x-fp82BETM.js";import"./react-CRB3T2We.js";import"./codemirror-DXt7RW72.js";import"./TrustBadge-D5CGp0cu.js";import"./AiBuildResult-xKtGthWv.js";import"./user-round-DukNupB_.js";import"./rotate-ccw-B2p953Zh.js";import"./wrench-1m0_kcza.js";import"./style-NlN9F6JE.js";import"./dagre.esm-B6nvU4OB.js";import"./list-tree-DapsIuQB.js";import"./minimize-2-BlVoipnT.js";import"./arrow-right-C7G3M_S8.js";/**
|
|
2
2
|
* @license lucide-react v0.563.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const vr=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Sr=Ri("chevron-left",vr);/**
|
|
7
|
-
* @license lucide-react v0.563.0 - ISC
|
|
8
|
-
*
|
|
9
|
-
* This source code is licensed under the ISC license.
|
|
10
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const kr=[["path",{d:"M4 11V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-1",key:"1q9hii"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]],Qi=Ri("file-input",kr);function _t({value:t,onChange:n,multiline:s,placeholder:r,style:o,ariaLabel:a,rows:p}){const[m,f]=c.useState(t),E=c.useRef(!1);c.useEffect(()=>{E.current||f(t)},[t]);const l={value:m,placeholder:r,style:o,"aria-label":a,onFocus:()=>{E.current=!0},onBlur:()=>{E.current=!1,f(t)},onChange:h=>{f(h.target.value),n(h.target.value)}};return s?e.jsx("textarea",{...l,rows:p}):e.jsx("input",{type:"text",...l})}function jr(t,n){return Ao(t,n)}const wr={native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function Cr(t){switch(t){case"no_join_path":return"No join path from this metric’s model to this dimension.";case"not_shared_across_metrics":return"Not reachable from every selected metric.";case"metric_unresolved":return"The selected metric could not be resolved.";default:return"Not compatible with the selected metrics."}}const wi=["day","week","month","quarter","year"];function Br(t,n,s){var a,p;if(!t)return wi;const r=(a=n.get(t))==null?void 0:a.granularities;if(r&&r.length>0)return r;const o=(p=s.find(m=>(m.reference??m.name)===t||m.name===t))==null?void 0:p.granularities;return o&&o.length>0?o:wi}function qs(){var Gn,Vn,Yn,Xn,Zn,Jn,ei,ti,ni,ii,oi,ri,si,li,ai,di,ci,ui,pi,fi,hi,mi,gi,xi,yi,bi,vi;const t=Ot(_o(i=>({activeBlockPath:i.activeBlockPath,authoredDomains:i.authoredDomains,blockStudioDbtStatus:i.blockStudioDbtStatus,blockStudioDirty:i.blockStudioDirty,blockStudioDraft:i.blockStudioDraft,blockStudioImportOpen:i.blockStudioImportOpen,blockStudioLastRun:i.blockStudioLastRun,blockStudioMetadata:i.blockStudioMetadata,blockStudioPreview:i.blockStudioPreview,blockStudioValidation:i.blockStudioValidation,files:i.files,schemaTables:i.schemaTables,semanticLayer:i.semanticLayer,themeMode:i.themeMode}))),n=Wo(),{operations:s,track:r}=Fo(),o=qt[t.themeMode],[a,p]=c.useState(()=>us()),m=t.activeBlockPath?`block-studio.block.${encodeURIComponent(t.activeBlockPath)}`:`block-studio.draft.${a}`,f=sr(m),[E,l]=c.useState("blocks"),[h,k]=c.useState("results"),[b,P]=c.useState(()=>ps()),[L,K]=c.useState([]),[_,w]=c.useState({}),[x,X]=c.useState(""),[H,re]=c.useState(new Set),$=c.useMemo(()=>{const i=t.schemaTables.map(y=>[y.name,y.columns.map(j=>j.name)]),d=ys(L).map(y=>[y.path,y.columns]),S=new Map;for(const[y,j]of[...d,...i])y&&S.set(y,j);return S.size>0?Object.fromEntries(S):void 0},[t.schemaTables,L]),[G,J]=c.useState(!1),[I,N]=c.useState(null),[q,V]=c.useState(null),[ve,te]=c.useState(!1),[Q,pe]=c.useState(null),[Se,Pe]=c.useState(0),[z,Y]=c.useState({}),[we,fe]=c.useState(!1),[De,ge]=c.useState(!1),[Ae,ke]=c.useState(null),[Ie,Ce]=c.useState(null),[u,M]=c.useState(null),[ee,de]=c.useState(null),[se,qe]=c.useState(null),oe=c.useRef(!1),le=c.useRef(null),[Ne,ae]=c.useState(null),[Je,et]=c.useState(!1),[_e,tt]=c.useState(null),[at,dt]=c.useState(!1),[ht,Re]=c.useState(null),[mt,Ge]=c.useState(0),[gt,Ve]=c.useState(!1),[xt,g]=c.useState(!1),T=c.useRef(null),D=c.useRef(null),C=c.useRef(!1),[U,ne]=c.useState(null),[v,B]=c.useState([]),[R,O]=c.useState(!1),[We,Ee]=c.useState(!1),[wt,Ct]=c.useState(null),[Xi,wn]=c.useState(null),[Zi,Cn]=c.useState(null),[Bn,Ji]=c.useState(340),[Nt,eo]=c.useState(320),[Le,Ht]=c.useState(!1),[Tn,yt]=c.useState(!1),[he,to]=c.useState(()=>typeof window<"u"?window.innerWidth<900:!1),[Dn,He]=c.useState(()=>t.blockStudioImportOpen?"import":"start"),[Bt,ie]=c.useState("visual"),[nt,nn]=c.useState(()=>fs("dql.block-studio.ai.open",!1)),[Qt,no]=c.useState(()=>hs("dql.block-studio.ai.width",420,360,520)),[In,Mn]=c.useState(!1),[io,oo]=c.useState(!1),[ro,so]=c.useState(0),[Qe,Ut]=c.useState(null),[lo,zn]=c.useState([]),[ao,Pn]=c.useState(!1),[Tt,on]=c.useState(null),[Rn,rn]=c.useState(null),[En,co]=c.useState("ask"),[uo,po]=c.useState(""),[fo,ho]=c.useState(void 0),[mo,go]=c.useState(!1),[Ln,it]=c.useState(null),sn=c.useRef(t.activeBlockPath),Dt=c.useRef(new Set),$n=c.useRef(new Set),me=c.useRef(0),Kt=c.useRef(t.blockStudioDraft);Kt.current=t.blockStudioDraft;const Gt=c.useCallback(()=>{me.current+=1,J(!1),N(null),V(null),te(!1),pe(null),Pe(0),Y({}),fe(!1),ge(!1),ke(null),Ce(null),M(null),de(null),ae(null),it(null),qe(null),B([]),O(!1),k("results")},[]),Ue=fn({queryKey:["block-studio","catalog","summary"],queryFn:()=>W.getBlockStudioCatalog({includeSemantic:!1}),staleTime:3e4}),It=fn({queryKey:["block-studio","dbt-status"],queryFn:()=>W.getBlockStudioDbtStatus(),staleTime:3e4}),Mt=fn({queryKey:["semantic-layer"],queryFn:()=>W.getSemanticLayer(),staleTime:3e4});c.useEffect(()=>{const i=()=>Ge(d=>d+1);return window.addEventListener("dql:block-library-invalidated",i),()=>window.removeEventListener("dql:block-library-invalidated",i)},[]),c.useEffect(()=>{var S;if(se)return;const i=Oo(s,{activePath:t.activeBlockPath,sourceFingerprint:(S=t.blockStudioMetadata)==null?void 0:S.sourceFingerprint});if(!i||$n.current.has(i.id))return;r(i),qe(i.id);const d=i.result;Dt.current=new Set([t.activeBlockPath,i.scope.startsWith("block:")?i.scope.slice(6):void 0,d==null?void 0:d.oldPath,d==null?void 0:d.draftPath,d==null?void 0:d.newPath].filter(y=>!!y))},[se,s,t.activeBlockPath,(Gn=t.blockStudioMetadata)==null?void 0:Gn.sourceFingerprint,r]),c.useEffect(()=>{var d,S,y;if(!se)return;const i=s.find(j=>j.id===se);if(i){if(i.status==="queued"||i.status==="running"){it({pending:!0,phase:i.phase,progress:i.progress,message:i.message});return}if(i.status==="succeeded"){const j=i.result;it({pending:!1,ok:(j==null?void 0:j.outcome)==="certified",checklist:j==null?void 0:j.checklist,blockers:(j==null?void 0:j.blockers)??((d=j==null?void 0:j.checklist)==null?void 0:d.blockers),error:(j==null?void 0:j.outcome)==="draft_saved_with_blockers"?"The draft was saved. Resolve the certification blockers and try again.":void 0}),ae(null)}else ae(((S=i.error)==null?void 0:S.message)??"Certification did not complete. The draft remains saved."),it({pending:!1,error:((y=i.error)==null?void 0:y.message)??i.message});$n.current.add(i.id),qe(null),k("save")}},[se,s]),c.useEffect(()=>{n({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:Ue.isLoading}),Ue.data?(n({type:"SET_BLOCK_STUDIO_CATALOG",catalog:Ue.data}),K(Ue.data.databaseTree),ne(null)):Ue.isError&&ne("Failed to load schema. Check your connection and try refreshing.")},[Ue.data,Ue.isError,Ue.isLoading,n]),c.useEffect(()=>{It.data?n({type:"SET_BLOCK_STUDIO_DBT_STATUS",status:It.data}):It.isError&&n({type:"SET_BLOCK_STUDIO_DBT_STATUS",status:null})},[It.data,It.isError,n]),c.useEffect(()=>{n({type:"SET_SEMANTIC_LOADING",loading:Mt.isLoading}),Mt.data&&n({type:"SET_SEMANTIC_LAYER",layer:Mt.data})},[n,Mt.data,Mt.isLoading]);const Vt=c.useCallback(async()=>{Pn(!0);try{const i=await W.listBlockStudioImports();zn(i.sessions??[])}catch{zn([])}finally{Pn(!1)}},[]);c.useEffect(()=>{Vt()},[Vt]),c.useEffect(()=>{const i=sn.current,d=t.activeBlockPath;if(d!==i){const S=se?s.find(je=>je.id===se):void 0,y=S==null?void 0:S.result,j=new Set([...Dt.current,y==null?void 0:y.oldPath,y==null?void 0:y.draftPath,y==null?void 0:y.newPath].filter(je=>!!je));!!(d&&j.has(d)&&(!i||j.has(i)))||(Dt.current.clear(),Gt())}d&&d!==i&&n({type:"CLOSE_BLOCK_IMPORT"}),sn.current=d},[t.activeBlockPath,se,n,s,Gt]),c.useEffect(()=>{if(!t.blockStudioDirty)return;const i=d=>{d.preventDefault(),d.returnValue=""};return window.addEventListener("beforeunload",i),()=>window.removeEventListener("beforeunload",i)},[t.blockStudioDirty]),c.useEffect(()=>{const i=new AbortController,d=window.setTimeout(()=>{t.blockStudioDraft.trim()&&W.validateBlockStudio(t.blockStudioDraft,t.activeBlockPath,i.signal).then(S=>{i.signal.aborted||n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:S})}).catch(()=>{})},250);return()=>{window.clearTimeout(d),i.abort()}},[t.blockStudioDraft,t.activeBlockPath,n]),c.useMemo(()=>gs(L,x),[L,x]);const Yt=c.useMemo(()=>xs(L),[L]),An={metrics:t.semanticLayer.metrics.length,measures:t.semanticLayer.measures.length,dimensions:t.semanticLayer.dimensions.length,timeDimensions:t.semanticLayer.timeDimensions.length,entities:t.semanticLayer.entities.length,hierarchies:t.semanticLayer.hierarchies.length,semanticModels:t.semanticLayer.semanticModels.length,savedQueries:t.semanticLayer.savedQueries.length},_n=bs(An);c.useEffect(()=>{const i=()=>to(window.innerWidth<900);return i(),window.addEventListener("resize",i),()=>window.removeEventListener("resize",i)},[]),c.useEffect(()=>{try{window.localStorage.setItem("dql.block-studio.ai.open",nt?"1":"0")}catch{}},[nt]),c.useEffect(()=>{try{window.localStorage.setItem("dql.block-studio.ai.width",String(Qt))}catch{}},[Qt]),c.useEffect(()=>{if(b)try{window.localStorage.setItem("dql.block-studio.domain",b)}catch{}},[b]),c.useEffect(()=>{var d,S;const i=(S=(d=t.blockStudioMetadata)==null?void 0:d.domain)==null?void 0:S.trim();i&&i!=="uncategorized"&&P(i)},[t.activeBlockPath,(Vn=t.blockStudioMetadata)==null?void 0:Vn.domain]),c.useEffect(()=>{t.blockStudioImportOpen&&(He("import"),n({type:"CLOSE_BLOCK_IMPORT"}))},[n,t.blockStudioImportOpen]),c.useEffect(()=>{var i;He(ms(t)?"manual":"start"),ie(((i=vt(t.blockStudioDraft))==null?void 0:i.blockType)==="semantic"?"visual":"source")},[t.activeBlockPath]);const ct=c.useMemo(()=>{var d;const i=vt(t.blockStudioDraft);return t.blockStudioMetadata?{...i,name:(i==null?void 0:i.name)||t.blockStudioMetadata.name,domain:(i==null?void 0:i.domain)||t.blockStudioMetadata.domain,description:(i==null?void 0:i.description)||t.blockStudioMetadata.description,owner:(i==null?void 0:i.owner)||t.blockStudioMetadata.owner,tags:(d=i==null?void 0:i.tags)!=null&&d.length?i.tags:t.blockStudioMetadata.tags,blockType:(i==null?void 0:i.blockType)||"custom",status:(i==null?void 0:i.status)||t.blockStudioMetadata.reviewStatus||"draft"}:i},[t.blockStudioDraft,t.blockStudioMetadata]),xe=(ct==null?void 0:ct.name)??((Yn=t.blockStudioMetadata)==null?void 0:Yn.name)??null,ot=((ct==null?void 0:ct.blockType)??"custom")==="semantic",Ye=!!(t.blockStudioDraft.trim()||t.blockStudioMetadata||t.activeBlockPath);c.useEffect(()=>{var i;if(t.activeBlockPath){if(le.current==="builder"){le.current=null,ie(((i=vt(t.blockStudioDraft))==null?void 0:i.blockType)==="semantic"?"visual":"source");return}t.activeBlockPath&&ie("detail")}},[t.activeBlockPath]);const ln=c.useCallback(async i=>{const d=me.current,S=`block:${i}`;n({type:"SET_LINEAGE_FOCUS",nodeId:S}),Ee(!0);try{const[y,j,F]=await Promise.all([W.fetchLineageNode(S),W.queryLineage({focus:S,upstreamDepth:3,downstreamDepth:2}),W.fetchLineagePaths(S,{maxDepth:6,maxPaths:6})]);if(d!==me.current)return;Ct(y),wn(j.graph??null),Cn(F)}catch{if(d!==me.current)return;Ct(null),wn(null),Cn(null)}finally{d===me.current&&Ee(!1)}},[n]);c.useEffect(()=>{xe&&ln(xe)},[xe,ln]);const Wn=c.useCallback(()=>{const i=t.activeBlockPath;if(!i||R)return;const d=me.current;W.getBlockHistory(i).then(S=>{d!==me.current||i!==sn.current||(B(S.entries),O(!0))}).catch(()=>{d===me.current&&(B([]),O(!0))})},[R,t.activeBlockPath]),Fe=i=>{N(null),V(null),ae(null),ke(null),Ce(null),M(null),de(null),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:i});const d=vt(i),S=t.blockStudioMetadata;if(!d||!S||!Ko(i))return;const y={...S,name:d.name||S.name,domain:d.domain||S.domain,description:d.description,owner:d.owner,tags:d.tags,reviewStatus:d.status||S.reviewStatus};(y.name!==S.name||y.domain!==S.domain||y.description!==S.description||y.owner!==S.owner||y.reviewStatus!==S.reviewStatus||y.tags.join("\0")!==S.tags.join("\0"))&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:y})},xo=i=>{if(i==="semantic"===ot)return;const d=t.blockStudioMetadata,S=(d==null?void 0:d.name)||(i==="semantic"?"new_semantic_block":"new_sql_block");let y=i==="semantic"?yn(S):Zt(S);y=$t(y,S),i==="custom"&&(y=Ai(y,"")),d&&(y=ue(y,"domain",d.domain||"uncategorized"),y=ue(y,"description",d.description??""),y=ue(y,"owner",d.owner??""),y=At(y,d.tags??[])),Fe(y),ie("visual")},yo=(i,d)=>{const S=t.blockStudioMetadata;let y=ot?t.blockStudioDraft:yn((S==null?void 0:S.name)||"new_semantic_block");!ot&&S&&(y=ue(y,"domain",S.domain||"uncategorized"),y=ue(y,"description",S.description??""),y=ue(y,"owner",S.owner??""),y=At(y,S.tags??[])),y=Ei(y,i),y=Li(y,"dimensions",d),Fe(y),on(null),rn(null),He("manual"),ie("visual")},Fn=()=>{Gt(),n({type:"START_NEW_BLOCK_WORKSPACE"}),p(kn()),Ut(null),He("start"),ie("visual")},On=async i=>{try{const d={name:i.path.split("/").pop()??i.name,path:i.path,type:"block",folder:"blocks"},S=await W.openBlockStudio(i.path);Gt(),t.files.some(y=>y.path===i.path)||n({type:"FILE_ADDED",file:d}),n({type:"OPEN_BLOCK_STUDIO",file:d,payload:S}),ne(null)}catch(d){ne(d instanceof Error?d.message:"Could not open this block.")}},an=()=>{const i=T.current;if(T.current=null,i){On(i);return}Fn()},qn=()=>{if(T.current=null,t.blockStudioDirty){g(!0);return}Fn()},Nn=()=>{qn()},bo=i=>{if(i.path!==t.activeBlockPath){if(t.blockStudioDirty){T.current=i,g(!0);return}On(i)}},Hn=i=>{const d=i==="semantic"?"new_semantic_block":"new_sql_block",S=b||"uncategorized",y=i==="semantic"?yn(d):Zt(d),j=ue(y,"domain",S);n({type:"SET_BLOCK_STUDIO_DRAFT",draft:j}),n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{name:d,path:null,domain:S,folderPath:"",description:"",owner:"",tags:[],reviewStatus:"draft",sourceKind:"manual"}}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:null}),n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:null}),He("manual"),ie("visual")},zt=async()=>{const i=me.current;J(!0),N(null),V(null),te(!1),pe(Date.now()),Pe(0),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:null});try{const d=await W.runBlockStudio(t.blockStudioDraft,t.activeBlockPath,z);if(i!==me.current)return;n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:d}),d.validation&&n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:d.validation}),ke(null),Ce(null),k("results")}catch(d){if(i!==me.current)return;const S=d instanceof Error?d.message:String(d),y=Ii(d);N(S),V(y),ke(y??S),Ce("run"),k(/required parameter|provide required parameter/i.test(S)?"parameters":"results")}finally{i===me.current&&(J(!1),pe(null))}},dn=async(i,d={})=>{var F,je,rt;const S=i??Ae;if(De||!S)return;const y=t.blockStudioDraft,j=me.current;ge(!0),ae(null),M(null),de(null);try{const ye=await W.repairAndRunBlockStudio(y,S,z,xe??((F=t.blockStudioMetadata)==null?void 0:F.name)??void 0);if(j!==me.current)return;if(Kt.current!==y)throw new Error("The block changed while AI repair was running. The stale repair was not applied.");const $e=await W.validateBlockStudio(ye.source,t.activeBlockPath);if(j!==me.current)return;if($e.saveable===!1)throw new Error(((je=$e.diagnostics.find(Oe=>Oe.severity==="error"))==null?void 0:je.message)??"The repaired DQL still has an authoring error.");if(Kt.current!==y)throw new Error("The block changed while AI repair was running. The stale repair was not applied.");const ce=d.requireCertificationReady?await W.assessBlockStudioCertification(ye.source):null;if(j!==me.current)return;if(Kt.current!==y)throw new Error("The block changed while AI repair was running. The stale repair was not applied.");if(Fe(ye.source),n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:$e}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:ye.preview}),N(null),ke(null),Ce(null),V(null),ce&&!ce.ok){const Oe=Math.max(1,ce.blockers.length),pt=(rt=ce.checklist.issues)==null?void 0:rt.find(Xt=>Xt.severity==="error");it({pending:!1,ok:!1,checklist:ce.checklist,certification:ce.certification,blockers:ce.blockers,error:"The repair attempt ran, but certification requirements are still not ready."}),de(`The repair attempt ran, but ${Oe} certification fix${Oe===1?"":"es"} remain${Oe===1?"s":""}.${pt!=null&&pt.title?` ${pt.title}.`:""}`),ie("source"),k("save"),yt(!1);return}ce!=null&&ce.ok?(it(null),M(`${ye.repairMode==="ai"?"AI repaired":"DQL repaired"} the draft, and every certification check now passes. Review the changes, then click Certify.`)):M(`${ye.repairMode==="ai"?"AI fixed":"DQL fixed"} the draft and the corrected block ran successfully. Review the changes, then save the draft.`),ie("source"),k("results"),yt(!1)}catch(ye){if(j!==me.current)return;const $e=ye instanceof Error?ye.message:String(ye),ce=Ii(ye);N($e),V(ce),ke(ce??$e),Ce("run"),k("results"),yt(!1)}finally{j===me.current&&ge(!1)}},vo=async(i=t.blockStudioDraft)=>{var y,j;if(!t.blockStudioMetadata)throw new Error("Block metadata is required before saving.");const d=await W.saveBlockStudio({path:t.activeBlockPath,source:i,metadata:{name:t.blockStudioMetadata.name,domain:t.blockStudioMetadata.domain,folderPath:t.blockStudioMetadata.folderPath,description:t.blockStudioMetadata.description,owner:t.blockStudioMetadata.owner,tags:t.blockStudioMetadata.tags,sourceKind:t.blockStudioMetadata.sourceKind,sourcePath:t.blockStudioMetadata.sourcePath,importId:t.blockStudioMetadata.importId,candidateId:t.blockStudioMetadata.candidateId,lineage:t.blockStudioMetadata.lineage}});return Ge(F=>F+1),n({type:"OPEN_BLOCK_STUDIO",file:{name:`${d.metadata.name}.dql`,path:d.path,type:"block",folder:"blocks"},payload:d}),t.files.some(F=>F.path===d.path)||n({type:"FILE_ADDED",file:{name:`${d.metadata.name}.dql`,path:d.path,type:"block",folder:"blocks"}}),((y=d.lineageRefresh)==null?void 0:y.status)==="ready"?ln(d.metadata.name):((j=d.lineageRefresh)==null?void 0:j.status)==="failed"&&(ae(`Block saved, but lineage refresh failed: ${d.lineageRefresh.message??"compile failed"}`),setTimeout(()=>ae(null),7e3)),d},cn=async()=>{var i,d;if(!((i=t.blockStudioMetadata)!=null&&i.name.trim())||!t.blockStudioMetadata.owner.trim())return D.current="save",Ve(!0),!1;fe(!0),ae(null);try{const S=t.blockStudioMetadata.reviewStatus==="certified"&&t.blockStudioDirty?ue(t.blockStudioDraft,"status","draft"):t.blockStudioDraft,y=await W.validateBlockStudio(S,t.activeBlockPath);if(n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:y}),y.saveable===!1||y.saveable===void 0&&!y.valid){const j=((d=y.diagnostics.find(F=>F.severity==="error"))==null?void 0:d.message)??"Fix the block errors before saving.";return ae(`Draft not saved: ${j}`),ke(j),Ce("save"),ie("source"),!1}return await vo(S),ke(null),Ce(null),M(null),de(null),k("save"),!0}catch(S){const y=(S==null?void 0:S.message)??"Save failed";return ae(y.includes("409")||y.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":y),!1}finally{fe(!1)}},un=(i,d)=>{Re(null),tt({path:i,name:d}),et(!0)},So=async()=>{var d;const i=_e==null?void 0:_e.path;if(i){dt(!0),Re(null);try{const S=await W.deleteBlockStudio(i);n({type:"FILE_REMOVED",path:S.path}),t.activeBlockPath===S.path&&(n({type:"START_NEW_BLOCK_WORKSPACE"}),p(kn()),Ut(null),He("start"),ie("visual")),et(!1),tt(null),Ge(y=>y+1),((d=S.lineageRefresh)==null?void 0:d.status)==="failed"&&ne(`Block deleted, but lineage refresh failed: ${S.lineageRefresh.message??"compile failed"}`)}catch(S){Re(S instanceof Error?S.message:String(S))}finally{dt(!1)}}},Qn=async()=>{var i;if(!((i=t.blockStudioMetadata)!=null&&i.name.trim())||!t.blockStudioMetadata.owner.trim())return D.current="certify",Ve(!0),!1;if(oe.current||se)return!1;oe.current=!0,fe(!0),ae(null);try{it(null);const d=t.blockStudioMetadata.reviewStatus==="certified"&&t.blockStudioDirty?ue(t.blockStudioDraft,"status","draft"):t.blockStudioDraft,S=`${t.blockStudioMetadata.sourceFingerprint??"new"}:${Date.now()}`,y=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`block-certification-${S}`,j=await W.requestBlockStudioCertification({source:d,path:t.activeBlockPath,metadata:t.blockStudioMetadata,expectedSourceFingerprint:t.blockStudioMetadata.sourceFingerprint,clientRevision:S,idempotencyKey:y});return r(j.operation),qe(j.operation.id),Dt.current=new Set([t.activeBlockPath,j.draft.path].filter(F=>!!F)),n({type:"BLOCK_CERTIFICATION_ACCEPTED",source:d}),it({pending:!0}),k("save"),!0}catch(d){Dt.current.clear();const S=(d==null?void 0:d.message)??"Save failed";return ae(S.includes("409")||S.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":S),setTimeout(()=>ae(null),5e3),!1}finally{oe.current=!1,fe(!1)}};c.useEffect(()=>{var S;const i=D.current;if(!i||!((S=t.blockStudioMetadata)!=null&&S.name.trim())||!t.blockStudioMetadata.owner.trim())return;D.current=null,(i==="certify"?Qn():cn()).then(y=>{y&&C.current&&(C.current=!1,an())})},[(Xn=t.blockStudioMetadata)==null?void 0:Xn.name,(Zn=t.blockStudioMetadata)==null?void 0:Zn.owner,t.blockStudioDraft]);const ko=i=>{var y;const d=i.savedPath??((y=i.draftSave)==null?void 0:y.path)??"",S={path:d,source:i.dqlSource,metadata:{name:i.name,path:d||null,domain:i.domain,description:i.description,owner:i.owner,tags:i.tags,reviewStatus:i.reviewStatus,sourceKind:i.sourceKind,sourcePath:i.sourcePath,importId:Qe==null?void 0:Qe.id,candidateId:i.id,lineage:i.lineage.sourceTables},companionPath:null,validation:i.validation??{valid:!0,diagnostics:[],semanticRefs:{metrics:[],dimensions:[],segments:[]},executableSql:null}};n({type:"OPEN_BLOCK_STUDIO",file:{name:`${i.name}.dql`,path:d,type:"block",folder:"blocks",isNew:!d},payload:S}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:i.preview}),k("results"),He("manual"),ie("visual")},jo=(i,d)=>{t.files.some(y=>y.path===d.path)||n({type:"FILE_ADDED",file:{name:`${d.metadata.name}.dql`,path:d.path,type:"block",folder:"blocks"}}),Ut(y=>y&&{...y,candidates:y.candidates.map(j=>j.id===i.id?i:j)}),Vt()},wo=(i,d)=>{var F,je,rt,ye,$e,ce,Oe;const S=t.blockStudioDraft.trim()?t.blockStudioDraft:Zt(((F=d==null?void 0:d.title)==null?void 0:F.trim())||"AI Generated Block"),y=(je=d==null?void 0:d.blockSource)!=null&&je.trim()?d.blockSource.trim():zi(S,i);Fe(y);const j=vt(y);j&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{name:j.name||(d==null?void 0:d.title)||"AI Generated Block",path:t.activeBlockPath,domain:j.domain||(d==null?void 0:d.domain)||"analytics",description:j.description||(d==null?void 0:d.description)||`AI generated block for ${(d==null?void 0:d.question)??"analysis"}`,owner:j.owner||(d==null?void 0:d.owner)||"",tags:j.tags.length>0?j.tags:(d==null?void 0:d.tags)??["ai-generated","review-required"],reviewStatus:j.status||"draft",sourceKind:((rt=t.blockStudioMetadata)==null?void 0:rt.sourceKind)??"ai-generated",sourcePath:(ye=t.blockStudioMetadata)==null?void 0:ye.sourcePath,importId:($e=t.blockStudioMetadata)==null?void 0:$e.importId,candidateId:(ce=t.blockStudioMetadata)==null?void 0:ce.candidateId,lineage:(Oe=t.blockStudioMetadata)==null?void 0:Oe.lineage}}),n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!0,diagnostics:[{severity:"info",code:"ai_sql_draft_inserted",message:j?"AI generated a draft block with metadata, SQL, visualization, and tests. Run preview, review joins and grain, then save.":"AI generated SQL inserted. Run preview, review joins and grain, then save or certify."}],semanticRefs:{metrics:[],dimensions:[],segments:[]},executableSql:i.trim()}}),k("results")},Co=async i=>{var rt,ye,$e,ce,Oe,pt,Xt;const d=(ye=(rt=i.dqlArtifact)==null?void 0:rt.source)==null?void 0:ye.trim(),S=(i.sql??"").trim();if(!d&&!S)return;let y;if(($e=i.question)!=null&&$e.trim())try{const Me=await W.composeSemanticBlock(i.question.trim());Me.ok&&Me.source.trim()&&(y=Me.source.trim())}catch{}const j=y||d||zi(Zt(((ce=i.title)==null?void 0:ce.trim())||"AI Generated Block"),S),F=vt(j),je=(F==null?void 0:F.name)||((Oe=i.dqlArtifact)==null?void 0:Oe.name)||i.title||"AI Generated Block";fe(!0),ae(null);try{const Me=await W.saveAgentBlockDraft({source:j,name:je,domain:(F==null?void 0:F.domain)||((pt=t.blockStudioMetadata)==null?void 0:pt.domain)||"uncategorized",description:(F==null?void 0:F.description)||`AI-generated draft for ${i.title??je}`,tags:(Xt=F==null?void 0:F.tags)!=null&&Xt.length?F.tags:["ai-generated","review-required"],runId:i.sourceRunId});le.current="builder",n({type:"OPEN_BLOCK_STUDIO",file:{name:`${Me.metadata.name}.dql`,path:Me.path,type:"block",folder:"blocks",isNew:!1},payload:Me}),t.files.some(pn=>pn.path===Me.path)||n({type:"FILE_ADDED",file:{name:`${Me.metadata.name}.dql`,path:Me.path,type:"block",folder:"blocks"}}),Ge(pn=>pn+1),He("manual"),ie("visual"),k("save")}catch(Me){ae(Me instanceof Error?Me.message:String(Me))}finally{fe(!1)}},bt=i=>{const d=(i==null?void 0:i.kind)??"ask";k("results"),co(d),po((i==null?void 0:i.initialInput)??""),ho(i!=null&&i.autoRun?{text:i.autoRun,mode:"block",nonce:Date.now()}:void 0),nn(!0)};c.useCallback(async()=>{try{const i=(await Ue.refetch()).data;i!=null&&i.databaseTree&&K(i.databaseTree),i&&n({type:"SET_BLOCK_STUDIO_CATALOG",catalog:i})}catch{}},[Ue,n]),c.useEffect(()=>{if(!G||!Q)return;const i=()=>Pe(Date.now()-Q);i();const d=window.setInterval(i,1e3);return()=>window.clearInterval(d)},[G,Q]);const Un=((Jn=t.blockStudioValidation)==null?void 0:Jn.chartConfig)??((ei=t.blockStudioPreview)==null?void 0:ei.chartConfig)??{chart:"table"},Bo=t.blockStudioPreview?lr(t.blockStudioPreview.result,t.blockStudioPreview.chartConfig):"table",To=i=>{i.preventDefault();const d=i.clientX,S=Bn,y=F=>{const je=Math.min(560,Math.max(300,S+F.clientX-d));Ji(je)},j=()=>{window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",y),window.addEventListener("mouseup",j)},Do=i=>{i.preventDefault();const d=i.clientY,S=Nt,y=F=>{const je=Math.min(500,Math.max(180,S-(F.clientY-d)));eo(je)},j=()=>{window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",y),window.addEventListener("mouseup",j)},Io=i=>{i.preventDefault();const d=i.clientX,S=Qt,y=F=>{no(Math.min(520,Math.max(360,S-(F.clientX-d))))},j=()=>{window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",y),window.addEventListener("mouseup",j)},ut=Ye&&!Tn,Mo=he?"minmax(0, 1fr)":`${Le?0:Bn}px ${Le?0:6}px minmax(0, 1fr) ${nt?6:0}px ${nt?In?`min(${mr}px, 52vw)`:`${Qt}px`:0}`,zo=he?Le?ut?`minmax(0, 1fr) 6px ${Nt}px`:"minmax(0, 1fr) 0 0":ut?`minmax(220px, 34vh) minmax(320px, 1fr) 6px ${Nt}px`:"minmax(220px, 34vh) minmax(0, 1fr) 0 0":ut?`minmax(0, 1fr) 6px ${Nt}px`:"minmax(0, 1fr) 0 0",Po=he?"1":"3",Kn=he?Le?"1":"2":"1",Ro=he?"1":"3",Eo=he?Le?"2":"3":"2",Lo=he?"1":"3",$o=he?Le?"3":"4":"3";return e.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:Mo,gridTemplateRows:zo,overflow:"hidden",background:o.appBg},children:[e.jsx("div",{style:{gridColumn:"1",gridRow:he?"1":"1 / 4",borderRight:Le?"none":`1px solid ${o.headerBorder}`,borderBottom:he&&!Le?`1px solid ${o.headerBorder}`:"none",display:Le?"none":"flex",flexDirection:"column",overflow:"hidden",background:o.sidebarBg,minWidth:0},children:e.jsx("div",{style:{flex:1,minHeight:0,overflow:"hidden"},children:e.jsx(qo,{tabs:["blocks","semantic","database"],defaultTab:E,blockDomain:b,onBlockDomainChange:P,onInsertText:i=>{if(ot){rn("That snippet is SQL. Use a SQL Block for raw SELECT work, or keep this Semantic Block on metrics and dimensions.");return}Fe(cs(t.blockStudioDraft,i))},onSemanticCompose:yo,onNewBlock:Nn,onOpenBlock:bo,onDeleteBlock:i=>un(i.path,i.name),blockLibraryRefreshKey:mt,onCollapse:()=>Ht(!0),footer:t.semanticLayer.loading?`Loading ${(((ti=t.blockStudioDbtStatus)==null?void 0:ti.counts.metrics)??0).toLocaleString()} semantic metrics…`:`${t.semanticLayer.provider?`${t.semanticLayer.provider} synced`:"dbt synced"} · ${Yt.tables} table${Yt.tables===1?"":"s"} · ${t.semanticLayer.metrics.length.toLocaleString()} metric${t.semanticLayer.metrics.length===1?"":"s"}`,footerStatus:t.semanticLayer.loading?"loading":"ready"})})}),e.jsx("div",{onMouseDown:Le?void 0:To,style:{gridColumn:"2",gridRow:"1 / 4",display:Le||he?"none":"block",cursor:"col-resize",background:o.headerBorder}}),e.jsxs("div",{style:{display:he&&nt?"none":"flex",flexDirection:"column",minWidth:0,overflow:"hidden",gridColumn:Po,gridRow:Kn},children:[e.jsx("style",{children:`
|
|
6
|
+
*/const Sr=[["path",{d:"M4 11V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-1",key:"1q9hii"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]],Hi=$o("file-input",Sr);function _t({value:t,onChange:n,multiline:s,placeholder:r,style:o,ariaLabel:a,rows:p}){const[m,f]=c.useState(t),E=c.useRef(!1);c.useEffect(()=>{E.current||f(t)},[t]);const l={value:m,placeholder:r,style:o,"aria-label":a,onFocus:()=>{E.current=!0},onBlur:()=>{E.current=!1,f(t)},onChange:h=>{f(h.target.value),n(h.target.value)}};return s?e.jsx("textarea",{...l,rows:p}):e.jsx("input",{type:"text",...l})}function kr(t,n){return Ao(t,n)}const jr={native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function wr(t){switch(t){case"no_join_path":return"No join path from this metric’s model to this dimension.";case"not_shared_across_metrics":return"Not reachable from every selected metric.";case"metric_unresolved":return"The selected metric could not be resolved.";default:return"Not compatible with the selected metrics."}}const wi=["day","week","month","quarter","year"];function Cr(t,n,s){var a,p;if(!t)return wi;const r=(a=n.get(t))==null?void 0:a.granularities;if(r&&r.length>0)return r;const o=(p=s.find(m=>(m.reference??m.name)===t||m.name===t))==null?void 0:p.granularities;return o&&o.length>0?o:wi}function Ns(){var Gn,Vn,Yn,Xn,Zn,Jn,ei,ti,ni,ii,oi,ri,si,li,ai,di,ci,ui,pi,fi,hi,mi,gi,xi,yi,bi,vi;const t=Ot(_o(i=>({activeBlockPath:i.activeBlockPath,authoredDomains:i.authoredDomains,blockStudioDbtStatus:i.blockStudioDbtStatus,blockStudioDirty:i.blockStudioDirty,blockStudioDraft:i.blockStudioDraft,blockStudioImportOpen:i.blockStudioImportOpen,blockStudioLastRun:i.blockStudioLastRun,blockStudioMetadata:i.blockStudioMetadata,blockStudioPreview:i.blockStudioPreview,blockStudioValidation:i.blockStudioValidation,files:i.files,schemaTables:i.schemaTables,semanticLayer:i.semanticLayer,themeMode:i.themeMode}))),n=Wo(),{operations:s,track:r}=Fo(),o=qt[t.themeMode],[a,p]=c.useState(()=>cs()),m=t.activeBlockPath?`block-studio.block.${encodeURIComponent(t.activeBlockPath)}`:`block-studio.draft.${a}`,f=sr(m),[E,l]=c.useState("blocks"),[h,k]=c.useState("results"),[b,P]=c.useState(()=>us()),[L,K]=c.useState([]),[_,w]=c.useState({}),[x,X]=c.useState(""),[H,re]=c.useState(new Set),$=c.useMemo(()=>{const i=t.schemaTables.map(y=>[y.name,y.columns.map(j=>j.name)]),d=xs(L).map(y=>[y.path,y.columns]),S=new Map;for(const[y,j]of[...d,...i])y&&S.set(y,j);return S.size>0?Object.fromEntries(S):void 0},[t.schemaTables,L]),[G,J]=c.useState(!1),[I,N]=c.useState(null),[q,V]=c.useState(null),[ve,te]=c.useState(!1),[Q,pe]=c.useState(null),[Se,Pe]=c.useState(0),[z,Y]=c.useState({}),[we,fe]=c.useState(!1),[De,ge]=c.useState(!1),[Ae,ke]=c.useState(null),[Ie,Ce]=c.useState(null),[u,M]=c.useState(null),[ee,de]=c.useState(null),[se,qe]=c.useState(null),oe=c.useRef(!1),le=c.useRef(null),[Ne,ae]=c.useState(null),[Je,et]=c.useState(!1),[_e,tt]=c.useState(null),[at,dt]=c.useState(!1),[ht,Re]=c.useState(null),[mt,Ge]=c.useState(0),[gt,Ve]=c.useState(!1),[xt,g]=c.useState(!1),T=c.useRef(null),D=c.useRef(null),C=c.useRef(!1),[U,ne]=c.useState(null),[v,B]=c.useState([]),[R,O]=c.useState(!1),[We,Ee]=c.useState(!1),[wt,Ct]=c.useState(null),[Yi,wn]=c.useState(null),[Xi,Cn]=c.useState(null),[Bn,Zi]=c.useState(340),[Nt,Ji]=c.useState(320),[Le,Ht]=c.useState(!1),[Tn,yt]=c.useState(!1),[he,eo]=c.useState(()=>typeof window<"u"?window.innerWidth<900:!1),[Dn,He]=c.useState(()=>t.blockStudioImportOpen?"import":"start"),[Bt,ie]=c.useState("visual"),[nt,nn]=c.useState(()=>ps("dql.block-studio.ai.open",!1)),[Qt,to]=c.useState(()=>fs("dql.block-studio.ai.width",420,360,520)),[In,Mn]=c.useState(!1),[no,io]=c.useState(!1),[oo,ro]=c.useState(0),[Qe,Ut]=c.useState(null),[so,zn]=c.useState([]),[lo,Pn]=c.useState(!1),[Tt,on]=c.useState(null),[Rn,rn]=c.useState(null),[En,ao]=c.useState("ask"),[co,uo]=c.useState(""),[po,fo]=c.useState(void 0),[ho,mo]=c.useState(!1),[Ln,it]=c.useState(null),sn=c.useRef(t.activeBlockPath),Dt=c.useRef(new Set),$n=c.useRef(new Set),me=c.useRef(0),Kt=c.useRef(t.blockStudioDraft);Kt.current=t.blockStudioDraft;const Gt=c.useCallback(()=>{me.current+=1,J(!1),N(null),V(null),te(!1),pe(null),Pe(0),Y({}),fe(!1),ge(!1),ke(null),Ce(null),M(null),de(null),ae(null),it(null),qe(null),B([]),O(!1),k("results")},[]),Ue=fn({queryKey:["block-studio","catalog","summary"],queryFn:()=>W.getBlockStudioCatalog({includeSemantic:!1}),staleTime:3e4}),It=fn({queryKey:["block-studio","dbt-status"],queryFn:()=>W.getBlockStudioDbtStatus(),staleTime:3e4}),Mt=fn({queryKey:["semantic-layer"],queryFn:()=>W.getSemanticLayer(),staleTime:3e4});c.useEffect(()=>{const i=()=>Ge(d=>d+1);return window.addEventListener("dql:block-library-invalidated",i),()=>window.removeEventListener("dql:block-library-invalidated",i)},[]),c.useEffect(()=>{var S;if(se)return;const i=Oo(s,{activePath:t.activeBlockPath,sourceFingerprint:(S=t.blockStudioMetadata)==null?void 0:S.sourceFingerprint});if(!i||$n.current.has(i.id))return;r(i),qe(i.id);const d=i.result;Dt.current=new Set([t.activeBlockPath,i.scope.startsWith("block:")?i.scope.slice(6):void 0,d==null?void 0:d.oldPath,d==null?void 0:d.draftPath,d==null?void 0:d.newPath].filter(y=>!!y))},[se,s,t.activeBlockPath,(Gn=t.blockStudioMetadata)==null?void 0:Gn.sourceFingerprint,r]),c.useEffect(()=>{var d,S,y;if(!se)return;const i=s.find(j=>j.id===se);if(i){if(i.status==="queued"||i.status==="running"){it({pending:!0,phase:i.phase,progress:i.progress,message:i.message});return}if(i.status==="succeeded"){const j=i.result;it({pending:!1,ok:(j==null?void 0:j.outcome)==="certified",checklist:j==null?void 0:j.checklist,blockers:(j==null?void 0:j.blockers)??((d=j==null?void 0:j.checklist)==null?void 0:d.blockers),error:(j==null?void 0:j.outcome)==="draft_saved_with_blockers"?"The draft was saved. Resolve the certification blockers and try again.":void 0}),ae(null)}else ae(((S=i.error)==null?void 0:S.message)??"Certification did not complete. The draft remains saved."),it({pending:!1,error:((y=i.error)==null?void 0:y.message)??i.message});$n.current.add(i.id),qe(null),k("save")}},[se,s]),c.useEffect(()=>{n({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:Ue.isLoading}),Ue.data?(n({type:"SET_BLOCK_STUDIO_CATALOG",catalog:Ue.data}),K(Ue.data.databaseTree),ne(null)):Ue.isError&&ne("Failed to load schema. Check your connection and try refreshing.")},[Ue.data,Ue.isError,Ue.isLoading,n]),c.useEffect(()=>{It.data?n({type:"SET_BLOCK_STUDIO_DBT_STATUS",status:It.data}):It.isError&&n({type:"SET_BLOCK_STUDIO_DBT_STATUS",status:null})},[It.data,It.isError,n]),c.useEffect(()=>{n({type:"SET_SEMANTIC_LOADING",loading:Mt.isLoading}),Mt.data&&n({type:"SET_SEMANTIC_LAYER",layer:Mt.data})},[n,Mt.data,Mt.isLoading]);const Vt=c.useCallback(async()=>{Pn(!0);try{const i=await W.listBlockStudioImports();zn(i.sessions??[])}catch{zn([])}finally{Pn(!1)}},[]);c.useEffect(()=>{Vt()},[Vt]),c.useEffect(()=>{const i=sn.current,d=t.activeBlockPath;if(d!==i){const S=se?s.find(je=>je.id===se):void 0,y=S==null?void 0:S.result,j=new Set([...Dt.current,y==null?void 0:y.oldPath,y==null?void 0:y.draftPath,y==null?void 0:y.newPath].filter(je=>!!je));!!(d&&j.has(d)&&(!i||j.has(i)))||(Dt.current.clear(),Gt())}d&&d!==i&&n({type:"CLOSE_BLOCK_IMPORT"}),sn.current=d},[t.activeBlockPath,se,n,s,Gt]),c.useEffect(()=>{if(!t.blockStudioDirty)return;const i=d=>{d.preventDefault(),d.returnValue=""};return window.addEventListener("beforeunload",i),()=>window.removeEventListener("beforeunload",i)},[t.blockStudioDirty]),c.useEffect(()=>{const i=new AbortController,d=window.setTimeout(()=>{t.blockStudioDraft.trim()&&W.validateBlockStudio(t.blockStudioDraft,t.activeBlockPath,i.signal).then(S=>{i.signal.aborted||n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:S})}).catch(()=>{})},250);return()=>{window.clearTimeout(d),i.abort()}},[t.blockStudioDraft,t.activeBlockPath,n]),c.useMemo(()=>ms(L,x),[L,x]);const Yt=c.useMemo(()=>gs(L),[L]),An={metrics:t.semanticLayer.metrics.length,measures:t.semanticLayer.measures.length,dimensions:t.semanticLayer.dimensions.length,timeDimensions:t.semanticLayer.timeDimensions.length,entities:t.semanticLayer.entities.length,hierarchies:t.semanticLayer.hierarchies.length,semanticModels:t.semanticLayer.semanticModels.length,savedQueries:t.semanticLayer.savedQueries.length},_n=ys(An);c.useEffect(()=>{const i=()=>eo(window.innerWidth<900);return i(),window.addEventListener("resize",i),()=>window.removeEventListener("resize",i)},[]),c.useEffect(()=>{try{window.localStorage.setItem("dql.block-studio.ai.open",nt?"1":"0")}catch{}},[nt]),c.useEffect(()=>{try{window.localStorage.setItem("dql.block-studio.ai.width",String(Qt))}catch{}},[Qt]),c.useEffect(()=>{if(b)try{window.localStorage.setItem("dql.block-studio.domain",b)}catch{}},[b]),c.useEffect(()=>{var d,S;const i=(S=(d=t.blockStudioMetadata)==null?void 0:d.domain)==null?void 0:S.trim();i&&i!=="uncategorized"&&P(i)},[t.activeBlockPath,(Vn=t.blockStudioMetadata)==null?void 0:Vn.domain]),c.useEffect(()=>{t.blockStudioImportOpen&&(He("import"),n({type:"CLOSE_BLOCK_IMPORT"}))},[n,t.blockStudioImportOpen]),c.useEffect(()=>{var i;He(hs(t)?"manual":"start"),ie(((i=vt(t.blockStudioDraft))==null?void 0:i.blockType)==="semantic"?"visual":"source")},[t.activeBlockPath]);const ct=c.useMemo(()=>{var d;const i=vt(t.blockStudioDraft);return t.blockStudioMetadata?{...i,name:(i==null?void 0:i.name)||t.blockStudioMetadata.name,domain:(i==null?void 0:i.domain)||t.blockStudioMetadata.domain,description:(i==null?void 0:i.description)||t.blockStudioMetadata.description,owner:(i==null?void 0:i.owner)||t.blockStudioMetadata.owner,tags:(d=i==null?void 0:i.tags)!=null&&d.length?i.tags:t.blockStudioMetadata.tags,blockType:(i==null?void 0:i.blockType)||"custom",status:(i==null?void 0:i.status)||t.blockStudioMetadata.reviewStatus||"draft"}:i},[t.blockStudioDraft,t.blockStudioMetadata]),xe=(ct==null?void 0:ct.name)??((Yn=t.blockStudioMetadata)==null?void 0:Yn.name)??null,ot=((ct==null?void 0:ct.blockType)??"custom")==="semantic",Ye=!!(t.blockStudioDraft.trim()||t.blockStudioMetadata||t.activeBlockPath);c.useEffect(()=>{var i;if(t.activeBlockPath){if(le.current==="builder"){le.current=null,ie(((i=vt(t.blockStudioDraft))==null?void 0:i.blockType)==="semantic"?"visual":"source");return}t.activeBlockPath&&ie("detail")}},[t.activeBlockPath]);const ln=c.useCallback(async i=>{const d=me.current,S=`block:${i}`;n({type:"SET_LINEAGE_FOCUS",nodeId:S}),Ee(!0);try{const[y,j,F]=await Promise.all([W.fetchLineageNode(S),W.queryLineage({focus:S,upstreamDepth:3,downstreamDepth:2}),W.fetchLineagePaths(S,{maxDepth:6,maxPaths:6})]);if(d!==me.current)return;Ct(y),wn(j.graph??null),Cn(F)}catch{if(d!==me.current)return;Ct(null),wn(null),Cn(null)}finally{d===me.current&&Ee(!1)}},[n]);c.useEffect(()=>{xe&&ln(xe)},[xe,ln]);const Wn=c.useCallback(()=>{const i=t.activeBlockPath;if(!i||R)return;const d=me.current;W.getBlockHistory(i).then(S=>{d!==me.current||i!==sn.current||(B(S.entries),O(!0))}).catch(()=>{d===me.current&&(B([]),O(!0))})},[R,t.activeBlockPath]),Fe=i=>{N(null),V(null),ae(null),ke(null),Ce(null),M(null),de(null),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:i});const d=vt(i),S=t.blockStudioMetadata;if(!d||!S||!Ko(i))return;const y={...S,name:d.name||S.name,domain:d.domain||S.domain,description:d.description,owner:d.owner,tags:d.tags,reviewStatus:d.status||S.reviewStatus};(y.name!==S.name||y.domain!==S.domain||y.description!==S.description||y.owner!==S.owner||y.reviewStatus!==S.reviewStatus||y.tags.join("\0")!==S.tags.join("\0"))&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:y})},go=i=>{if(i==="semantic"===ot)return;const d=t.blockStudioMetadata,S=(d==null?void 0:d.name)||(i==="semantic"?"new_semantic_block":"new_sql_block");let y=i==="semantic"?yn(S):Zt(S);y=$t(y,S),i==="custom"&&(y=$i(y,"")),d&&(y=ue(y,"domain",d.domain||"uncategorized"),y=ue(y,"description",d.description??""),y=ue(y,"owner",d.owner??""),y=At(y,d.tags??[])),Fe(y),ie("visual")},xo=(i,d)=>{const S=t.blockStudioMetadata;let y=ot?t.blockStudioDraft:yn((S==null?void 0:S.name)||"new_semantic_block");!ot&&S&&(y=ue(y,"domain",S.domain||"uncategorized"),y=ue(y,"description",S.description??""),y=ue(y,"owner",S.owner??""),y=At(y,S.tags??[])),y=Ri(y,i),y=Ei(y,"dimensions",d),Fe(y),on(null),rn(null),He("manual"),ie("visual")},Fn=()=>{Gt(),n({type:"START_NEW_BLOCK_WORKSPACE"}),p(kn()),Ut(null),He("start"),ie("visual")},On=async i=>{try{const d={name:i.path.split("/").pop()??i.name,path:i.path,type:"block",folder:"blocks"},S=await W.openBlockStudio(i.path);Gt(),t.files.some(y=>y.path===i.path)||n({type:"FILE_ADDED",file:d}),n({type:"OPEN_BLOCK_STUDIO",file:d,payload:S}),ne(null)}catch(d){ne(d instanceof Error?d.message:"Could not open this block.")}},an=()=>{const i=T.current;if(T.current=null,i){On(i);return}Fn()},qn=()=>{if(T.current=null,t.blockStudioDirty){g(!0);return}Fn()},Nn=()=>{qn()},yo=i=>{if(i.path!==t.activeBlockPath){if(t.blockStudioDirty){T.current=i,g(!0);return}On(i)}},Hn=i=>{const d=i==="semantic"?"new_semantic_block":"new_sql_block",S=b||"uncategorized",y=i==="semantic"?yn(d):Zt(d),j=ue(y,"domain",S);n({type:"SET_BLOCK_STUDIO_DRAFT",draft:j}),n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{name:d,path:null,domain:S,folderPath:"",description:"",owner:"",tags:[],reviewStatus:"draft",sourceKind:"manual"}}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:null}),n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:null}),He("manual"),ie("visual")},zt=async()=>{const i=me.current;J(!0),N(null),V(null),te(!1),pe(Date.now()),Pe(0),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:null});try{const d=await W.runBlockStudio(t.blockStudioDraft,t.activeBlockPath,z);if(i!==me.current)return;n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:d}),d.validation&&n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:d.validation}),ke(null),Ce(null),k("results")}catch(d){if(i!==me.current)return;const S=d instanceof Error?d.message:String(d),y=Ii(d);N(S),V(y),ke(y??S),Ce("run"),k(/required parameter|provide required parameter/i.test(S)?"parameters":"results")}finally{i===me.current&&(J(!1),pe(null))}},dn=async(i,d={})=>{var F,je,rt;const S=i??Ae;if(De||!S)return;const y=t.blockStudioDraft,j=me.current;ge(!0),ae(null),M(null),de(null);try{const ye=await W.repairAndRunBlockStudio(y,S,z,xe??((F=t.blockStudioMetadata)==null?void 0:F.name)??void 0);if(j!==me.current)return;if(Kt.current!==y)throw new Error("The block changed while AI repair was running. The stale repair was not applied.");const $e=await W.validateBlockStudio(ye.source,t.activeBlockPath);if(j!==me.current)return;if($e.saveable===!1)throw new Error(((je=$e.diagnostics.find(Oe=>Oe.severity==="error"))==null?void 0:je.message)??"The repaired DQL still has an authoring error.");if(Kt.current!==y)throw new Error("The block changed while AI repair was running. The stale repair was not applied.");const ce=d.requireCertificationReady?await W.assessBlockStudioCertification(ye.source):null;if(j!==me.current)return;if(Kt.current!==y)throw new Error("The block changed while AI repair was running. The stale repair was not applied.");if(Fe(ye.source),n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:$e}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:ye.preview}),N(null),ke(null),Ce(null),V(null),ce&&!ce.ok){const Oe=Math.max(1,ce.blockers.length),pt=(rt=ce.checklist.issues)==null?void 0:rt.find(Xt=>Xt.severity==="error");it({pending:!1,ok:!1,checklist:ce.checklist,certification:ce.certification,blockers:ce.blockers,error:"The repair attempt ran, but certification requirements are still not ready."}),de(`The repair attempt ran, but ${Oe} certification fix${Oe===1?"":"es"} remain${Oe===1?"s":""}.${pt!=null&&pt.title?` ${pt.title}.`:""}`),ie("source"),k("save"),yt(!1);return}ce!=null&&ce.ok?(it(null),M(`${ye.repairMode==="ai"?"AI repaired":"DQL repaired"} the draft, and every certification check now passes. Review the changes, then click Certify.`)):M(`${ye.repairMode==="ai"?"AI fixed":"DQL fixed"} the draft and the corrected block ran successfully. Review the changes, then save the draft.`),ie("source"),k("results"),yt(!1)}catch(ye){if(j!==me.current)return;const $e=ye instanceof Error?ye.message:String(ye),ce=Ii(ye);N($e),V(ce),ke(ce??$e),Ce("run"),k("results"),yt(!1)}finally{j===me.current&&ge(!1)}},bo=async(i=t.blockStudioDraft)=>{var y,j;if(!t.blockStudioMetadata)throw new Error("Block metadata is required before saving.");const d=await W.saveBlockStudio({path:t.activeBlockPath,source:i,metadata:{name:t.blockStudioMetadata.name,domain:t.blockStudioMetadata.domain,folderPath:t.blockStudioMetadata.folderPath,description:t.blockStudioMetadata.description,owner:t.blockStudioMetadata.owner,tags:t.blockStudioMetadata.tags,sourceKind:t.blockStudioMetadata.sourceKind,sourcePath:t.blockStudioMetadata.sourcePath,importId:t.blockStudioMetadata.importId,candidateId:t.blockStudioMetadata.candidateId,lineage:t.blockStudioMetadata.lineage}});return Ge(F=>F+1),n({type:"OPEN_BLOCK_STUDIO",file:{name:`${d.metadata.name}.dql`,path:d.path,type:"block",folder:"blocks"},payload:d}),t.files.some(F=>F.path===d.path)||n({type:"FILE_ADDED",file:{name:`${d.metadata.name}.dql`,path:d.path,type:"block",folder:"blocks"}}),((y=d.lineageRefresh)==null?void 0:y.status)==="ready"?ln(d.metadata.name):((j=d.lineageRefresh)==null?void 0:j.status)==="failed"&&(ae(`Block saved, but lineage refresh failed: ${d.lineageRefresh.message??"compile failed"}`),setTimeout(()=>ae(null),7e3)),d},cn=async()=>{var i,d;if(!((i=t.blockStudioMetadata)!=null&&i.name.trim())||!t.blockStudioMetadata.owner.trim())return D.current="save",Ve(!0),!1;fe(!0),ae(null);try{const S=t.blockStudioMetadata.reviewStatus==="certified"&&t.blockStudioDirty?ue(t.blockStudioDraft,"status","draft"):t.blockStudioDraft,y=await W.validateBlockStudio(S,t.activeBlockPath);if(n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:y}),y.saveable===!1||y.saveable===void 0&&!y.valid){const j=((d=y.diagnostics.find(F=>F.severity==="error"))==null?void 0:d.message)??"Fix the block errors before saving.";return ae(`Draft not saved: ${j}`),ke(j),Ce("save"),ie("source"),!1}return await bo(S),ke(null),Ce(null),M(null),de(null),k("save"),!0}catch(S){const y=(S==null?void 0:S.message)??"Save failed";return ae(y.includes("409")||y.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":y),!1}finally{fe(!1)}},un=(i,d)=>{Re(null),tt({path:i,name:d}),et(!0)},vo=async()=>{var d;const i=_e==null?void 0:_e.path;if(i){dt(!0),Re(null);try{const S=await W.deleteBlockStudio(i);n({type:"FILE_REMOVED",path:S.path}),t.activeBlockPath===S.path&&(n({type:"START_NEW_BLOCK_WORKSPACE"}),p(kn()),Ut(null),He("start"),ie("visual")),et(!1),tt(null),Ge(y=>y+1),((d=S.lineageRefresh)==null?void 0:d.status)==="failed"&&ne(`Block deleted, but lineage refresh failed: ${S.lineageRefresh.message??"compile failed"}`)}catch(S){Re(S instanceof Error?S.message:String(S))}finally{dt(!1)}}},Qn=async()=>{var i;if(!((i=t.blockStudioMetadata)!=null&&i.name.trim())||!t.blockStudioMetadata.owner.trim())return D.current="certify",Ve(!0),!1;if(oe.current||se)return!1;oe.current=!0,fe(!0),ae(null);try{it(null);const d=t.blockStudioMetadata.reviewStatus==="certified"&&t.blockStudioDirty?ue(t.blockStudioDraft,"status","draft"):t.blockStudioDraft,S=`${t.blockStudioMetadata.sourceFingerprint??"new"}:${Date.now()}`,y=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`block-certification-${S}`,j=await W.requestBlockStudioCertification({source:d,path:t.activeBlockPath,metadata:t.blockStudioMetadata,expectedSourceFingerprint:t.blockStudioMetadata.sourceFingerprint,clientRevision:S,idempotencyKey:y});return r(j.operation),qe(j.operation.id),Dt.current=new Set([t.activeBlockPath,j.draft.path].filter(F=>!!F)),n({type:"BLOCK_CERTIFICATION_ACCEPTED",source:d}),it({pending:!0}),k("save"),!0}catch(d){Dt.current.clear();const S=(d==null?void 0:d.message)??"Save failed";return ae(S.includes("409")||S.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":S),setTimeout(()=>ae(null),5e3),!1}finally{oe.current=!1,fe(!1)}};c.useEffect(()=>{var S;const i=D.current;if(!i||!((S=t.blockStudioMetadata)!=null&&S.name.trim())||!t.blockStudioMetadata.owner.trim())return;D.current=null,(i==="certify"?Qn():cn()).then(y=>{y&&C.current&&(C.current=!1,an())})},[(Xn=t.blockStudioMetadata)==null?void 0:Xn.name,(Zn=t.blockStudioMetadata)==null?void 0:Zn.owner,t.blockStudioDraft]);const So=i=>{var y;const d=i.savedPath??((y=i.draftSave)==null?void 0:y.path)??"",S={path:d,source:i.dqlSource,metadata:{name:i.name,path:d||null,domain:i.domain,description:i.description,owner:i.owner,tags:i.tags,reviewStatus:i.reviewStatus,sourceKind:i.sourceKind,sourcePath:i.sourcePath,importId:Qe==null?void 0:Qe.id,candidateId:i.id,lineage:i.lineage.sourceTables},companionPath:null,validation:i.validation??{valid:!0,diagnostics:[],semanticRefs:{metrics:[],dimensions:[],segments:[]},executableSql:null}};n({type:"OPEN_BLOCK_STUDIO",file:{name:`${i.name}.dql`,path:d,type:"block",folder:"blocks",isNew:!d},payload:S}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:i.preview}),k("results"),He("manual"),ie("visual")},ko=(i,d)=>{t.files.some(y=>y.path===d.path)||n({type:"FILE_ADDED",file:{name:`${d.metadata.name}.dql`,path:d.path,type:"block",folder:"blocks"}}),Ut(y=>y&&{...y,candidates:y.candidates.map(j=>j.id===i.id?i:j)}),Vt()},jo=(i,d)=>{var F,je,rt,ye,$e,ce,Oe;const S=t.blockStudioDraft.trim()?t.blockStudioDraft:Zt(((F=d==null?void 0:d.title)==null?void 0:F.trim())||"AI Generated Block"),y=(je=d==null?void 0:d.blockSource)!=null&&je.trim()?d.blockSource.trim():zi(S,i);Fe(y);const j=vt(y);j&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{name:j.name||(d==null?void 0:d.title)||"AI Generated Block",path:t.activeBlockPath,domain:j.domain||(d==null?void 0:d.domain)||"analytics",description:j.description||(d==null?void 0:d.description)||`AI generated block for ${(d==null?void 0:d.question)??"analysis"}`,owner:j.owner||(d==null?void 0:d.owner)||"",tags:j.tags.length>0?j.tags:(d==null?void 0:d.tags)??["ai-generated","review-required"],reviewStatus:j.status||"draft",sourceKind:((rt=t.blockStudioMetadata)==null?void 0:rt.sourceKind)??"ai-generated",sourcePath:(ye=t.blockStudioMetadata)==null?void 0:ye.sourcePath,importId:($e=t.blockStudioMetadata)==null?void 0:$e.importId,candidateId:(ce=t.blockStudioMetadata)==null?void 0:ce.candidateId,lineage:(Oe=t.blockStudioMetadata)==null?void 0:Oe.lineage}}),n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:{valid:!0,diagnostics:[{severity:"info",code:"ai_sql_draft_inserted",message:j?"AI generated a draft block with metadata, SQL, visualization, and tests. Run preview, review joins and grain, then save.":"AI generated SQL inserted. Run preview, review joins and grain, then save or certify."}],semanticRefs:{metrics:[],dimensions:[],segments:[]},executableSql:i.trim()}}),k("results")},wo=async i=>{var rt,ye,$e,ce,Oe,pt,Xt;const d=(ye=(rt=i.dqlArtifact)==null?void 0:rt.source)==null?void 0:ye.trim(),S=(i.sql??"").trim();if(!d&&!S)return;let y;if(($e=i.question)!=null&&$e.trim())try{const Me=await W.composeSemanticBlock(i.question.trim());Me.ok&&Me.source.trim()&&(y=Me.source.trim())}catch{}const j=y||d||zi(Zt(((ce=i.title)==null?void 0:ce.trim())||"AI Generated Block"),S),F=vt(j),je=(F==null?void 0:F.name)||((Oe=i.dqlArtifact)==null?void 0:Oe.name)||i.title||"AI Generated Block";fe(!0),ae(null);try{const Me=await W.saveAgentBlockDraft({source:j,name:je,domain:(F==null?void 0:F.domain)||((pt=t.blockStudioMetadata)==null?void 0:pt.domain)||"uncategorized",description:(F==null?void 0:F.description)||`AI-generated draft for ${i.title??je}`,tags:(Xt=F==null?void 0:F.tags)!=null&&Xt.length?F.tags:["ai-generated","review-required"],runId:i.sourceRunId});le.current="builder",n({type:"OPEN_BLOCK_STUDIO",file:{name:`${Me.metadata.name}.dql`,path:Me.path,type:"block",folder:"blocks",isNew:!1},payload:Me}),t.files.some(pn=>pn.path===Me.path)||n({type:"FILE_ADDED",file:{name:`${Me.metadata.name}.dql`,path:Me.path,type:"block",folder:"blocks"}}),Ge(pn=>pn+1),He("manual"),ie("visual"),k("save")}catch(Me){ae(Me instanceof Error?Me.message:String(Me))}finally{fe(!1)}},bt=i=>{const d=(i==null?void 0:i.kind)??"ask";k("results"),ao(d),uo((i==null?void 0:i.initialInput)??""),fo(i!=null&&i.autoRun?{text:i.autoRun,mode:"block",nonce:Date.now()}:void 0),nn(!0)};c.useCallback(async()=>{try{const i=(await Ue.refetch()).data;i!=null&&i.databaseTree&&K(i.databaseTree),i&&n({type:"SET_BLOCK_STUDIO_CATALOG",catalog:i})}catch{}},[Ue,n]),c.useEffect(()=>{if(!G||!Q)return;const i=()=>Pe(Date.now()-Q);i();const d=window.setInterval(i,1e3);return()=>window.clearInterval(d)},[G,Q]);const Un=((Jn=t.blockStudioValidation)==null?void 0:Jn.chartConfig)??((ei=t.blockStudioPreview)==null?void 0:ei.chartConfig)??{chart:"table"},Co=t.blockStudioPreview?lr(t.blockStudioPreview.result,t.blockStudioPreview.chartConfig):"table",Bo=i=>{i.preventDefault();const d=i.clientX,S=Bn,y=F=>{const je=Math.min(560,Math.max(300,S+F.clientX-d));Zi(je)},j=()=>{window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",y),window.addEventListener("mouseup",j)},To=i=>{i.preventDefault();const d=i.clientY,S=Nt,y=F=>{const je=Math.min(500,Math.max(180,S-(F.clientY-d)));Ji(je)},j=()=>{window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",y),window.addEventListener("mouseup",j)},Do=i=>{i.preventDefault();const d=i.clientX,S=Qt,y=F=>{to(Math.min(520,Math.max(360,S-(F.clientX-d))))},j=()=>{window.removeEventListener("mousemove",y),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",y),window.addEventListener("mouseup",j)},ut=Ye&&!Tn,Io=he?"minmax(0, 1fr)":`${Le?0:Bn}px ${Le?0:6}px minmax(0, 1fr) ${nt?6:0}px ${nt?In?`min(${mr}px, 52vw)`:`${Qt}px`:0}`,Mo=he?Le?ut?`minmax(0, 1fr) 6px ${Nt}px`:"minmax(0, 1fr) 0 0":ut?`minmax(220px, 34vh) minmax(320px, 1fr) 6px ${Nt}px`:"minmax(220px, 34vh) minmax(0, 1fr) 0 0":ut?`minmax(0, 1fr) 6px ${Nt}px`:"minmax(0, 1fr) 0 0",zo=he?"1":"3",Kn=he?Le?"1":"2":"1",Po=he?"1":"3",Ro=he?Le?"2":"3":"2",Eo=he?"1":"3",Lo=he?Le?"3":"4":"3";return e.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:Io,gridTemplateRows:Mo,overflow:"hidden",background:o.appBg},children:[e.jsx("div",{style:{gridColumn:"1",gridRow:he?"1":"1 / 4",borderRight:Le?"none":`1px solid ${o.headerBorder}`,borderBottom:he&&!Le?`1px solid ${o.headerBorder}`:"none",display:Le?"none":"flex",flexDirection:"column",overflow:"hidden",background:o.sidebarBg,minWidth:0},children:e.jsx("div",{style:{flex:1,minHeight:0,overflow:"hidden"},children:e.jsx(qo,{tabs:["blocks","semantic","database"],defaultTab:E,blockDomain:b,onBlockDomainChange:P,onInsertText:i=>{if(ot){rn("That snippet is SQL. Use a SQL Block for raw SELECT work, or keep this Semantic Block on metrics and dimensions.");return}Fe(ds(t.blockStudioDraft,i))},onSemanticCompose:xo,onNewBlock:Nn,onOpenBlock:yo,onDeleteBlock:i=>un(i.path,i.name),blockLibraryRefreshKey:mt,onCollapse:()=>Ht(!0),footer:t.semanticLayer.loading?`Loading ${(((ti=t.blockStudioDbtStatus)==null?void 0:ti.counts.metrics)??0).toLocaleString()} semantic metrics…`:`${t.semanticLayer.provider?`${t.semanticLayer.provider} synced`:"dbt synced"} · ${Yt.tables} table${Yt.tables===1?"":"s"} · ${t.semanticLayer.metrics.length.toLocaleString()} metric${t.semanticLayer.metrics.length===1?"":"s"}`,footerStatus:t.semanticLayer.loading?"loading":"ready"})})}),e.jsx("div",{onMouseDown:Le?void 0:Bo,style:{gridColumn:"2",gridRow:"1 / 4",display:Le||he?"none":"block",cursor:"col-resize",background:o.headerBorder}}),e.jsxs("div",{style:{display:he&&nt?"none":"flex",flexDirection:"column",minWidth:0,overflow:"hidden",gridColumn:zo,gridRow:Kn},children:[e.jsx("style",{children:`
|
|
12
7
|
@keyframes dql-agent-fadein { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }
|
|
13
8
|
@keyframes dql-agent-run-spin { to { transform: rotate(360deg); } }
|
|
14
|
-
`}),e.jsxs("div",{style:{height:46,flexShrink:0,display:"flex",alignItems:"center",gap:10,padding:"0 16px",borderBottom:`1px solid ${o.headerBorder}`,background:o.cellBg,overflowX:"auto"},children:[Le&&e.jsx("button",{onClick:()=>Ht(!1),style:{background:"transparent",border:"none",color:o.textMuted,cursor:"pointer",fontSize:14,fontFamily:o.font,padding:0,lineHeight:1},title:"Open explorer",children:"›"}),e.jsxs("button",{type:"button",onClick:qn,title:"Back to Block Studio",className:"dql-hover",style:{display:"inline-flex",alignItems:"center",gap:4,background:"transparent",border:"none",padding:"2px 4px",margin:"0 -4px",borderRadius:6,color:o.textMuted,fontSize:12,fontFamily:o.font,whiteSpace:"nowrap",cursor:"pointer"},children:[e.jsx(Sr,{size:12,strokeWidth:2})," Blocks"]}),e.jsx(bn,{size:11,color:o.textMuted,style:{flexShrink:0}}),e.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:o.textPrimary,fontFamily:o.fontMono,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:220},children:xe||((ni=t.blockStudioMetadata)==null?void 0:ni.name)||(Ye?"new_block":ot?"semantic":"sql")}),((ii=t.blockStudioMetadata)==null?void 0:ii.reviewStatus)&&e.jsx(Ni,{status:t.blockStudioMetadata.reviewStatus,t:o}),Ye&&Dn==="manual"&&Bt!=="detail"&&e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:2,padding:2,border:`1px solid ${o.headerBorder}`,borderRadius:7,background:o.appBg,marginLeft:6,flexShrink:0},children:[e.jsx("button",{type:"button",onClick:()=>ie("visual"),style:Ci(o,Bt==="visual"),children:"Visual Builder"}),e.jsx("button",{type:"button",onClick:()=>ie("source"),style:Ci(o,Bt==="source"),children:"DQL Source"})]}),Ye&&e.jsx(st,{label:`Context${Pi(t.blockStudioDraft)?` (${Pi(t.blockStudioDraft)})`:""}`,Icon:vn,onClick:()=>go(i=>!i)}),e.jsx("div",{style:{flex:1}}),t.activeBlockPath&&e.jsx(st,{label:"Delete",Icon:tn,variant:"danger",title:"Delete this saved block",onClick:()=>{var i;return un(t.activeBlockPath,((i=t.blockStudioMetadata)==null?void 0:i.name)||xe||t.activeBlockPath)}}),e.jsx(st,{label:"New block",Icon:No,onClick:Nn}),Ye&&e.jsxs(e.Fragment,{children:[e.jsx(st,{label:"Ask AI",Icon:Lt,onClick:()=>bt({kind:"ask"})}),t.activeBlockPath&&e.jsx(st,{label:"Modify with AI",Icon:Lt,onClick:()=>bt({kind:"edit",initialInput:`Modify this block${xe?` (${xe})`:""}: `})}),e.jsx(st,{label:"Run",Icon:Hi,onClick:()=>void zt(),busy:G}),e.jsx(st,{label:we?"Saving":"Save draft",Icon:kt,variant:"secondary",busy:we,onClick:()=>void cn(),title:"Save changes as a review-required draft"}),e.jsx(st,{label:((oi=t.blockStudioMetadata)==null?void 0:oi.reviewStatus)==="certified"?"Re-certify":"Certify",Icon:Ho,variant:"primary",busy:we||!!se,onClick:()=>void Qn(),title:"Run validation, query, tests, chart, and lineage gates before certification"})]}),Ne&&e.jsx("span",{style:{fontSize:11,color:"var(--status-error)",fontFamily:o.font,padding:"4px 8px",background:"var(--status-error-bg)",borderRadius:6},children:Ne})]}),Ae&&Ie==="save"&&e.jsxs("div",{role:"alert",style:{flexShrink:0,display:"flex",alignItems:"flex-start",gap:10,padding:"10px 14px",borderBottom:"1px solid var(--status-error)",background:"var(--status-error-bg)",color:o.textPrimary,fontFamily:o.font},children:[e.jsx(ft,{size:16,color:"var(--status-error)",style:{marginTop:1,flexShrink:0}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:700},children:"This draft was not saved. Your work is still editable."}),e.jsx("div",{style:{marginTop:2,fontSize:11.5,lineHeight:1.45,color:o.textSecondary},children:Ae}),(((ri=t.blockStudioValidation)==null?void 0:ri.diagnostics.filter(i=>i.severity==="error").length)??0)>1&&e.jsx("div",{style:{marginTop:4,fontSize:10.5,color:o.textMuted},children:t.blockStudioValidation.diagnostics.filter(i=>i.severity==="error").slice(1,3).map(i=>i.message).join(" · ")})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,flexWrap:"wrap",justifyContent:"flex-end"},children:[e.jsxs("button",{type:"button",onClick:()=>void dn(),disabled:De,style:{...Te(o),display:"inline-flex",alignItems:"center",gap:6,opacity:De?.72:1},children:[De?e.jsx(Ze,{size:13,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):e.jsx(Lt,{size:13}),De?"Fixing & running…":"Fix with AI & run"]}),e.jsx("button",{type:"button",onClick:()=>ie("source"),style:Z(o),children:"Edit DQL"}),e.jsx("button",{type:"button",onClick:()=>bt({kind:"edit",initialInput:`Help me fix this block error without changing its intended grain, parameters, or trust state: ${Ae} `}),style:Z(o),children:"Open Block AI"})]})]}),u&&e.jsxs("div",{role:"status",style:{flexShrink:0,display:"flex",alignItems:"center",gap:8,padding:"8px 14px",borderBottom:"1px solid var(--status-success)",background:"var(--status-success-bg)",color:o.textSecondary,fontSize:11.5,fontFamily:o.font},children:[e.jsx(kt,{size:14,color:"var(--status-success)"})," ",u]}),ee&&e.jsxs("div",{role:"status",style:{flexShrink:0,display:"flex",alignItems:"center",gap:8,padding:"8px 14px",borderBottom:"1px solid var(--status-warning-border)",background:"var(--status-warning-bg)",color:o.textSecondary,fontSize:11.5,fontFamily:o.font},children:[e.jsx(ft,{size:14,color:"var(--status-warning)"})," ",ee]}),Ye&&mo&&e.jsx(Er,{source:t.blockStudioDraft,databaseStats:Yt,semanticCount:_n,onChange:Fe,onOpenExplorer:()=>{Ht(!1),l("database")},onOpenAi:()=>bt({kind:"edit",initialInput:"Review and improve this block context. Keep only grounded business references, sources, constraints, and caveats: "}),t:o}),e.jsx("div",{style:{flex:1,overflow:"hidden"},children:Dn==="import"?e.jsx(Gr,{session:Qe,sessions:lo,sessionsLoading:ao,onClose:()=>He(Ye?"manual":"start"),onSessionChange:Ut,onRefreshSessions:Vt,onSelectCandidate:ko,onSavedCandidate:jo,defaultDomain:((si=t.blockStudioMetadata)==null?void 0:si.domain)??b,defaultOwner:((li=t.blockStudioMetadata)==null?void 0:li.owner)??"",themeMode:t.themeMode,t:o,inline:!0}):Ye?Bt==="detail"?e.jsx(Ar,{metadata:t.blockStudioMetadata,source:t.blockStudioDraft,parameters:((ai=t.blockStudioValidation)==null?void 0:ai.parameters)??[],preview:t.blockStudioPreview,lastRun:t.blockStudioLastRun??void 0,lineageDetail:wt,isSemanticBlock:ot,running:G,onOpenBuilder:()=>ie("visual"),onOpenSource:()=>ie("source"),onDelete:()=>{var i;return t.activeBlockPath&&un(t.activeBlockPath,((i=t.blockStudioMetadata)==null?void 0:i.name)||xe||t.activeBlockPath)},onRun:()=>void zt(),onOpenHistory:()=>{k("history"),yt(!1),Wn()},t:o}):Bt==="visual"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[e.jsx(Wr,{mode:ot?"semantic":"custom",onModeChange:xo,t:o}),e.jsx("div",{style:{flex:1,minHeight:0},children:ot?e.jsx(_r,{source:t.blockStudioDraft,metadata:t.blockStudioMetadata,semanticLayer:t.semanticLayer,dbtStatus:t.blockStudioDbtStatus,domainOptions:t.authoredDomains,chartConfig:Un,onChange:Fe,onMetadataChange:i=>t.blockStudioMetadata&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...i}}),onOpenAi:()=>bt({kind:"edit",initialInput:"Help resolve the selected semantic metrics and dimensions for this block: "}),onSetupRuntime:()=>{n({type:"SET_SETTINGS_TAB",tab:"project"}),n({type:"SET_MAIN_VIEW",view:"settings"})},t:o},`sem-${t.activeBlockPath??a}`):e.jsx(Fr,{source:t.blockStudioDraft,metadata:t.blockStudioMetadata,domainOptions:t.authoredDomains,chartConfig:Un,onChange:Fe,onMetadataChange:i=>t.blockStudioMetadata&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...i}}),onConvertToDql:()=>ie("source"),t:o},`sql-${t.activeBlockPath??a}`)})]}):e.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(Tt||Rn)&&e.jsx(Or,{semanticChoice:Tt,databaseWarning:Rn,onDismiss:()=>{on(null),rn(null)},onInsertAdvanced:()=>{if(!Tt)return;const i=Qo(Tt.kind==="metric"?"metric":"dimension",Tt.name);Fe(Uo(t.blockStudioDraft,i)),on(null)},onCreateSemantic:()=>n({type:"OPEN_NEW_BLOCK_MODAL",blockType:"semantic"}),t:o}),e.jsxs("div",{style:{height:34,flexShrink:0,display:"flex",alignItems:"center",gap:10,padding:"0 14px",borderBottom:"1px solid var(--border-subtle)",background:o.appBg},children:[e.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.activeBlockPath??Vi(t.blockStudioMetadata)}),t.blockStudioDirty&&e.jsx("span",{style:{width:6,height:6,borderRadius:999,background:"var(--status-warning)",flexShrink:0},title:"Unsaved changes"}),e.jsx("div",{style:{flex:1}}),t.blockStudioValidation?t.blockStudioValidation.diagnostics.filter(i=>i.severity==="error").length===0?e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:"var(--status-success)",fontWeight:600,whiteSpace:"nowrap",fontFamily:o.font},children:[e.jsx(kt,{size:12})," Valid"]}):e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:"var(--status-warning)",fontWeight:600,whiteSpace:"nowrap",fontFamily:o.font},children:[e.jsx(ft,{size:12})," ",t.blockStudioValidation.diagnostics.filter(i=>i.severity==="error").length," problem",t.blockStudioValidation.diagnostics.filter(i=>i.severity==="error").length===1?"":"s"]}):e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:o.textMuted,fontWeight:600,whiteSpace:"nowrap",fontFamily:o.font},children:[e.jsx(Ze,{size:12,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}})," Checking"]})]}),e.jsxs("div",{style:{flex:1,minHeight:0,display:"flex",overflow:"hidden"},children:[e.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",background:o.cellBg,borderRight:"1px solid var(--border-subtle)"},children:e.jsx(or,{value:t.blockStudioDraft,onChange:Fe,onRun:()=>void zt(),themeMode:t.themeMode,autoFocus:!0,wrap:!1,fillHeight:!0,schema:$,dqlMode:!0,errorMessage:(ci=(di=t.blockStudioValidation)==null?void 0:di.diagnostics.find(i=>i.severity==="error"))==null?void 0:ci.message})}),!he&&e.jsx(Dr,{source:t.blockStudioDraft,diagnostics:((ui=t.blockStudioValidation)==null?void 0:ui.diagnostics)??[],parameterCount:((fi=(pi=t.blockStudioValidation)==null?void 0:pi.parameters)==null?void 0:fi.length)??0,t:o})]})]}):e.jsx(Pr,{dbtStatus:t.blockStudioDbtStatus,semanticStats:An,semanticObjectCount:_n,databaseStats:Yt,onCreateSql:()=>Hn("custom"),onCreateSemantic:()=>Hn("semantic"),onImport:()=>He("import"),onBuildDql:()=>bt({kind:"build",initialInput:"Draft a reusable DQL block that "}),t:o})})]}),e.jsx("div",{onMouseDown:ut?Do:void 0,style:{gridColumn:Ro,gridRow:Eo,display:ut?"block":"none",cursor:"row-resize",background:o.headerBorder}}),e.jsxs("div",{style:{gridColumn:Lo,gridRow:$o,borderTop:ut?`1px solid ${o.headerBorder}`:"none",display:ut?"flex":"none",flexDirection:"column",overflow:"hidden",background:o.cellBg},children:[e.jsxs("div",{style:{display:"flex",gap:14,alignItems:"center",padding:"0 16px",borderBottom:`1px solid ${o.headerBorder}`,flexWrap:"wrap"},children:[e.jsx(Pt,{active:h==="results",onClick:()=>k("results"),label:"Results",t:o}),e.jsx(Pt,{active:h==="parameters",onClick:()=>k("parameters"),label:`Run inputs${(((mi=(hi=t.blockStudioValidation)==null?void 0:hi.parameters)==null?void 0:mi.length)??0)>0?` · ${t.blockStudioValidation.parameters.length}`:""}`,t:o}),e.jsx(Pt,{active:h==="lineage",onClick:()=>k("lineage"),label:"Lineage",t:o}),e.jsx(Pt,{active:h==="history",onClick:()=>{k("history"),Wn()},label:"History",t:o}),e.jsx(Pt,{active:h==="save",onClick:()=>k("save"),label:"Metadata",t:o}),e.jsx("div",{style:{flex:1}}),t.blockStudioPreview?e.jsxs("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.font,whiteSpace:"nowrap"},children:[t.blockStudioPreview.result.executionTime?`Ran in ${(t.blockStudioPreview.result.executionTime/1e3).toFixed(1)}s · `:"",t.blockStudioPreview.result.rowCount??t.blockStudioPreview.result.rows.length," rows"]}):null,e.jsx("button",{onClick:()=>yt(!0),style:{background:"transparent",border:"none",color:o.textMuted,cursor:"pointer",fontSize:11,fontFamily:o.font,padding:"4px 6px"},title:"Hide pane",children:"▾ Hide"})]}),e.jsxs("div",{style:{flex:1,overflow:"auto"},children:[h==="results"&&(G?e.jsx(ns,{elapsedMs:Se}):t.blockStudioPreview?e.jsxs("div",{style:{display:"grid",gap:12,padding:12},children:[(xi=(gi=t.blockStudioPreview.invocation)==null?void 0:gi.resolvedParameters)!=null&&xi.length?e.jsx(ts,{values:t.blockStudioPreview.invocation.resolvedParameters,t:o}):null,Bo==="table"?e.jsx(Oi,{result:t.blockStudioPreview.result,themeMode:t.themeMode}):e.jsx(ar,{result:t.blockStudioPreview.result,chartConfig:t.blockStudioPreview.chartConfig,themeMode:t.themeMode}),e.jsxs("details",{open:ve,onToggle:i=>te(i.currentTarget.open),style:{border:`1px solid ${o.headerBorder}`,borderRadius:8,background:o.pillBg},children:[e.jsx("summary",{style:{cursor:"pointer",padding:"9px 11px",fontSize:11,fontWeight:700,color:o.textSecondary,fontFamily:o.font},children:"Query details"}),e.jsx("pre",{style:{margin:0,padding:"0 11px 11px",maxHeight:220,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:10.5,lineHeight:1.45,color:o.textMuted,fontFamily:o.fontMono},children:t.blockStudioPreview.sql})]})]}):I?e.jsx(is,{message:I,technicalDetails:q,repairing:De,onFix:()=>void dn(q??I),onEdit:()=>ie("source")}):e.jsx(jt,{message:"Run the block to preview results."})),h==="lineage"&&e.jsx(Zr,{blockName:xe,loading:We,detail:wt,graph:Xi,paths:Zi,onSelectNode:i=>{n({type:"SET_LINEAGE_FOCUS",nodeId:i}),n({type:"OPEN_LINEAGE_DRAWER",nodeId:i})},onOpenInspector:()=>{if(xe){const i=`block:${xe}`;n({type:"SET_LINEAGE_FOCUS",nodeId:i}),n({type:"OPEN_LINEAGE_DRAWER",nodeId:i})}},t:o}),h==="parameters"&&e.jsx(es,{parameters:((yi=t.blockStudioValidation)==null?void 0:yi.parameters)??[],values:z,onChange:(i,d)=>Y(S=>({...S,[i]:d})),onReset:i=>Y(d=>{const S={...d};return delete S[i],S}),onRun:()=>void zt(),running:G,t:o}),h==="history"&&e.jsx(ds,{entries:v,t:o}),h==="save"&&e.jsxs("div",{style:{display:"grid",gap:12},children:[t.activeBlockPath&&t.blockStudioMetadata&&e.jsx("div",{style:{padding:"12px 12px 0"},children:e.jsx(ss,{currentStatus:t.blockStudioMetadata.reviewStatus??"draft",blockPath:t.activeBlockPath,onStatusChanged:i=>{t.blockStudioMetadata&&(n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,reviewStatus:i}}),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:ue(t.blockStudioDraft,"status",i)}))},t:o})}),Ln&&e.jsx(ls,{result:Ln,t:o,repairing:De,onEditSource:()=>ie("source"),onEditParameters:()=>k("parameters"),onReviewMetrics:()=>{Ht(!1),l("semantic"),ie("visual")},onRun:()=>void zt(),onFix:i=>void dn(i.technicalDetails??i.message,{requireCertificationReady:!0})}),e.jsx(Jr,{metadata:t.blockStudioMetadata,draftMetadata:ct,onChange:i=>{if(!t.blockStudioMetadata)return;n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...i}});let d=t.blockStudioDraft;typeof i.name=="string"&&(d=$t(d,i.name)),typeof i.domain=="string"&&(d=ue(d,"domain",i.domain)),typeof i.owner=="string"&&(d=ue(d,"owner",i.owner)),typeof i.description=="string"&&(d=ue(d,"description",i.description)),i.tags&&(d=At(d,i.tags)),Fe(d)},t:o})]})]})]}),Ye&&Tn&&e.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:e.jsx("button",{onClick:()=>yt(!1),style:{background:o.btnBg,border:`1px solid ${o.btnBorder}`,borderRadius:6,color:o.textSecondary,cursor:"pointer",fontSize:12,fontFamily:o.font,padding:"8px 12px"},children:"Open Results"})}),!he&&nt&&e.jsx("div",{onMouseDown:Io,style:{gridColumn:"4",gridRow:"1 / 4",cursor:"col-resize",background:o.headerBorder}}),nt&&e.jsx(gr,{t:o,title:"Block AI",subtitle:xe?`Current block: ${xe}`:"Unsaved governed block draft",expanded:In,onToggleExpanded:()=>Mn(i=>!i),onClose:()=>{nn(!1),Mn(!1)},onNewChat:()=>{f.resetThreadId(),so(i=>i+1)},running:io,compact:he,ariaLabel:"Block Studio AI",style:{gridColumn:he?"1":"5",gridRow:he?Kn:"1 / 4"},children:e.jsx(fr,{themeMode:t.themeMode,title:"Block AI",scopeHint:xe?`Current block: ${xe}`:"Block Studio project context",workspaceContext:{surface:"block-studio",task:En==="edit"?"edit_block":"author_block",draftSessionId:a,blockStudioDraft:t.blockStudioDraft,activeBlockPath:t.activeBlockPath,domain:(bi=t.blockStudioMetadata)==null?void 0:bi.domain,importId:Qe==null?void 0:Qe.id,importCandidateId:(vi=Qe==null?void 0:Qe.candidates[0])==null?void 0:vi.id,...En==="edit"?{mode:"edit",blockPath:t.activeBlockPath}:{}},initialMode:"block",initialInput:uo,autoRun:fo,threadId:f.threadId,onThreadIdChange:f.onThreadIdChange,onRunningChange:oo,onInsertSql:(i,d)=>wo(i,{question:d??xe??"analysis",title:d}),onInsertDql:i=>{Co(i)},answerFirstCards:!0,insertDqlActionLabel:"Add to Block Studio",emptyHint:"Describe the governed block you need. DQL checks certified blocks and semantic metrics before creating a review-required draft.",examplePrompts:[{label:"Build from business question",prompt:"Build a reusable governed DQL block for this business question: "},{label:"Find reusable blocks",prompt:"Which certified DQL blocks already answer this analysis, and what should be reused instead of duplicated?"},{label:"Review this block",prompt:"Review this block for grain, compatible metrics and dimensions, parameters, tests, and certification gaps."}]},`${m}:${ro}`)}),!nt&&!he&&e.jsx("button",{type:"button",onClick:()=>nn(!0),title:"Open Block AI",style:{position:"absolute",right:12,top:58,width:34,height:34,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:`1px solid ${o.btnBorder}`,background:o.btnBg,color:o.accent,cursor:"pointer",boxShadow:"0 6px 18px rgba(0, 0, 0, 0.12)"},children:e.jsx(yr,{size:16,strokeWidth:2})}),gt&&t.blockStudioMetadata&&e.jsx(Ir,{metadata:t.blockStudioMetadata,onCancel:()=>{D.current=null,Ve(!1)},onConfirm:i=>{let d=$t(t.blockStudioDraft,i.name);d=ue(d,"owner",i.owner),n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...i}}),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:d}),Ve(!1)},t:o}),xt&&e.jsx(Mr,{saving:we,onCancel:()=>g(!1),onDiscard:()=>{g(!1),an()},onSave:async()=>{C.current=!0,g(!1),await cn()&&(C.current=!1,an())},t:o}),Je&&_e&&e.jsx(zr,{blockName:_e.name,blockPath:_e.path,deleting:at,error:ht,onCancel:()=>{at||(et(!1),tt(null),Re(null))},onConfirm:()=>void So(),t:o})]})}function Tr({active:t,onClick:n,label:s,busy:r,Icon:o,variant:a="secondary",title:p}){const m=qt[Ot(l=>l.themeMode)],f=a==="primary",E=a==="danger";return e.jsxs("button",{onClick:n,disabled:r,"aria-busy":r||void 0,title:p??s,style:{background:f?m.accent:E?`${m.error}0d`:t?`${m.accent}18`:m.btnBg,border:`1px solid ${f?m.accent:E?`${m.error}55`:t?m.accent:m.btnBorder}`,borderRadius:6,height:28,color:f?"#ffffff":E?m.error:t?m.accent:m.textSecondary,cursor:r?"wait":"pointer",display:"inline-flex",alignItems:"center",gap:6,fontSize:11,fontWeight:f?800:600,fontFamily:m.font,padding:"0 10px",whiteSpace:"nowrap",opacity:r?.7:1},children:[r?e.jsx(Ze,{size:13,strokeWidth:2,"aria-hidden":"true"}):o?e.jsx(o,{size:13,strokeWidth:2,"aria-hidden":"true"}):null,r?`${s}...`:s]})}function st(t){return e.jsx(Tr,{active:!1,...t})}function Dr({source:t,diagnostics:n,parameterCount:s,t:r}){const o=t.split(`
|
|
15
|
-
`),a={block:"var(--text-tertiary)",parameters:"var(--accent)",query:"var(--status-success)",tests:"var(--status-warning)",visualization:"var(--cat-audit)"},p=[];o.forEach((l,h)=>{const k=l.match(/^\s*(block|parameters|query|tests|visualization)\b/);if(k&&!p.some(b=>b.label.toLowerCase().startsWith(k[1]))){const b=k[1],P=b==="block"?"Metadata":b==="parameters"?`Parameters${s?` · ${s}`:""}`:b.charAt(0).toUpperCase()+b.slice(1);p.push({label:P,line:h+1,color:a[b]??"var(--text-tertiary)"})}});const m=(t.match(/^\s*assert\b/gm)??[]).length,f=new Set((t.match(/\b(?:from|join)\s+([a-z_][\w.]*)/gi)??[]).map(l=>l.replace(/^(from|join)\s+/i,""))).size,E=n.filter(l=>l.severity==="error");return e.jsxs("div",{style:{width:208,flexShrink:0,background:r.appBg,display:"flex",flexDirection:"column",overflow:"auto"},children:[e.jsx("div",{style:{padding:"12px 14px 6px",fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font},children:"Outline"}),e.jsx("div",{style:{padding:"0 8px",display:"flex",flexDirection:"column",gap:1},children:p.length===0?e.jsx("span",{style:{fontSize:11,color:r.textMuted,padding:"2px 8px",fontFamily:r.font},children:"No sections yet."}):p.map(l=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:6},children:[e.jsx("span",{style:{width:8,height:8,borderRadius:2,background:l.color,flexShrink:0}}),e.jsx("span",{style:{flex:1,fontSize:11.5,fontWeight:550,color:r.textSecondary,fontFamily:r.font},children:l.label}),e.jsxs("span",{style:{fontSize:10,color:r.textMuted,fontFamily:r.fontMono},children:[":",l.line]})]},l.label))}),e.jsx("div",{style:{padding:"14px 14px 6px",fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font},children:"Problems"}),E.length===0?e.jsxs("div",{style:{padding:"0 14px",fontSize:11.5,color:"var(--status-success)",display:"flex",alignItems:"center",gap:6,fontFamily:r.font},children:[e.jsx(kt,{size:12})," No problems"]}):e.jsx("div",{style:{padding:"0 14px",display:"flex",flexDirection:"column",gap:5},children:E.slice(0,4).map((l,h)=>e.jsx("span",{style:{fontSize:11,color:"var(--status-error)",lineHeight:1.4,fontFamily:r.font},children:l.message},h))}),e.jsx("div",{style:{padding:"14px 14px 6px",fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font},children:"Context"}),e.jsxs("div",{style:{padding:"0 14px 16px",display:"flex",flexDirection:"column",gap:5,fontSize:11,color:r.textSecondary,fontFamily:r.font},children:[e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:999,background:"var(--accent)"}}),s," parameter",s===1?"":"s"," bound"]}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:999,background:"var(--status-success)"}}),f," model",f===1?"":"s"," referenced"]}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:999,background:"var(--status-warning)"}}),m," test",m===1?"":"s"," declared"]})]})]})}function Pt({active:t,onClick:n,label:s,t:r}){return e.jsx("button",{type:"button",onClick:n,style:{padding:"9px 1px",fontSize:11.5,fontWeight:650,cursor:"pointer",border:"none",background:"none",fontFamily:r.font,whiteSpace:"nowrap",color:t?r.textPrimary:r.textMuted,boxShadow:t?`inset 0 -2px 0 0 ${r.accent}`:"none"},children:s})}function Ci(t,n){return Go(t,{variant:n?"accent":"ghost",size:"xs",active:n})}function Wt(t,n){return{display:"inline-flex",alignItems:"center",gap:5,background:n?"var(--accent-dim)":t.btnBg,border:`1px solid ${n?`${t.accent}55`:t.btnBorder}`,borderRadius:999,color:n?t.accent:t.textSecondary,cursor:"pointer",fontSize:11.5,fontFamily:t.fontMono,lineHeight:1.2,padding:"4px 9px"}}function Ir({metadata:t,onCancel:n,onConfirm:s,t:r}){const[o,a]=c.useState(t.name),[p,m]=c.useState(t.owner),f=!!(o.trim()&&p.trim());return e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Save block",style:{position:"absolute",inset:0,zIndex:70,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,.32)",padding:18},children:e.jsxs("div",{style:{width:420,maxWidth:"100%",display:"grid",gap:14,padding:18,borderRadius:10,border:`1px solid ${r.headerBorder}`,background:r.cellBg,boxShadow:"0 24px 70px rgba(0,0,0,.35)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:15,fontWeight:850,color:r.textPrimary},children:"Save governed block"}),e.jsx("div",{style:{marginTop:4,fontSize:11,lineHeight:1.45,color:r.textMuted},children:"Name and owner are required. DQL will run the local governance checks and certify the block when they pass; otherwise it remains a draft with blockers."})]}),e.jsx(A,{label:"Block name",t:r,children:e.jsx("input",{autoFocus:!0,value:o,onChange:E=>a(E.target.value),style:ze(r)})}),e.jsx(A,{label:"Owner",t:r,children:e.jsx("input",{value:p,onChange:E=>m(E.target.value),placeholder:"analytics@company.com or team name",style:ze(r)})}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:n,style:Z(r),children:"Cancel"}),e.jsx("button",{type:"button",disabled:!f,onClick:()=>f&&s({name:o.trim(),owner:p.trim()}),style:{...Te(r),opacity:f?1:.55},children:"Save block"})]})]})})}function Mr({saving:t,onSave:n,onDiscard:s,onCancel:r,t:o}){return e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Unsaved block",style:{position:"fixed",inset:0,zIndex:90,display:"grid",placeItems:"center",padding:20,background:"rgba(0, 0, 0, 0.42)"},children:e.jsxs("div",{style:{width:"min(430px, 100%)",border:`1px solid ${o.cellBorder}`,borderRadius:12,background:o.cellBg,padding:18,display:"grid",gap:14,boxShadow:"0 20px 60px rgba(0, 0, 0, 0.24)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:15,fontWeight:800,color:o.textPrimary,fontFamily:o.font},children:"Save this block before leaving?"}),e.jsx("div",{style:{marginTop:5,fontSize:12,lineHeight:1.5,color:o.textMuted,fontFamily:o.font},children:"Your current Block Studio workspace has unsaved changes."})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:r,disabled:t,style:Z(o),children:"Cancel"}),e.jsx("button",{type:"button",onClick:s,disabled:t,style:{...Z(o),color:o.error},children:"Discard"}),e.jsx("button",{type:"button",onClick:()=>void n(),disabled:t,style:Te(o),children:t?"Saving…":"Save block"})]})]})})}function zr({blockName:t,blockPath:n,deleting:s,error:r,onCancel:o,onConfirm:a,t:p}){return e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Delete block",style:{position:"fixed",inset:0,zIndex:95,display:"grid",placeItems:"center",padding:20,background:"rgba(0, 0, 0, 0.42)"},children:e.jsxs("div",{style:{width:"min(460px, 100%)",border:`1px solid ${p.error}55`,borderRadius:12,background:p.cellBg,padding:18,display:"grid",gap:14,boxShadow:"0 20px 60px rgba(0, 0, 0, 0.26)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:9},children:[e.jsx("span",{style:{width:30,height:30,display:"grid",placeItems:"center",borderRadius:8,background:`${p.error}12`},children:e.jsx(tn,{size:16,color:p.error})}),e.jsxs("div",{children:[e.jsxs("div",{style:{fontSize:15,fontWeight:800,color:p.textPrimary,fontFamily:p.font},children:["Delete “",t,"”?"]}),e.jsx("div",{style:{marginTop:3,fontSize:11,color:p.textMuted,fontFamily:p.fontMono},children:n})]})]}),e.jsxs("div",{style:{fontSize:12,lineHeight:1.5,color:p.textSecondary,fontFamily:p.font},children:["This removes the saved ",e.jsx("code",{children:".dql"})," block and its generated semantic companion. Unsaved editor changes are discarded. Git can recover committed versions."]}),r&&e.jsx("div",{role:"alert",style:{padding:"8px 10px",borderRadius:7,border:`1px solid ${p.error}45`,background:`${p.error}0d`,color:p.error,fontSize:11,lineHeight:1.4},children:r}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:o,disabled:s,style:Z(p),children:"Cancel"}),e.jsx("button",{type:"button",onClick:a,disabled:s,style:{...Te(p),background:p.error,borderColor:p.error,opacity:s?.65:1},children:s?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{size:13,className:"dql-spin"})," Deleting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(tn,{size:13})," Delete block"]})})]})]})})}function Pr({dbtStatus:t,semanticStats:n,semanticObjectCount:s,databaseStats:r,onCreateSql:o,onCreateSemantic:a,onImport:p,onBuildDql:m,t:f}){var P;const E=[{title:"Blank SQL block",detail:"Start with an empty custom query.",action:o,label:"Create",Icon:dr},{title:"Semantic block",detail:"Build directly from governed metrics.",action:a,label:"Build",Icon:Jt}],l=!!(t!=null&&t.artifacts.manifest.exists),h=(t==null?void 0:t.counts.metrics)??n.metrics,k=t?`${t.counts.models} dbt models · ${h} MetricFlow metrics`:"Waiting for dbt artifacts",b=(t==null?void 0:t.projectName)||((P=t==null?void 0:t.projectPath)==null?void 0:P.split("/").filter(Boolean).pop())||"dbt project";return e.jsxs("div",{style:{height:"100%",overflow:"auto",padding:22,display:"grid",gap:14,alignContent:"start",background:f.appBg},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16,flexWrap:"wrap"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:20,fontWeight:800,color:f.textPrimary,fontFamily:f.font},children:"Create DQL blocks"}),e.jsx("div",{style:{fontSize:12,color:f.textMuted,lineHeight:1.45,marginTop:5,maxWidth:560,fontFamily:f.font},children:"Start from SQL you already have, or describe the business asset you want DQL to build from project context."})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"7px 10px",border:`1px solid ${l?"#2ea04340":f.headerBorder}`,borderRadius:8,background:l?"#2ea0430d":f.cellBg},children:[e.jsx(kt,{size:15,strokeWidth:2,color:l?"#2ea043":f.textMuted,"aria-hidden":"true"}),e.jsx("span",{style:{fontSize:11,color:l?"#2ea043":f.textMuted,fontWeight:700,fontFamily:f.font},children:l?"dbt ready":"dbt pending"})]})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(260px, 1fr))",gap:10},children:[e.jsx(mn,{title:"Ask AI",detail:"Describe the business asset you need. DQL uses this domain's blocks, models, and semantic metrics to draft it.",label:"Describe block",Icon:xr,onClick:m,t:f}),e.jsx(mn,{title:"Import SQL",detail:"Paste scripts, upload files, or point at a folder. DQL analyzes candidates without writing block files until you save.",label:"Start import",Icon:Qi,onClick:p,t:f}),e.jsx(mn,{title:"Build manually",detail:"Use the visual semantic builder for multiple metrics, compatible dimensions, time grain, filters, and chart intent.",label:"Open builder",Icon:Jt,onClick:a,t:f})]}),e.jsxs("details",{style:Rt(f),children:[e.jsx("summary",{style:Et(f),children:"Manual options"}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))",gap:10},children:E.map(L=>e.jsx(Rr,{title:L.title,detail:L.detail,label:L.label,Icon:L.Icon,onClick:L.action,t:f},L.title))})]}),e.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))",gap:8},children:[e.jsx(gn,{Icon:vn,label:`${b} dbt`,value:k,tone:l?"success":"neutral",t:f}),e.jsx(gn,{Icon:vn,label:"Database",value:`${r.tables} tables`,tone:r.tables>0?"success":"neutral",t:f}),e.jsx(gn,{Icon:Jt,label:"DQL semantic layer",value:`${s} objects`,tone:s>0?"success":"neutral",t:f})]})]})}function mn({title:t,detail:n,label:s,Icon:r,onClick:o,t:a}){return e.jsxs("button",{onClick:o,style:{border:`1px solid ${a.accent}`,borderRadius:8,background:a.cellBg,color:a.textPrimary,cursor:"pointer",display:"grid",gridTemplateColumns:"42px minmax(0, 1fr) auto",gap:12,alignItems:"center",padding:16,minHeight:104,textAlign:"left",fontFamily:a.font,boxShadow:`inset 0 0 0 1px ${a.accent}22`},children:[e.jsx("span",{style:{width:42,height:42,borderRadius:8,display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${a.accent}18`,color:a.accent},children:e.jsx(r,{size:20,strokeWidth:2,"aria-hidden":"true"})}),e.jsxs("span",{style:{display:"grid",gap:5,minWidth:0},children:[e.jsx("span",{style:{fontSize:15,fontWeight:850,color:a.textPrimary},children:t}),e.jsx("span",{style:{fontSize:12,color:a.textMuted,lineHeight:1.4},children:n})]}),e.jsx("span",{style:{color:"#ffffff",background:a.accent,borderRadius:6,padding:"7px 10px",fontSize:11,fontWeight:800,whiteSpace:"nowrap"},children:s})]})}function Rr({title:t,detail:n,label:s,Icon:r,onClick:o,t:a}){return e.jsxs("button",{onClick:o,style:{textAlign:"left",background:a.cellBg,border:`1px solid ${a.headerBorder}`,borderRadius:8,padding:12,cursor:"pointer",color:a.textPrimary,display:"grid",gridTemplateColumns:"30px minmax(0, 1fr)",gap:10,minHeight:94,fontFamily:a.font,alignItems:"start"},children:[e.jsx("span",{style:{width:30,height:30,borderRadius:7,display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${a.accent}14`,color:a.accent},children:e.jsx(r,{size:16,strokeWidth:2,"aria-hidden":"true"})}),e.jsxs("span",{style:{display:"grid",gap:5,minWidth:0},children:[e.jsx("span",{style:{fontSize:13,fontWeight:800,color:a.textPrimary},children:t}),e.jsx("span",{style:{fontSize:11,color:a.textMuted,lineHeight:1.35},children:n}),e.jsx("span",{style:{color:a.accent,fontSize:11,fontWeight:800},children:s})]})]})}function gn({Icon:t,label:n,value:s,tone:r,t:o}){const a=r==="success"?"#2ea043":o.textMuted;return e.jsxs("div",{style:{border:`1px solid ${o.headerBorder}`,borderRadius:8,background:o.cellBg,padding:"9px 10px",display:"flex",alignItems:"center",gap:8,minWidth:0},children:[e.jsx("span",{style:{color:a,display:"inline-flex",flexShrink:0},children:e.jsx(t,{size:15,strokeWidth:2,"aria-hidden":"true"})}),e.jsxs("span",{style:{display:"grid",gap:2,minWidth:0},children:[e.jsx("span",{style:{fontSize:10,color:o.textMuted,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),e.jsx("span",{style:{fontSize:12,color:o.textPrimary,fontWeight:700,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s})]})]})}function Er({source:t,databaseStats:n,semanticCount:s,onChange:r,onOpenExplorer:o,onOpenAi:a,t:p}){const m=l=>{var h;return((h=t.match(new RegExp(`\\b${l}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:h[1])??""},f=l=>{var h;return(((h=t.match(new RegExp(`\\b${l}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i")))==null?void 0:h[1].match(/"([^"]*)"/g))??[]).map(k=>k.slice(1,-1))},E=[{key:"primaryTerms",label:"Business terms",hint:"net revenue, active customer"},{key:"sourceSystems",label:"Source systems",hint:"billing, product events"},{key:"synonyms",label:"Question aliases",hint:"sales, bookings"}];return e.jsxs("div",{style:{padding:"10px 14px",borderBottom:`1px solid ${p.headerBorder}`,background:p.appBg,display:"grid",gap:10},children:[e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"},children:[e.jsx("div",{style:{fontSize:12,fontWeight:750,color:p.textPrimary},children:"Block context"}),e.jsx("span",{style:{fontSize:11,color:p.textMuted},children:"Only grounded context is kept with the block and used for retrieval."}),e.jsx("div",{style:{flex:1}}),e.jsxs("button",{type:"button",onClick:o,style:Z(p),children:[n.tables," database tables"]}),e.jsx("button",{type:"button",onClick:a,style:Z(p),children:"Review with AI"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(230px, 1fr))",gap:10},children:[e.jsx(A,{label:"Business outcome",t:p,children:e.jsx(_t,{value:m("businessOutcome"),onChange:l=>r(ue(t,"businessOutcome",l)),placeholder:"Decision or outcome this block supports",style:ze(p)})}),e.jsx(A,{label:"Agent guidance",t:p,children:e.jsx(_t,{value:m("llmContext"),onChange:l=>r(ue(t,"llmContext",l)),placeholder:"When to use this block",style:ze(p)})}),E.map(l=>e.jsx(Lr,{label:l.label,hint:l.hint,values:f(l.key),onChange:h=>r(Vo(t,l.key,h)),t:p},l.key)),e.jsx(A,{label:"Rules and caveats",t:p,children:e.jsx(_t,{value:m("caveats"),onChange:l=>r(ue(t,"caveats",l)),placeholder:"Known limitation or interpretation rule",style:ze(p)})})]}),e.jsxs("div",{style:{fontSize:10,color:p.textMuted},children:["Available authoring context: ",s," semantic objects, ",n.schemas," schemas, ",n.columns," columns. SQL completion uses the same loaded catalog."]})]})}function Lr({label:t,hint:n,values:s,onChange:r,t:o}){const[a,p]=c.useState(""),m=()=>{const f=a.split(",").map(E=>E.trim()).filter(Boolean);f.length>0&&r([...s,...f]),p("")};return e.jsx(A,{label:t,t:o,children:e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:5,padding:6,minHeight:36,border:`1px solid ${o.cellBorder}`,borderRadius:6,background:o.cellBg},children:[s.map(f=>e.jsxs("button",{type:"button",onClick:()=>r(s.filter(E=>E!==f)),title:"Remove",style:{...Wt(o,!0),border:"none",cursor:"pointer"},children:[f," ×"]},f)),e.jsx("input",{value:a,onChange:f=>p(f.target.value),onKeyDown:f=>{(f.key==="Enter"||f.key===",")&&(f.preventDefault(),m())},onBlur:m,placeholder:s.length?"Add another…":n,style:{minWidth:120,flex:1,border:"none",outline:"none",background:"transparent",color:o.textPrimary,fontSize:11,fontFamily:o.font}})]})})}function Ui({source:t,kind:n,onChange:s,t:r}){const o=c.useMemo(()=>tr(t),[t]),[a,p]=c.useState(""),[m,f]=c.useState(""),[E,l]=c.useState(!0),[h,k]=c.useState("dynamic"),[b,P]=c.useState("auto"),L=hn(m,a),K=b==="auto"?L:b,_=ze(r),w=()=>{a.trim()&&(s(ki(t,{name:a,type:K,required:E&&!m.trim(),defaultText:m,policy:h})),p(""),f(""),l(!0),k("dynamic"),P("auto"))};return e.jsx(be,{title:"Runtime parameters",t:r,children:e.jsxs("div",{style:{display:"grid",gap:10},children:[e.jsxs("div",{style:{fontSize:11,color:r.textMuted,lineHeight:1.45},children:["Add a values-only input once, then reuse this block for a different period, region, customer set, or limit.",n==="custom"?e.jsxs(e.Fragment,{children:[" Use ",e.jsx("code",{children:"${parameter_name}"})," in SQL where the value belongs; DQL always binds it safely."]}):" Choose a semantic field above as a filter to create its governed parameter binding."]}),o.length>0&&e.jsx("div",{style:{display:"grid",gap:7},children:o.map(x=>{var re;const X=nr(x),H=$=>s(ki(t,{name:x.name,type:$.type??x.type,required:$.required??x.required,defaultText:$.defaultText??X,policy:$.policy??x.policy}));return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 1fr) 122px minmax(150px, 1fr) 118px auto",gap:7,alignItems:"center",padding:8,border:`1px solid ${r.cellBorder}`,borderRadius:7,background:r.cellBg},children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:11,fontWeight:800,color:r.textPrimary},children:x.name}),e.jsxs("div",{style:{fontSize:10,color:r.textMuted},children:[((re=x.binding)==null?void 0:re.kind)??"declared value"," · ",x.required?"required":"has default"]})]}),e.jsx("select",{"aria-label":`${x.name} type`,value:x.type,onChange:$=>H({type:$.target.value}),style:_,children:Bi.map($=>e.jsx("option",{value:$,children:$},$))}),x.type==="boolean"?e.jsxs("select",{"aria-label":`${x.name} default`,value:X,onChange:$=>H({defaultText:$.target.value,required:!1}),style:_,children:[e.jsx("option",{value:"",children:"Required / no default"}),e.jsx("option",{value:"true",children:"True"}),e.jsx("option",{value:"false",children:"False"})]}):e.jsx("input",{"aria-label":`${x.name} default`,value:X,onChange:$=>{const G=$.target.value,J=x.type===hn(X,x.name);H({defaultText:G,required:G.trim()?!1:x.required,...J?{type:hn(G,x.name)}:{}})},placeholder:x.type.endsWith("[]")?"West, East":x.required?"Required value":"Default value",style:_}),e.jsx("select",{"aria-label":`${x.name} policy`,value:x.policy,onChange:$=>H({policy:$.target.value}),style:_,children:$r.map($=>e.jsx("option",{value:$,children:$},$))}),e.jsx("button",{type:"button",onClick:()=>s(ir(t,x.name)),title:`Remove ${x.name}`,style:{border:"none",background:"transparent",color:r.error,cursor:"pointer",fontSize:16,padding:"3px 5px"},children:"×"})]},x.name)})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(140px, 1fr) minmax(150px, 1.3fr) 150px 130px auto",gap:7,alignItems:"center",padding:9,border:`1px dashed ${r.btnBorder}`,borderRadius:7,background:r.appBg},children:[e.jsx("input",{"aria-label":"New parameter name",value:a,onChange:x=>p(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),w())},placeholder:"region_set",style:_}),e.jsx("input",{"aria-label":"New parameter default",value:m,onChange:x=>{f(x.target.value),x.target.value.trim()&&l(!1)},onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),w())},placeholder:"Central, East or 2026-01-01",style:_}),e.jsxs("select",{"aria-label":"New parameter type",value:b,onChange:x=>P(x.target.value),style:_,children:[e.jsxs("option",{value:"auto",children:["Auto · ",L]}),Bi.map(x=>e.jsx("option",{value:x,children:x},x))]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:5,color:r.textSecondary,fontSize:11,whiteSpace:"nowrap"},children:[e.jsx("input",{type:"checkbox",checked:E&&!m.trim(),onChange:x=>l(x.target.checked)})," Required"]}),e.jsx("button",{type:"button",onClick:w,disabled:!a.trim(),style:{...Te(r),opacity:a.trim()?1:.5},children:"Add"})]}),e.jsxs("div",{style:{fontSize:10,color:r.textMuted},children:["Type is inferred from a value you enter: ",e.jsx("code",{children:"10"})," → number, ",e.jsx("code",{children:"2026-01-01"})," → date, ",e.jsx("code",{children:"West, East"})," → string[]. You can override it at any time."]})]})})}const Bi=["string","number","boolean","date","string[]","number[]","date[]"],$r=["dynamic","static","business","derived","optional","ambiguous_review_required"];function Ar({metadata:t,source:n,parameters:s,preview:r,lastRun:o,lineageDetail:a,isSemanticBlock:p,running:m,onOpenBuilder:f,onOpenSource:E,onDelete:l,onRun:h,onOpenHistory:k,t:b}){var te,Q,pe,Se,Pe;const P=((t==null?void 0:t.reviewStatus)??"").toLowerCase()==="certified",L=(t==null?void 0:t.name)||"block",K=p?$i(n):null,_=((Q=(te=n.match(/query\s*=\s*"""([\s\S]*?)"""/i))==null?void 0:te[1])==null?void 0:Q.trim())??"",w=K?Array.from(new Set([...K.dimensions,...K.timeDimension?[K.timeDimension]:[],...K.metrics])):Yi(_),x=(n.match(/^\s*assert\b.*$/gm)??[]).map(z=>z.trim()),X=((pe=a==null?void 0:a.incoming)==null?void 0:pe.length)??0,H=((Se=a==null?void 0:a.outgoing)==null?void 0:Se.length)??0,[re,$]=c.useState(!1),G=((a==null?void 0:a.incoming)??[]).map(z=>{var Y;return(Y=z.node)==null?void 0:Y.name}).filter(Boolean).slice(0,3),J=((a==null?void 0:a.outgoing)??[]).map(z=>{var Y;return(Y=z.node)==null?void 0:Y.name}).filter(Boolean).slice(0,3),I={fontSize:11,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:b.textMuted,marginBottom:8,fontFamily:b.font},N=(z,Y=!1)=>e.jsx("span",{style:{padding:"3px 9px",borderRadius:999,border:`1px solid ${Y?`${b.accent}59`:b.headerBorder}`,background:Y?"var(--accent-dim)":"var(--bg-1)",color:Y?b.accent:b.textSecondary,fontFamily:b.fontMono,fontWeight:Y?600:400,fontSize:11.5},children:z},z),q=e.jsx("span",{style:{color:b.textMuted,fontSize:11},children:"→"}),V=(r==null?void 0:r.result.executionTime)??(o==null?void 0:o.executionTime),ve=[["Last run",r||o?typeof V=="number"?`${(V/1e3).toFixed(1)}s`:"Completed":"Not run yet"],["Rows",r?String(r.result.rowCount??r.result.rows.length):o?String(o.rowCount):"—"],["Used in",H>0?`${H} downstream`:"—"],["Tests",x.length>0?`${x.length} declared`:"None yet"]];return e.jsx("div",{style:{height:"100%",overflow:"auto",background:b.appBg},children:e.jsxs("div",{style:{width:"min(860px, 100% - 48px)",margin:"0 auto",padding:"26px 0 40px",display:"flex",flexDirection:"column",gap:20,animation:"dql-agent-fadein 0.25s ease-out",fontFamily:b.font},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:14},children:[e.jsx("span",{style:{width:42,height:42,borderRadius:10,background:P?"var(--status-success-bg)":"var(--accent-dim)",color:P?"var(--status-success)":b.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border-subtle)"},children:e.jsx(Jt,{size:20,strokeWidth:1.75})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:9,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:17,fontWeight:700,color:b.textPrimary,fontFamily:b.fontMono,letterSpacing:"-0.01em"},children:L}),t!=null&&t.reviewStatus?e.jsx(Ni,{status:t.reviewStatus,t:b}):null]}),e.jsx("div",{style:{fontSize:12,color:b.textMuted,marginTop:4},children:[t==null?void 0:t.domain,t!=null&&t.folderPath?`folder: ${t.folderPath}`:null,t==null?void 0:t.owner,...(Pe=t==null?void 0:t.tags)!=null&&Pe.length?[t.tags.join(", ")]:[]].filter(Boolean).join(" · ")||"Unsaved draft"})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexShrink:0},children:[e.jsxs("button",{type:"button",onClick:f,style:{display:"inline-flex",alignItems:"center",gap:7,height:32,padding:"0 14px",borderRadius:8,border:"none",background:b.accent,color:"#fff",fontSize:12.5,fontWeight:650,cursor:"pointer",fontFamily:b.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)"},children:[e.jsx(cr,{size:13,strokeWidth:1.75})," Open in builder"]}),e.jsxs("button",{type:"button",onClick:h,disabled:m,style:{display:"inline-flex",alignItems:"center",gap:6,height:32,padding:"0 13px",borderRadius:8,border:`1px solid ${b.headerBorder}`,background:b.cellBg,color:b.textSecondary,fontSize:12.5,fontWeight:600,cursor:"pointer",fontFamily:b.font,opacity:m?.7:1},children:[m?e.jsx(Ze,{size:12,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):e.jsx(Hi,{size:11,fill:"currentColor"})," Run"]}),e.jsx("button",{type:"button","aria-label":`Delete ${L}`,title:"Delete block",onClick:l,style:{width:32,height:32,borderRadius:8,border:`1px solid ${b.error}55`,background:`${b.error}0d`,color:b.error,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:e.jsx(tn,{size:14})}),e.jsx("button",{type:"button",title:"History and metadata",onClick:k,style:{width:32,height:32,borderRadius:8,border:`1px solid ${b.headerBorder}`,background:b.cellBg,color:b.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:e.jsx(ur,{size:15})})]})]}),t!=null&&t.description?e.jsx("div",{style:{fontSize:13.5,lineHeight:1.6,color:b.textSecondary,maxWidth:640},children:t.description}):null,e.jsx("div",{style:{display:"flex",border:"1px solid var(--border-subtle)",borderRadius:10,background:b.cellBg,overflow:"hidden"},children:ve.map(([z,Y],we)=>e.jsxs("div",{style:{flex:1,padding:"12px 16px",borderRight:we<ve.length-1?"1px solid var(--border-subtle)":"none"},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:b.textMuted},children:z}),e.jsx("div",{style:{fontSize:14,fontWeight:650,color:b.textPrimary,marginTop:3},children:Y})]},z))}),e.jsxs("div",{children:[e.jsx("div",{style:I,children:"Outputs"}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:w.length>0?w.map(z=>e.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11.5,padding:"4px 10px",borderRadius:999,background:"var(--accent-dim)",color:b.accent,border:`1px solid ${b.accent}33`,fontFamily:b.fontMono},children:z},z)):e.jsx("span",{style:{fontSize:11.5,color:b.textMuted},children:"Open the builder to define outputs."})})]}),e.jsxs("div",{children:[e.jsx("div",{style:I,children:"Parameters"}),e.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:9,overflow:"hidden",background:b.cellBg},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1.2fr 0.8fr 1fr 0.9fr",gap:8,padding:"7px 12px",background:"var(--bg-1)",borderBottom:"1px solid var(--border-subtle)",fontSize:10.5,fontWeight:700,color:b.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:[e.jsx("span",{children:"Name"}),e.jsx("span",{children:"Type"}),e.jsx("span",{children:"Default"}),e.jsx("span",{children:"Policy"})]}),s.length===0?e.jsx("div",{style:{padding:"9px 12px",fontSize:12,color:b.textMuted},children:"No parameters — this block always runs the same way."}):s.map((z,Y)=>e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1.2fr 0.8fr 1fr 0.9fr",gap:8,padding:"8px 12px",borderBottom:Y<s.length-1?"1px solid var(--border-subtle)":"none",fontSize:12,alignItems:"center"},children:[e.jsx("span",{style:{fontFamily:b.fontMono,fontWeight:600,color:b.textPrimary},children:z.name}),e.jsx("span",{style:{color:b.textSecondary},children:z.type}),e.jsx("span",{style:{fontFamily:b.fontMono,color:z.default!==void 0&&z.default!==null&&z.default!==""?"var(--status-warning)":b.textMuted},children:z.default!==void 0&&z.default!==null&&z.default!==""?JSON.stringify(z.default):z.required?"required":"—"}),e.jsx("span",{style:{color:b.textMuted},children:z.policy})]},z.name))]})]}),e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[e.jsx("span",{style:{...I,marginBottom:0},children:"DQL source"}),e.jsxs("button",{type:"button",onClick:E,style:{display:"inline-flex",alignItems:"center",gap:5,border:"none",background:"none",color:b.accent,fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:b.font,padding:0},children:["Open in DQL Source ",e.jsx(bn,{size:11,strokeWidth:2})]})]}),e.jsx("pre",{style:{margin:0,border:"1px solid var(--border-subtle)",background:b.cellBg,borderRadius:9,padding:"13px 15px",fontSize:11.5,lineHeight:1.65,fontFamily:b.fontMono,whiteSpace:"pre",overflowX:"auto",color:b.textPrimary,maxHeight:320,overflowY:"auto"},children:n.trim()||"Open the builder to author this block."})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:20},children:[e.jsxs("div",{children:[e.jsx("div",{style:I,children:"Tests"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:x.length>0?x.map(z=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12},children:[e.jsx(kt,{size:13,color:"var(--status-success)",strokeWidth:2,style:{flexShrink:0}}),e.jsx("span",{style:{fontFamily:b.fontMono,color:b.textSecondary},children:z})]},z)):e.jsx("span",{style:{fontSize:11.5,color:b.textMuted},children:"No tests yet — add assertions in the builder before certification."})})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>$(z=>!z),style:{display:"flex",alignItems:"center",gap:6,border:"none",background:"none",cursor:"pointer",padding:0,fontFamily:b.font,marginBottom:8},children:[e.jsx(bn,{size:11,color:b.textMuted,strokeWidth:2,style:{transform:re?"rotate(90deg)":"none",transition:"transform 0.12s"}}),e.jsx("span",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:b.textMuted},children:"Lineage"}),re?null:e.jsxs("span",{style:{fontSize:10.5,color:b.textMuted},children:[X," upstream · ",H," downstream"]})]}),re?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap",fontSize:11.5,animation:"dql-agent-fadein 0.18s ease-out"},children:[G.length>0?G.map(z=>N(z)):N("no upstream"),q,N(L,!0),q,J.length>0?J.map(z=>N(z)):N("no downstream yet")]}):null]})]})]})})}function _r({source:t,metadata:n,semanticLayer:s,dbtStatus:r,domainOptions:o,chartConfig:a,onChange:p,onMetadataChange:m,onOpenAi:f,onSetupRuntime:E,t:l}){const h=$i(t),k={...h,filters:h.requestedFilters},[b,P]=c.useState([]),[L,K]=c.useState(!1),[_,w]=c.useState(null),[x,X]=c.useState(null),[H,re]=c.useState(0);c.useEffect(()=>{let u=!1;if(k.metrics.length===0){P([]),w(null),X(null),K(!1);return}return P([]),w(null),K(!0),X(null),W.getCompatibility(k.metrics).then(M=>{u||(w(M),P(M.dimensions))}).catch(M=>{u||(P([]),X(M instanceof Error?M.message:String(M)))}).finally(()=>{u||K(!1)}),()=>{u=!0}},[s.dimensions,k.metrics.join("|"),H]);const $=new Set(b.flatMap(u=>[u.reference??u.name,u.name])),G=new Map(b.flatMap(u=>[[u.reference??u.name,u.qualifiedName??void 0],[u.name,u.qualifiedName??void 0]])),J=new Map(((_==null?void 0:_.incompatible)??[]).map(u=>[u.name,Cr(u.reason)])),I=new Map(b.flatMap(u=>[[u.reference??u.name,u],[u.name,u]])),N=Array.from(new Map([...s.dimensions,...s.timeDimensions].map(u=>{const M=u.reference??u.name;return[M,{...u,name:M}]})).values()),q=new Map(N.flatMap(u=>[[u.name,u],[u.reference??u.name,u]])),V=b.map(u=>{const M=u.reference??u.name;return{...q.get(M)??q.get(u.name),...u,name:M}}),ve=V.filter(u=>u.isTimeDimension||u.type==="time"),te=jn(l),[Q,pe]=c.useState(""),[Se,Pe]=c.useState(""),z=c.useMemo(()=>new Map(s.metrics.map(u=>[u.name,u])),[s.metrics]),Y=c.useMemo(()=>new Map([...N,...V].flatMap(u=>[[u.name,u],[u.reference??u.name,u]])),[N,V]),we=c.useMemo(()=>Ti(s.metrics,Q),[s.metrics,Q]),fe=c.useMemo(()=>Ti(V,Se),[V,Se]),De=_i(t,"tests"),ge=Array.from(new Set([...k.dimensions,...k.timeDimension?[k.timeDimension]:[],...k.metrics])),Ae=(u,M)=>{m({[u]:M}),p(u==="name"?$t(t,M):ue(t,u,M))},ke=u=>{const M=k.metrics.includes(u)?k.metrics.filter(ee=>ee!==u):[...k.metrics,u];p(Ei(t,M))},Ie=u=>p(Li(t,"dimensions",u)),Ce=u=>{const M=k.dimensions.includes(u)?k.dimensions.filter(ee=>ee!==u):[...k.dimensions,u];Ie(M)};return c.useEffect(()=>{if(!_||k.metrics.length===0)return;const u=Yo(t,Array.from($));u!==t&&p(u)},[_,t]),e.jsx("div",{style:{height:"100%",overflow:"auto",background:l.appBg},children:e.jsxs("div",{style:{width:"min(820px, 100% - 48px)",margin:"0 auto",padding:"24px 0 40px",display:"flex",flexDirection:"column",animation:"dql-agent-fadein 0.25s ease-out"},children:[e.jsx(Ki,{metadata:n,domains:o,onTextChange:Ae,onFolderChange:u=>m({folderPath:u}),onTagsChange:u=>{m({tags:u}),p(At(t,u))},t:l}),e.jsxs(be,{title:"Metric and grain",hint:"Pick governed semantic objects — they compile to the DQL script.",t:l,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsxs("span",{style:{fontSize:11,fontWeight:750,color:l.textSecondary},children:["Governed metrics · ",k.metrics.length," selected"]}),L&&e.jsx("span",{style:{fontSize:10,color:l.textMuted},children:"Checking compatibility…"})]}),e.jsx(Di,{kind:"metric",total:s.metrics.length,search:Q,onSearchChange:pe,matches:we,pool:s.metrics,selected:k.metrics,resolveLabel:u=>{var M;return((M=z.get(u))==null?void 0:M.label)||u},onToggle:ke,compatible:u=>{var M,ee,de,se;return((ee=(M=z.get(u))==null?void 0:M.execution)==null?void 0:ee.status)!=="requires_setup"&&((se=(de=z.get(u))==null?void 0:de.execution)==null?void 0:se.status)!=="unsupported"},t:l}),s.metrics.some(u=>u.execution&&u.execution.status!=="ready")&&e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",fontSize:10.5,color:l.textMuted,lineHeight:1.4},children:[e.jsx("span",{style:{flex:1},children:"Complex metrics are imported but need a full semantic runtime to execute."}),e.jsx("button",{type:"button",onClick:E,style:{border:"none",background:"transparent",color:l.accent,fontSize:10.5,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Set up runtime →"})]}),((_==null?void 0:_.engine)||(_==null?void 0:_.degraded))&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:10,color:l.textMuted,marginTop:2},children:[e.jsxs("span",{style:{padding:"1px 7px",borderRadius:999,background:"var(--accent-dim)",color:"var(--accent)",fontWeight:700},children:["Runs via ",wr[_.engine]??_.engine]}),_.degraded&&e.jsx("span",{style:{color:"var(--status-warning)"},children:_.degraded})]}),x&&e.jsxs("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"var(--status-warning)",lineHeight:1.4,marginTop:4},children:[e.jsx(ft,{size:14,style:{flexShrink:0}}),e.jsxs("span",{style:{flex:1},children:["Could not verify governed dimensions: ",x,". Dimension selection is paused so an unapproved join cannot be saved."]}),e.jsx("button",{type:"button",onClick:()=>re(u=>u+1),style:Z(l),children:"Retry"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 150px",gap:8},children:[e.jsx(A,{label:"Time dimension",t:l,children:e.jsxs("select",{disabled:k.metrics.length===0||L||!!x,value:k.timeDimension,onChange:u=>p(Si(t,"time_dimension",u.target.value)),style:{...te,opacity:k.metrics.length===0||L||x?.6:1},children:[e.jsx("option",{value:"",children:"None"}),ve.map(u=>e.jsxs("option",{value:u.reference??u.name,children:[u.label||u.name," · ",u.name]},u.reference??u.name))]})}),e.jsx(A,{label:"Grain",t:l,children:e.jsxs("select",{value:k.granularity,onChange:u=>p(Si(t,"granularity",u.target.value)),style:te,children:[e.jsx("option",{value:"",children:"None"}),Br(k.timeDimension,I,s.timeDimensions).map(u=>e.jsx("option",{value:u,children:u},u))]})})]}),s.metrics.length===0&&(s.loading?e.jsxs("div",{role:"status",style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:l.textMuted,lineHeight:1.45},children:[e.jsx(Ze,{size:14,className:"dql-spin"}),"Loading ",((r==null?void 0:r.counts.metrics)??0).toLocaleString()," semantic metrics from parsed dbt artifacts… Large catalogs continue loading in the background."]}):((r==null?void 0:r.counts.metrics)??0)>0||r!=null&&r.artifacts.semanticManifest.exists?e.jsxs("div",{role:"alert",style:{fontSize:12,color:"var(--status-warning)",lineHeight:1.45},children:["dbt artifacts contain ",((r==null?void 0:r.counts.metrics)??0).toLocaleString()," metrics, but Block Studio could not load them. Refresh the semantic layer; another dbt parse is not required."]}):e.jsx("div",{style:{fontSize:12,color:"var(--status-warning)",lineHeight:1.45},children:"No semantic metrics were discovered. Run dbt parse or import a semantic layer, then refresh Block Studio."})),k.metrics.length>1&&_&&b.length===0&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"#d29922",fontSize:11,lineHeight:1.4},children:[e.jsx(ft,{size:14})," These metrics do not expose a common dimension or join path.",e.jsx("button",{type:"button",onClick:f,style:Z(l),children:"Resolve with AI"})]})]}),e.jsxs(be,{title:"Chart intent",hint:"How apps and answers render this block by default.",t:l,children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:10},children:[e.jsx(A,{label:"Type",t:l,children:e.jsxs("select",{value:a.chart??"table",onChange:u=>p(Ke(t,{...a,chart:u.target.value})),style:te,children:[e.jsx("option",{value:"table",children:"Table"}),qi.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))]})}),e.jsx(A,{label:"X axis",t:l,children:e.jsxs("select",{value:a.x??"",onChange:u=>p(Ke(t,{...a,x:u.target.value})),style:te,children:[e.jsx("option",{value:"",children:"Auto"}),ge.map(u=>e.jsx("option",{value:u,children:Xe(u)},u))]})}),e.jsx(A,{label:"Y axis",t:l,children:e.jsxs("select",{value:a.y??"",onChange:u=>p(Ke(t,{...a,y:u.target.value})),style:te,children:[e.jsx("option",{value:"",children:"Auto"}),ge.map(u=>e.jsx("option",{value:u,children:Xe(u)},u))]})}),e.jsx(A,{label:"Series / color",t:l,children:e.jsxs("select",{value:a.color??"",onChange:u=>p(Ke(t,{...a,color:u.target.value})),style:te,children:[e.jsx("option",{value:"",children:"None"}),ge.map(u=>e.jsx("option",{value:u,children:Xe(u)},u))]})})]}),e.jsx(A,{label:"Title",t:l,children:e.jsx("input",{value:a.title??"",onChange:u=>p(Ke(t,{...a,title:u.target.value})),placeholder:"Chart title",style:te})})]}),e.jsx(be,{title:"Dimensions",hint:"Governed group-bys checked against the metric's join path.",t:l,children:k.metrics.length===0?e.jsx("div",{style:{fontSize:12,color:l.textMuted},children:"Choose one or more governed metrics first. Only their connected, approved dimensions will appear."}):L?e.jsxs("div",{role:"status",style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:l.textMuted},children:[e.jsx(Ze,{size:14,className:"dql-spin"}),"Checking common governed dimensions…"]}):x?e.jsx("div",{style:{fontSize:12,color:"var(--status-warning)"},children:"Dimension selection is unavailable until compatibility succeeds."}):V.length===0?e.jsx("div",{style:{fontSize:12,color:l.textMuted},children:"No dimensions are loaded yet."}):e.jsx(Di,{kind:"dimension",total:V.length,search:Se,onSearchChange:Pe,matches:fe,pool:V,selected:k.dimensions,resolveLabel:u=>{var M;return((M=Y.get(u))==null?void 0:M.label)||u},resolveMachineName:u=>{var M;return G.get(u)??((M=Y.get(u))==null?void 0:M.name)??u},reasonFor:u=>J.get(u),onToggle:Ce,compatible:u=>$.has(u),disabled:k.metrics.length===0||L||!!x,emptyHint:L?"Checking common governed dimensions…":x?"Retry compatibility before selecting dimensions.":"Choose a metric first; dimensions are checked against its governed join path.",t:l})}),e.jsxs(be,{title:"Filters and parameters",hint:"Values-only inputs so this block is reusable across periods and regions.",t:l,children:[e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:Array.from(new Set([...k.dimensions,...k.timeDimension?[k.timeDimension]:[]])).map(u=>{var ee;const M=k.filters.includes(u);return e.jsx("button",{type:"button",onClick:()=>p(Xo(t,M?k.filters.filter(de=>de!==u):[...k.filters,u])),style:Wt(l,M),children:((ee=Y.get(u))==null?void 0:ee.label)||u},u)})}),e.jsx("div",{style:{fontSize:10,color:l.textMuted,marginTop:8},children:k.dimensions.length===0&&!k.timeDimension?"Search and add a compatible dimension first, then choose whether it should also be a dynamic filter.":"Selected fields become governed runtime filters. Values stay dynamic rather than being hard-coded into SQL."}),k.filters.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:k.filters.map(u=>e.jsxs("span",{style:Wt(l,!0),children:[Xe(u)," · dynamic"]},u))})]}),e.jsx(Ui,{source:t,kind:"semantic",onChange:p,t:l}),e.jsx(be,{title:`Output fields${ge.length?` · ${ge.length}`:""}`,hint:"What consumers see when this block answers a question.",t:l,children:e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:ge.length>0?ge.map(u=>e.jsx("span",{style:Wt(l,!0),children:Xe(u)},u)):e.jsx("span",{style:{fontSize:11,color:l.textMuted},children:"Select metrics and dimensions to define outputs."})})}),e.jsx(be,{title:"Tests",hint:"Assertions checked on every run and required for certification.",t:l,children:e.jsx(_t,{multiline:!0,value:De,onChange:u=>p(Wi(t,"tests",u)),placeholder:`assert row_count >= 1
|
|
16
|
-
assert total_revenue >= 0`,style:{...te,minHeight:64,resize:"vertical",fontFamily:l.fontMono}})}),e.jsxs("details",{style:{padding:"14px 0",color:l.textSecondary,fontFamily:l.font},children:[e.jsx("summary",{style:{cursor:"pointer",fontSize:11,fontWeight:750},children:"Generated DQL preview"}),e.jsx("pre",{style:{maxHeight:240,overflow:"auto",margin:"10px 0 0",whiteSpace:"pre-wrap",color:l.textSecondary,fontSize:11,lineHeight:1.45,fontFamily:l.fontMono,border:"1px solid var(--border-subtle)",background:"var(--bg-2)",borderRadius:9,padding:"12px 14px"},children:t})]})]})})}function
|
|
9
|
+
`}),e.jsxs("div",{style:{height:46,flexShrink:0,display:"flex",alignItems:"center",gap:10,padding:"0 16px",borderBottom:`1px solid ${o.headerBorder}`,background:o.cellBg,overflowX:"auto"},children:[Le&&e.jsx("button",{onClick:()=>Ht(!1),style:{background:"transparent",border:"none",color:o.textMuted,cursor:"pointer",fontSize:14,fontFamily:o.font,padding:0,lineHeight:1},title:"Open explorer",children:"›"}),e.jsxs("button",{type:"button",onClick:qn,title:"Back to Block Studio",className:"dql-hover",style:{display:"inline-flex",alignItems:"center",gap:4,background:"transparent",border:"none",padding:"2px 4px",margin:"0 -4px",borderRadius:6,color:o.textMuted,fontSize:12,fontFamily:o.font,whiteSpace:"nowrap",cursor:"pointer"},children:[e.jsx(xr,{size:12,strokeWidth:2})," Blocks"]}),e.jsx(bn,{size:11,color:o.textMuted,style:{flexShrink:0}}),e.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:o.textPrimary,fontFamily:o.fontMono,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:220},children:xe||((ni=t.blockStudioMetadata)==null?void 0:ni.name)||(Ye?"new_block":ot?"semantic":"sql")}),((ii=t.blockStudioMetadata)==null?void 0:ii.reviewStatus)&&e.jsx(qi,{status:t.blockStudioMetadata.reviewStatus,t:o}),Ye&&Dn==="manual"&&Bt!=="detail"&&e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:2,padding:2,border:`1px solid ${o.headerBorder}`,borderRadius:7,background:o.appBg,marginLeft:6,flexShrink:0},children:[e.jsx("button",{type:"button",onClick:()=>ie("visual"),style:Ci(o,Bt==="visual"),children:"Visual Builder"}),e.jsx("button",{type:"button",onClick:()=>ie("source"),style:Ci(o,Bt==="source"),children:"DQL Source"})]}),Ye&&e.jsx(st,{label:`Context${Pi(t.blockStudioDraft)?` (${Pi(t.blockStudioDraft)})`:""}`,Icon:vn,onClick:()=>mo(i=>!i)}),e.jsx("div",{style:{flex:1}}),t.activeBlockPath&&e.jsx(st,{label:"Delete",Icon:tn,variant:"danger",title:"Delete this saved block",onClick:()=>{var i;return un(t.activeBlockPath,((i=t.blockStudioMetadata)==null?void 0:i.name)||xe||t.activeBlockPath)}}),e.jsx(st,{label:"New block",Icon:No,onClick:Nn}),Ye&&e.jsxs(e.Fragment,{children:[e.jsx(st,{label:"Ask AI",Icon:Lt,onClick:()=>bt({kind:"ask"})}),t.activeBlockPath&&e.jsx(st,{label:"Modify with AI",Icon:Lt,onClick:()=>bt({kind:"edit",initialInput:`Modify this block${xe?` (${xe})`:""}: `})}),e.jsx(st,{label:"Run",Icon:Ni,onClick:()=>void zt(),busy:G}),e.jsx(st,{label:we?"Saving":"Save draft",Icon:kt,variant:"secondary",busy:we,onClick:()=>void cn(),title:"Save changes as a review-required draft"}),e.jsx(st,{label:((oi=t.blockStudioMetadata)==null?void 0:oi.reviewStatus)==="certified"?"Re-certify":"Certify",Icon:Ho,variant:"primary",busy:we||!!se,onClick:()=>void Qn(),title:"Run validation, query, tests, chart, and lineage gates before certification"})]}),Ne&&e.jsx("span",{style:{fontSize:11,color:"var(--status-error)",fontFamily:o.font,padding:"4px 8px",background:"var(--status-error-bg)",borderRadius:6},children:Ne})]}),Ae&&Ie==="save"&&e.jsxs("div",{role:"alert",style:{flexShrink:0,display:"flex",alignItems:"flex-start",gap:10,padding:"10px 14px",borderBottom:"1px solid var(--status-error)",background:"var(--status-error-bg)",color:o.textPrimary,fontFamily:o.font},children:[e.jsx(ft,{size:16,color:"var(--status-error)",style:{marginTop:1,flexShrink:0}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:700},children:"This draft was not saved. Your work is still editable."}),e.jsx("div",{style:{marginTop:2,fontSize:11.5,lineHeight:1.45,color:o.textSecondary},children:Ae}),(((ri=t.blockStudioValidation)==null?void 0:ri.diagnostics.filter(i=>i.severity==="error").length)??0)>1&&e.jsx("div",{style:{marginTop:4,fontSize:10.5,color:o.textMuted},children:t.blockStudioValidation.diagnostics.filter(i=>i.severity==="error").slice(1,3).map(i=>i.message).join(" · ")})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,flexWrap:"wrap",justifyContent:"flex-end"},children:[e.jsxs("button",{type:"button",onClick:()=>void dn(),disabled:De,style:{...Te(o),display:"inline-flex",alignItems:"center",gap:6,opacity:De?.72:1},children:[De?e.jsx(Ze,{size:13,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):e.jsx(Lt,{size:13}),De?"Fixing & running…":"Fix with AI & run"]}),e.jsx("button",{type:"button",onClick:()=>ie("source"),style:Z(o),children:"Edit DQL"}),e.jsx("button",{type:"button",onClick:()=>bt({kind:"edit",initialInput:`Help me fix this block error without changing its intended grain, parameters, or trust state: ${Ae} `}),style:Z(o),children:"Open Block AI"})]})]}),u&&e.jsxs("div",{role:"status",style:{flexShrink:0,display:"flex",alignItems:"center",gap:8,padding:"8px 14px",borderBottom:"1px solid var(--status-success)",background:"var(--status-success-bg)",color:o.textSecondary,fontSize:11.5,fontFamily:o.font},children:[e.jsx(kt,{size:14,color:"var(--status-success)"})," ",u]}),ee&&e.jsxs("div",{role:"status",style:{flexShrink:0,display:"flex",alignItems:"center",gap:8,padding:"8px 14px",borderBottom:"1px solid var(--status-warning-border)",background:"var(--status-warning-bg)",color:o.textSecondary,fontSize:11.5,fontFamily:o.font},children:[e.jsx(ft,{size:14,color:"var(--status-warning)"})," ",ee]}),Ye&&ho&&e.jsx(Rr,{source:t.blockStudioDraft,databaseStats:Yt,semanticCount:_n,onChange:Fe,onOpenExplorer:()=>{Ht(!1),l("database")},onOpenAi:()=>bt({kind:"edit",initialInput:"Review and improve this block context. Keep only grounded business references, sources, constraints, and caveats: "}),t:o}),e.jsx("div",{style:{flex:1,overflow:"hidden"},children:Dn==="import"?e.jsx(Kr,{session:Qe,sessions:so,sessionsLoading:lo,onClose:()=>He(Ye?"manual":"start"),onSessionChange:Ut,onRefreshSessions:Vt,onSelectCandidate:So,onSavedCandidate:ko,defaultDomain:((si=t.blockStudioMetadata)==null?void 0:si.domain)??b,defaultOwner:((li=t.blockStudioMetadata)==null?void 0:li.owner)??"",themeMode:t.themeMode,t:o,inline:!0}):Ye?Bt==="detail"?e.jsx($r,{metadata:t.blockStudioMetadata,source:t.blockStudioDraft,parameters:((ai=t.blockStudioValidation)==null?void 0:ai.parameters)??[],preview:t.blockStudioPreview,lastRun:t.blockStudioLastRun??void 0,lineageDetail:wt,isSemanticBlock:ot,running:G,onOpenBuilder:()=>ie("visual"),onOpenSource:()=>ie("source"),onDelete:()=>{var i;return t.activeBlockPath&&un(t.activeBlockPath,((i=t.blockStudioMetadata)==null?void 0:i.name)||xe||t.activeBlockPath)},onRun:()=>void zt(),onOpenHistory:()=>{k("history"),yt(!1),Wn()},t:o}):Bt==="visual"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[e.jsx(_r,{mode:ot?"semantic":"custom",onModeChange:go,t:o}),e.jsx("div",{style:{flex:1,minHeight:0},children:ot?e.jsx(Ar,{source:t.blockStudioDraft,metadata:t.blockStudioMetadata,semanticLayer:t.semanticLayer,dbtStatus:t.blockStudioDbtStatus,domainOptions:t.authoredDomains,chartConfig:Un,onChange:Fe,onMetadataChange:i=>t.blockStudioMetadata&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...i}}),onOpenAi:()=>bt({kind:"edit",initialInput:"Help resolve the selected semantic metrics and dimensions for this block: "}),onSetupRuntime:()=>{n({type:"SET_SETTINGS_TAB",tab:"project"}),n({type:"SET_MAIN_VIEW",view:"settings"})},t:o},`sem-${t.activeBlockPath??a}`):e.jsx(Wr,{source:t.blockStudioDraft,metadata:t.blockStudioMetadata,domainOptions:t.authoredDomains,chartConfig:Un,onChange:Fe,onMetadataChange:i=>t.blockStudioMetadata&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...i}}),onConvertToDql:()=>ie("source"),t:o},`sql-${t.activeBlockPath??a}`)})]}):e.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(Tt||Rn)&&e.jsx(Fr,{semanticChoice:Tt,databaseWarning:Rn,onDismiss:()=>{on(null),rn(null)},onInsertAdvanced:()=>{if(!Tt)return;const i=Qo(Tt.kind==="metric"?"metric":"dimension",Tt.name);Fe(Uo(t.blockStudioDraft,i)),on(null)},onCreateSemantic:()=>n({type:"OPEN_NEW_BLOCK_MODAL",blockType:"semantic"}),t:o}),e.jsxs("div",{style:{height:34,flexShrink:0,display:"flex",alignItems:"center",gap:10,padding:"0 14px",borderBottom:"1px solid var(--border-subtle)",background:o.appBg},children:[e.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.activeBlockPath??Gi(t.blockStudioMetadata)}),t.blockStudioDirty&&e.jsx("span",{style:{width:6,height:6,borderRadius:999,background:"var(--status-warning)",flexShrink:0},title:"Unsaved changes"}),e.jsx("div",{style:{flex:1}}),t.blockStudioValidation?t.blockStudioValidation.diagnostics.filter(i=>i.severity==="error").length===0?e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:"var(--status-success)",fontWeight:600,whiteSpace:"nowrap",fontFamily:o.font},children:[e.jsx(kt,{size:12})," Valid"]}):e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:"var(--status-warning)",fontWeight:600,whiteSpace:"nowrap",fontFamily:o.font},children:[e.jsx(ft,{size:12})," ",t.blockStudioValidation.diagnostics.filter(i=>i.severity==="error").length," problem",t.blockStudioValidation.diagnostics.filter(i=>i.severity==="error").length===1?"":"s"]}):e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:o.textMuted,fontWeight:600,whiteSpace:"nowrap",fontFamily:o.font},children:[e.jsx(Ze,{size:12,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}})," Checking"]})]}),e.jsxs("div",{style:{flex:1,minHeight:0,display:"flex",overflow:"hidden"},children:[e.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",background:o.cellBg,borderRight:"1px solid var(--border-subtle)"},children:e.jsx(or,{value:t.blockStudioDraft,onChange:Fe,onRun:()=>void zt(),themeMode:t.themeMode,autoFocus:!0,wrap:!1,fillHeight:!0,schema:$,dqlMode:!0,errorMessage:(ci=(di=t.blockStudioValidation)==null?void 0:di.diagnostics.find(i=>i.severity==="error"))==null?void 0:ci.message})}),!he&&e.jsx(Tr,{source:t.blockStudioDraft,diagnostics:((ui=t.blockStudioValidation)==null?void 0:ui.diagnostics)??[],parameterCount:((fi=(pi=t.blockStudioValidation)==null?void 0:pi.parameters)==null?void 0:fi.length)??0,t:o})]})]}):e.jsx(zr,{dbtStatus:t.blockStudioDbtStatus,semanticStats:An,semanticObjectCount:_n,databaseStats:Yt,onCreateSql:()=>Hn("custom"),onCreateSemantic:()=>Hn("semantic"),onImport:()=>He("import"),onBuildDql:()=>bt({kind:"build",initialInput:"Draft a reusable DQL block that "}),t:o})})]}),e.jsx("div",{onMouseDown:ut?To:void 0,style:{gridColumn:Po,gridRow:Ro,display:ut?"block":"none",cursor:"row-resize",background:o.headerBorder}}),e.jsxs("div",{style:{gridColumn:Eo,gridRow:Lo,borderTop:ut?`1px solid ${o.headerBorder}`:"none",display:ut?"flex":"none",flexDirection:"column",overflow:"hidden",background:o.cellBg},children:[e.jsxs("div",{style:{display:"flex",gap:14,alignItems:"center",padding:"0 16px",borderBottom:`1px solid ${o.headerBorder}`,flexWrap:"wrap"},children:[e.jsx(Pt,{active:h==="results",onClick:()=>k("results"),label:"Results",t:o}),e.jsx(Pt,{active:h==="parameters",onClick:()=>k("parameters"),label:`Run inputs${(((mi=(hi=t.blockStudioValidation)==null?void 0:hi.parameters)==null?void 0:mi.length)??0)>0?` · ${t.blockStudioValidation.parameters.length}`:""}`,t:o}),e.jsx(Pt,{active:h==="lineage",onClick:()=>k("lineage"),label:"Lineage",t:o}),e.jsx(Pt,{active:h==="history",onClick:()=>{k("history"),Wn()},label:"History",t:o}),e.jsx(Pt,{active:h==="save",onClick:()=>k("save"),label:"Metadata",t:o}),e.jsx("div",{style:{flex:1}}),t.blockStudioPreview?e.jsxs("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.font,whiteSpace:"nowrap"},children:[t.blockStudioPreview.result.executionTime?`Ran in ${(t.blockStudioPreview.result.executionTime/1e3).toFixed(1)}s · `:"",t.blockStudioPreview.result.rowCount??t.blockStudioPreview.result.rows.length," rows"]}):null,e.jsx("button",{onClick:()=>yt(!0),style:{background:"transparent",border:"none",color:o.textMuted,cursor:"pointer",fontSize:11,fontFamily:o.font,padding:"4px 6px"},title:"Hide pane",children:"▾ Hide"})]}),e.jsxs("div",{style:{flex:1,overflow:"auto"},children:[h==="results"&&(G?e.jsx(ts,{elapsedMs:Se}):t.blockStudioPreview?e.jsxs("div",{style:{display:"grid",gap:12,padding:12},children:[(xi=(gi=t.blockStudioPreview.invocation)==null?void 0:gi.resolvedParameters)!=null&&xi.length?e.jsx(es,{values:t.blockStudioPreview.invocation.resolvedParameters,t:o}):null,Co==="table"?e.jsx(Fi,{result:t.blockStudioPreview.result,themeMode:t.themeMode}):e.jsx(ar,{result:t.blockStudioPreview.result,chartConfig:t.blockStudioPreview.chartConfig,themeMode:t.themeMode}),e.jsxs("details",{open:ve,onToggle:i=>te(i.currentTarget.open),style:{border:`1px solid ${o.headerBorder}`,borderRadius:8,background:o.pillBg},children:[e.jsx("summary",{style:{cursor:"pointer",padding:"9px 11px",fontSize:11,fontWeight:700,color:o.textSecondary,fontFamily:o.font},children:"Query details"}),e.jsx("pre",{style:{margin:0,padding:"0 11px 11px",maxHeight:220,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:10.5,lineHeight:1.45,color:o.textMuted,fontFamily:o.fontMono},children:t.blockStudioPreview.sql})]})]}):I?e.jsx(ns,{message:I,technicalDetails:q,repairing:De,onFix:()=>void dn(q??I),onEdit:()=>ie("source")}):e.jsx(jt,{message:"Run the block to preview results."})),h==="lineage"&&e.jsx(Xr,{blockName:xe,loading:We,detail:wt,graph:Yi,paths:Xi,onSelectNode:i=>{n({type:"SET_LINEAGE_FOCUS",nodeId:i}),n({type:"OPEN_LINEAGE_DRAWER",nodeId:i})},onOpenInspector:()=>{if(xe){const i=`block:${xe}`;n({type:"SET_LINEAGE_FOCUS",nodeId:i}),n({type:"OPEN_LINEAGE_DRAWER",nodeId:i})}},t:o}),h==="parameters"&&e.jsx(Jr,{parameters:((yi=t.blockStudioValidation)==null?void 0:yi.parameters)??[],values:z,onChange:(i,d)=>Y(S=>({...S,[i]:d})),onReset:i=>Y(d=>{const S={...d};return delete S[i],S}),onRun:()=>void zt(),running:G,t:o}),h==="history"&&e.jsx(as,{entries:v,t:o}),h==="save"&&e.jsxs("div",{style:{display:"grid",gap:12},children:[t.activeBlockPath&&t.blockStudioMetadata&&e.jsx("div",{style:{padding:"12px 12px 0"},children:e.jsx(rs,{currentStatus:t.blockStudioMetadata.reviewStatus??"draft",blockPath:t.activeBlockPath,onStatusChanged:i=>{t.blockStudioMetadata&&(n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,reviewStatus:i}}),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:ue(t.blockStudioDraft,"status",i)}))},t:o})}),Ln&&e.jsx(ss,{result:Ln,t:o,repairing:De,onEditSource:()=>ie("source"),onEditParameters:()=>k("parameters"),onReviewMetrics:()=>{Ht(!1),l("semantic"),ie("visual")},onRun:()=>void zt(),onFix:i=>void dn(i.technicalDetails??i.message,{requireCertificationReady:!0})}),e.jsx(Zr,{metadata:t.blockStudioMetadata,draftMetadata:ct,onChange:i=>{if(!t.blockStudioMetadata)return;n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...i}});let d=t.blockStudioDraft;typeof i.name=="string"&&(d=$t(d,i.name)),typeof i.domain=="string"&&(d=ue(d,"domain",i.domain)),typeof i.owner=="string"&&(d=ue(d,"owner",i.owner)),typeof i.description=="string"&&(d=ue(d,"description",i.description)),i.tags&&(d=At(d,i.tags)),Fe(d)},t:o})]})]})]}),Ye&&Tn&&e.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:e.jsx("button",{onClick:()=>yt(!1),style:{background:o.btnBg,border:`1px solid ${o.btnBorder}`,borderRadius:6,color:o.textSecondary,cursor:"pointer",fontSize:12,fontFamily:o.font,padding:"8px 12px"},children:"Open Results"})}),!he&&nt&&e.jsx("div",{onMouseDown:Do,style:{gridColumn:"4",gridRow:"1 / 4",cursor:"col-resize",background:o.headerBorder}}),nt&&e.jsx(gr,{t:o,title:"Block AI",subtitle:xe?`Current block: ${xe}`:"Unsaved governed block draft",expanded:In,onToggleExpanded:()=>Mn(i=>!i),onClose:()=>{nn(!1),Mn(!1)},onNewChat:()=>{f.resetThreadId(),ro(i=>i+1)},running:no,compact:he,ariaLabel:"Block Studio AI",style:{gridColumn:he?"1":"5",gridRow:he?Kn:"1 / 4"},children:e.jsx(fr,{themeMode:t.themeMode,title:"Block AI",scopeHint:xe?`Current block: ${xe}`:"Block Studio project context",workspaceContext:{surface:"block-studio",task:En==="edit"?"edit_block":"author_block",draftSessionId:a,blockStudioDraft:t.blockStudioDraft,activeBlockPath:t.activeBlockPath,domain:(bi=t.blockStudioMetadata)==null?void 0:bi.domain,importId:Qe==null?void 0:Qe.id,importCandidateId:(vi=Qe==null?void 0:Qe.candidates[0])==null?void 0:vi.id,...En==="edit"?{mode:"edit",blockPath:t.activeBlockPath}:{}},initialMode:"block",initialInput:co,autoRun:po,threadId:f.threadId,onThreadIdChange:f.onThreadIdChange,onRunningChange:io,onInsertSql:(i,d)=>jo(i,{question:d??xe??"analysis",title:d}),onInsertDql:i=>{wo(i)},answerFirstCards:!0,insertDqlActionLabel:"Add to Block Studio",emptyHint:"Describe the governed block you need. DQL checks certified blocks and semantic metrics before creating a review-required draft.",examplePrompts:[{label:"Build from business question",prompt:"Build a reusable governed DQL block for this business question: "},{label:"Find reusable blocks",prompt:"Which certified DQL blocks already answer this analysis, and what should be reused instead of duplicated?"},{label:"Review this block",prompt:"Review this block for grain, compatible metrics and dimensions, parameters, tests, and certification gaps."}]},`${m}:${oo}`)}),!nt&&!he&&e.jsx("button",{type:"button",onClick:()=>nn(!0),title:"Open Block AI",style:{position:"absolute",right:12,top:58,width:34,height:34,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:`1px solid ${o.btnBorder}`,background:o.btnBg,color:o.accent,cursor:"pointer",boxShadow:"0 6px 18px rgba(0, 0, 0, 0.12)"},children:e.jsx(br,{size:16,strokeWidth:2})}),gt&&t.blockStudioMetadata&&e.jsx(Dr,{metadata:t.blockStudioMetadata,onCancel:()=>{D.current=null,Ve(!1)},onConfirm:i=>{let d=$t(t.blockStudioDraft,i.name);d=ue(d,"owner",i.owner),n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...i}}),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:d}),Ve(!1)},t:o}),xt&&e.jsx(Ir,{saving:we,onCancel:()=>g(!1),onDiscard:()=>{g(!1),an()},onSave:async()=>{C.current=!0,g(!1),await cn()&&(C.current=!1,an())},t:o}),Je&&_e&&e.jsx(Mr,{blockName:_e.name,blockPath:_e.path,deleting:at,error:ht,onCancel:()=>{at||(et(!1),tt(null),Re(null))},onConfirm:()=>void vo(),t:o})]})}function Br({active:t,onClick:n,label:s,busy:r,Icon:o,variant:a="secondary",title:p}){const m=qt[Ot(l=>l.themeMode)],f=a==="primary",E=a==="danger";return e.jsxs("button",{onClick:n,disabled:r,"aria-busy":r||void 0,title:p??s,style:{background:f?m.accent:E?`${m.error}0d`:t?`${m.accent}18`:m.btnBg,border:`1px solid ${f?m.accent:E?`${m.error}55`:t?m.accent:m.btnBorder}`,borderRadius:6,height:28,color:f?"#ffffff":E?m.error:t?m.accent:m.textSecondary,cursor:r?"wait":"pointer",display:"inline-flex",alignItems:"center",gap:6,fontSize:11,fontWeight:f?800:600,fontFamily:m.font,padding:"0 10px",whiteSpace:"nowrap",opacity:r?.7:1},children:[r?e.jsx(Ze,{size:13,strokeWidth:2,"aria-hidden":"true"}):o?e.jsx(o,{size:13,strokeWidth:2,"aria-hidden":"true"}):null,r?`${s}...`:s]})}function st(t){return e.jsx(Br,{active:!1,...t})}function Tr({source:t,diagnostics:n,parameterCount:s,t:r}){const o=t.split(`
|
|
10
|
+
`),a={block:"var(--text-tertiary)",parameters:"var(--accent)",query:"var(--status-success)",tests:"var(--status-warning)",visualization:"var(--cat-audit)"},p=[];o.forEach((l,h)=>{const k=l.match(/^\s*(block|parameters|query|tests|visualization)\b/);if(k&&!p.some(b=>b.label.toLowerCase().startsWith(k[1]))){const b=k[1],P=b==="block"?"Metadata":b==="parameters"?`Parameters${s?` · ${s}`:""}`:b.charAt(0).toUpperCase()+b.slice(1);p.push({label:P,line:h+1,color:a[b]??"var(--text-tertiary)"})}});const m=(t.match(/^\s*assert\b/gm)??[]).length,f=new Set((t.match(/\b(?:from|join)\s+([a-z_][\w.]*)/gi)??[]).map(l=>l.replace(/^(from|join)\s+/i,""))).size,E=n.filter(l=>l.severity==="error");return e.jsxs("div",{style:{width:208,flexShrink:0,background:r.appBg,display:"flex",flexDirection:"column",overflow:"auto"},children:[e.jsx("div",{style:{padding:"12px 14px 6px",fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font},children:"Outline"}),e.jsx("div",{style:{padding:"0 8px",display:"flex",flexDirection:"column",gap:1},children:p.length===0?e.jsx("span",{style:{fontSize:11,color:r.textMuted,padding:"2px 8px",fontFamily:r.font},children:"No sections yet."}):p.map(l=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:6},children:[e.jsx("span",{style:{width:8,height:8,borderRadius:2,background:l.color,flexShrink:0}}),e.jsx("span",{style:{flex:1,fontSize:11.5,fontWeight:550,color:r.textSecondary,fontFamily:r.font},children:l.label}),e.jsxs("span",{style:{fontSize:10,color:r.textMuted,fontFamily:r.fontMono},children:[":",l.line]})]},l.label))}),e.jsx("div",{style:{padding:"14px 14px 6px",fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font},children:"Problems"}),E.length===0?e.jsxs("div",{style:{padding:"0 14px",fontSize:11.5,color:"var(--status-success)",display:"flex",alignItems:"center",gap:6,fontFamily:r.font},children:[e.jsx(kt,{size:12})," No problems"]}):e.jsx("div",{style:{padding:"0 14px",display:"flex",flexDirection:"column",gap:5},children:E.slice(0,4).map((l,h)=>e.jsx("span",{style:{fontSize:11,color:"var(--status-error)",lineHeight:1.4,fontFamily:r.font},children:l.message},h))}),e.jsx("div",{style:{padding:"14px 14px 6px",fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:r.textMuted,fontFamily:r.font},children:"Context"}),e.jsxs("div",{style:{padding:"0 14px 16px",display:"flex",flexDirection:"column",gap:5,fontSize:11,color:r.textSecondary,fontFamily:r.font},children:[e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:999,background:"var(--accent)"}}),s," parameter",s===1?"":"s"," bound"]}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:999,background:"var(--status-success)"}}),f," model",f===1?"":"s"," referenced"]}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:999,background:"var(--status-warning)"}}),m," test",m===1?"":"s"," declared"]})]})]})}function Pt({active:t,onClick:n,label:s,t:r}){return e.jsx("button",{type:"button",onClick:n,style:{padding:"9px 1px",fontSize:11.5,fontWeight:650,cursor:"pointer",border:"none",background:"none",fontFamily:r.font,whiteSpace:"nowrap",color:t?r.textPrimary:r.textMuted,boxShadow:t?`inset 0 -2px 0 0 ${r.accent}`:"none"},children:s})}function Ci(t,n){return Go(t,{variant:n?"accent":"ghost",size:"xs",active:n})}function Wt(t,n){return{display:"inline-flex",alignItems:"center",gap:5,background:n?"var(--accent-dim)":t.btnBg,border:`1px solid ${n?`${t.accent}55`:t.btnBorder}`,borderRadius:999,color:n?t.accent:t.textSecondary,cursor:"pointer",fontSize:11.5,fontFamily:t.fontMono,lineHeight:1.2,padding:"4px 9px"}}function Dr({metadata:t,onCancel:n,onConfirm:s,t:r}){const[o,a]=c.useState(t.name),[p,m]=c.useState(t.owner),f=!!(o.trim()&&p.trim());return e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Save block",style:{position:"absolute",inset:0,zIndex:70,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,.32)",padding:18},children:e.jsxs("div",{style:{width:420,maxWidth:"100%",display:"grid",gap:14,padding:18,borderRadius:10,border:`1px solid ${r.headerBorder}`,background:r.cellBg,boxShadow:"0 24px 70px rgba(0,0,0,.35)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:15,fontWeight:850,color:r.textPrimary},children:"Save governed block"}),e.jsx("div",{style:{marginTop:4,fontSize:11,lineHeight:1.45,color:r.textMuted},children:"Name and owner are required. DQL will run the local governance checks and certify the block when they pass; otherwise it remains a draft with blockers."})]}),e.jsx(A,{label:"Block name",t:r,children:e.jsx("input",{autoFocus:!0,value:o,onChange:E=>a(E.target.value),style:ze(r)})}),e.jsx(A,{label:"Owner",t:r,children:e.jsx("input",{value:p,onChange:E=>m(E.target.value),placeholder:"analytics@company.com or team name",style:ze(r)})}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:n,style:Z(r),children:"Cancel"}),e.jsx("button",{type:"button",disabled:!f,onClick:()=>f&&s({name:o.trim(),owner:p.trim()}),style:{...Te(r),opacity:f?1:.55},children:"Save block"})]})]})})}function Ir({saving:t,onSave:n,onDiscard:s,onCancel:r,t:o}){return e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Unsaved block",style:{position:"fixed",inset:0,zIndex:90,display:"grid",placeItems:"center",padding:20,background:"rgba(0, 0, 0, 0.42)"},children:e.jsxs("div",{style:{width:"min(430px, 100%)",border:`1px solid ${o.cellBorder}`,borderRadius:12,background:o.cellBg,padding:18,display:"grid",gap:14,boxShadow:"0 20px 60px rgba(0, 0, 0, 0.24)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:15,fontWeight:800,color:o.textPrimary,fontFamily:o.font},children:"Save this block before leaving?"}),e.jsx("div",{style:{marginTop:5,fontSize:12,lineHeight:1.5,color:o.textMuted,fontFamily:o.font},children:"Your current Block Studio workspace has unsaved changes."})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:r,disabled:t,style:Z(o),children:"Cancel"}),e.jsx("button",{type:"button",onClick:s,disabled:t,style:{...Z(o),color:o.error},children:"Discard"}),e.jsx("button",{type:"button",onClick:()=>void n(),disabled:t,style:Te(o),children:t?"Saving…":"Save block"})]})]})})}function Mr({blockName:t,blockPath:n,deleting:s,error:r,onCancel:o,onConfirm:a,t:p}){return e.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Delete block",style:{position:"fixed",inset:0,zIndex:95,display:"grid",placeItems:"center",padding:20,background:"rgba(0, 0, 0, 0.42)"},children:e.jsxs("div",{style:{width:"min(460px, 100%)",border:`1px solid ${p.error}55`,borderRadius:12,background:p.cellBg,padding:18,display:"grid",gap:14,boxShadow:"0 20px 60px rgba(0, 0, 0, 0.26)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:9},children:[e.jsx("span",{style:{width:30,height:30,display:"grid",placeItems:"center",borderRadius:8,background:`${p.error}12`},children:e.jsx(tn,{size:16,color:p.error})}),e.jsxs("div",{children:[e.jsxs("div",{style:{fontSize:15,fontWeight:800,color:p.textPrimary,fontFamily:p.font},children:["Delete “",t,"”?"]}),e.jsx("div",{style:{marginTop:3,fontSize:11,color:p.textMuted,fontFamily:p.fontMono},children:n})]})]}),e.jsxs("div",{style:{fontSize:12,lineHeight:1.5,color:p.textSecondary,fontFamily:p.font},children:["This removes the saved ",e.jsx("code",{children:".dql"})," block and its generated semantic companion. Unsaved editor changes are discarded. Git can recover committed versions."]}),r&&e.jsx("div",{role:"alert",style:{padding:"8px 10px",borderRadius:7,border:`1px solid ${p.error}45`,background:`${p.error}0d`,color:p.error,fontSize:11,lineHeight:1.4},children:r}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:o,disabled:s,style:Z(p),children:"Cancel"}),e.jsx("button",{type:"button",onClick:a,disabled:s,style:{...Te(p),background:p.error,borderColor:p.error,opacity:s?.65:1},children:s?e.jsxs(e.Fragment,{children:[e.jsx(Ze,{size:13,className:"dql-spin"})," Deleting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(tn,{size:13})," Delete block"]})})]})]})})}function zr({dbtStatus:t,semanticStats:n,semanticObjectCount:s,databaseStats:r,onCreateSql:o,onCreateSemantic:a,onImport:p,onBuildDql:m,t:f}){var P;const E=[{title:"Blank SQL block",detail:"Start with an empty custom query.",action:o,label:"Create",Icon:dr},{title:"Semantic block",detail:"Build directly from governed metrics.",action:a,label:"Build",Icon:Jt}],l=!!(t!=null&&t.artifacts.manifest.exists),h=(t==null?void 0:t.counts.metrics)??n.metrics,k=t?`${t.counts.models} dbt models · ${h} MetricFlow metrics`:"Waiting for dbt artifacts",b=(t==null?void 0:t.projectName)||((P=t==null?void 0:t.projectPath)==null?void 0:P.split("/").filter(Boolean).pop())||"dbt project";return e.jsxs("div",{style:{height:"100%",overflow:"auto",padding:22,display:"grid",gap:14,alignContent:"start",background:f.appBg},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16,flexWrap:"wrap"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:20,fontWeight:800,color:f.textPrimary,fontFamily:f.font},children:"Create DQL blocks"}),e.jsx("div",{style:{fontSize:12,color:f.textMuted,lineHeight:1.45,marginTop:5,maxWidth:560,fontFamily:f.font},children:"Start from SQL you already have, or describe the business asset you want DQL to build from project context."})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"7px 10px",border:`1px solid ${l?"#2ea04340":f.headerBorder}`,borderRadius:8,background:l?"#2ea0430d":f.cellBg},children:[e.jsx(kt,{size:15,strokeWidth:2,color:l?"#2ea043":f.textMuted,"aria-hidden":"true"}),e.jsx("span",{style:{fontSize:11,color:l?"#2ea043":f.textMuted,fontWeight:700,fontFamily:f.font},children:l?"dbt ready":"dbt pending"})]})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(260px, 1fr))",gap:10},children:[e.jsx(mn,{title:"Ask AI",detail:"Describe the business asset you need. DQL uses this domain's blocks, models, and semantic metrics to draft it.",label:"Describe block",Icon:yr,onClick:m,t:f}),e.jsx(mn,{title:"Import SQL",detail:"Paste scripts, upload files, or point at a folder. DQL analyzes candidates without writing block files until you save.",label:"Start import",Icon:Hi,onClick:p,t:f}),e.jsx(mn,{title:"Build manually",detail:"Use the visual semantic builder for multiple metrics, compatible dimensions, time grain, filters, and chart intent.",label:"Open builder",Icon:Jt,onClick:a,t:f})]}),e.jsxs("details",{style:Rt(f),children:[e.jsx("summary",{style:Et(f),children:"Manual options"}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))",gap:10},children:E.map(L=>e.jsx(Pr,{title:L.title,detail:L.detail,label:L.label,Icon:L.Icon,onClick:L.action,t:f},L.title))})]}),e.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))",gap:8},children:[e.jsx(gn,{Icon:vn,label:`${b} dbt`,value:k,tone:l?"success":"neutral",t:f}),e.jsx(gn,{Icon:vn,label:"Database",value:`${r.tables} tables`,tone:r.tables>0?"success":"neutral",t:f}),e.jsx(gn,{Icon:Jt,label:"DQL semantic layer",value:`${s} objects`,tone:s>0?"success":"neutral",t:f})]})]})}function mn({title:t,detail:n,label:s,Icon:r,onClick:o,t:a}){return e.jsxs("button",{onClick:o,style:{border:`1px solid ${a.accent}`,borderRadius:8,background:a.cellBg,color:a.textPrimary,cursor:"pointer",display:"grid",gridTemplateColumns:"42px minmax(0, 1fr) auto",gap:12,alignItems:"center",padding:16,minHeight:104,textAlign:"left",fontFamily:a.font,boxShadow:`inset 0 0 0 1px ${a.accent}22`},children:[e.jsx("span",{style:{width:42,height:42,borderRadius:8,display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${a.accent}18`,color:a.accent},children:e.jsx(r,{size:20,strokeWidth:2,"aria-hidden":"true"})}),e.jsxs("span",{style:{display:"grid",gap:5,minWidth:0},children:[e.jsx("span",{style:{fontSize:15,fontWeight:850,color:a.textPrimary},children:t}),e.jsx("span",{style:{fontSize:12,color:a.textMuted,lineHeight:1.4},children:n})]}),e.jsx("span",{style:{color:"#ffffff",background:a.accent,borderRadius:6,padding:"7px 10px",fontSize:11,fontWeight:800,whiteSpace:"nowrap"},children:s})]})}function Pr({title:t,detail:n,label:s,Icon:r,onClick:o,t:a}){return e.jsxs("button",{onClick:o,style:{textAlign:"left",background:a.cellBg,border:`1px solid ${a.headerBorder}`,borderRadius:8,padding:12,cursor:"pointer",color:a.textPrimary,display:"grid",gridTemplateColumns:"30px minmax(0, 1fr)",gap:10,minHeight:94,fontFamily:a.font,alignItems:"start"},children:[e.jsx("span",{style:{width:30,height:30,borderRadius:7,display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${a.accent}14`,color:a.accent},children:e.jsx(r,{size:16,strokeWidth:2,"aria-hidden":"true"})}),e.jsxs("span",{style:{display:"grid",gap:5,minWidth:0},children:[e.jsx("span",{style:{fontSize:13,fontWeight:800,color:a.textPrimary},children:t}),e.jsx("span",{style:{fontSize:11,color:a.textMuted,lineHeight:1.35},children:n}),e.jsx("span",{style:{color:a.accent,fontSize:11,fontWeight:800},children:s})]})]})}function gn({Icon:t,label:n,value:s,tone:r,t:o}){const a=r==="success"?"#2ea043":o.textMuted;return e.jsxs("div",{style:{border:`1px solid ${o.headerBorder}`,borderRadius:8,background:o.cellBg,padding:"9px 10px",display:"flex",alignItems:"center",gap:8,minWidth:0},children:[e.jsx("span",{style:{color:a,display:"inline-flex",flexShrink:0},children:e.jsx(t,{size:15,strokeWidth:2,"aria-hidden":"true"})}),e.jsxs("span",{style:{display:"grid",gap:2,minWidth:0},children:[e.jsx("span",{style:{fontSize:10,color:o.textMuted,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),e.jsx("span",{style:{fontSize:12,color:o.textPrimary,fontWeight:700,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s})]})]})}function Rr({source:t,databaseStats:n,semanticCount:s,onChange:r,onOpenExplorer:o,onOpenAi:a,t:p}){const m=l=>{var h;return((h=t.match(new RegExp(`\\b${l}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:h[1])??""},f=l=>{var h;return(((h=t.match(new RegExp(`\\b${l}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i")))==null?void 0:h[1].match(/"([^"]*)"/g))??[]).map(k=>k.slice(1,-1))},E=[{key:"primaryTerms",label:"Business terms",hint:"net revenue, active customer"},{key:"sourceSystems",label:"Source systems",hint:"billing, product events"},{key:"synonyms",label:"Question aliases",hint:"sales, bookings"}];return e.jsxs("div",{style:{padding:"10px 14px",borderBottom:`1px solid ${p.headerBorder}`,background:p.appBg,display:"grid",gap:10},children:[e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"},children:[e.jsx("div",{style:{fontSize:12,fontWeight:750,color:p.textPrimary},children:"Block context"}),e.jsx("span",{style:{fontSize:11,color:p.textMuted},children:"Only grounded context is kept with the block and used for retrieval."}),e.jsx("div",{style:{flex:1}}),e.jsxs("button",{type:"button",onClick:o,style:Z(p),children:[n.tables," database tables"]}),e.jsx("button",{type:"button",onClick:a,style:Z(p),children:"Review with AI"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(230px, 1fr))",gap:10},children:[e.jsx(A,{label:"Business outcome",t:p,children:e.jsx(_t,{value:m("businessOutcome"),onChange:l=>r(ue(t,"businessOutcome",l)),placeholder:"Decision or outcome this block supports",style:ze(p)})}),e.jsx(A,{label:"Agent guidance",t:p,children:e.jsx(_t,{value:m("llmContext"),onChange:l=>r(ue(t,"llmContext",l)),placeholder:"When to use this block",style:ze(p)})}),E.map(l=>e.jsx(Er,{label:l.label,hint:l.hint,values:f(l.key),onChange:h=>r(Vo(t,l.key,h)),t:p},l.key)),e.jsx(A,{label:"Rules and caveats",t:p,children:e.jsx(_t,{value:m("caveats"),onChange:l=>r(ue(t,"caveats",l)),placeholder:"Known limitation or interpretation rule",style:ze(p)})})]}),e.jsxs("div",{style:{fontSize:10,color:p.textMuted},children:["Available authoring context: ",s," semantic objects, ",n.schemas," schemas, ",n.columns," columns. SQL completion uses the same loaded catalog."]})]})}function Er({label:t,hint:n,values:s,onChange:r,t:o}){const[a,p]=c.useState(""),m=()=>{const f=a.split(",").map(E=>E.trim()).filter(Boolean);f.length>0&&r([...s,...f]),p("")};return e.jsx(A,{label:t,t:o,children:e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:5,padding:6,minHeight:36,border:`1px solid ${o.cellBorder}`,borderRadius:6,background:o.cellBg},children:[s.map(f=>e.jsxs("button",{type:"button",onClick:()=>r(s.filter(E=>E!==f)),title:"Remove",style:{...Wt(o,!0),border:"none",cursor:"pointer"},children:[f," ×"]},f)),e.jsx("input",{value:a,onChange:f=>p(f.target.value),onKeyDown:f=>{(f.key==="Enter"||f.key===",")&&(f.preventDefault(),m())},onBlur:m,placeholder:s.length?"Add another…":n,style:{minWidth:120,flex:1,border:"none",outline:"none",background:"transparent",color:o.textPrimary,fontSize:11,fontFamily:o.font}})]})})}function Qi({source:t,kind:n,onChange:s,t:r}){const o=c.useMemo(()=>tr(t),[t]),[a,p]=c.useState(""),[m,f]=c.useState(""),[E,l]=c.useState(!0),[h,k]=c.useState("dynamic"),[b,P]=c.useState("auto"),L=hn(m,a),K=b==="auto"?L:b,_=ze(r),w=()=>{a.trim()&&(s(ki(t,{name:a,type:K,required:E&&!m.trim(),defaultText:m,policy:h})),p(""),f(""),l(!0),k("dynamic"),P("auto"))};return e.jsx(be,{title:"Runtime parameters",t:r,children:e.jsxs("div",{style:{display:"grid",gap:10},children:[e.jsxs("div",{style:{fontSize:11,color:r.textMuted,lineHeight:1.45},children:["Add a values-only input once, then reuse this block for a different period, region, customer set, or limit.",n==="custom"?e.jsxs(e.Fragment,{children:[" Use ",e.jsx("code",{children:"${parameter_name}"})," in SQL where the value belongs; DQL always binds it safely."]}):" Choose a semantic field above as a filter to create its governed parameter binding."]}),o.length>0&&e.jsx("div",{style:{display:"grid",gap:7},children:o.map(x=>{var re;const X=nr(x),H=$=>s(ki(t,{name:x.name,type:$.type??x.type,required:$.required??x.required,defaultText:$.defaultText??X,policy:$.policy??x.policy}));return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(120px, 1fr) 122px minmax(150px, 1fr) 118px auto",gap:7,alignItems:"center",padding:8,border:`1px solid ${r.cellBorder}`,borderRadius:7,background:r.cellBg},children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:11,fontWeight:800,color:r.textPrimary},children:x.name}),e.jsxs("div",{style:{fontSize:10,color:r.textMuted},children:[((re=x.binding)==null?void 0:re.kind)??"declared value"," · ",x.required?"required":"has default"]})]}),e.jsx("select",{"aria-label":`${x.name} type`,value:x.type,onChange:$=>H({type:$.target.value}),style:_,children:Bi.map($=>e.jsx("option",{value:$,children:$},$))}),x.type==="boolean"?e.jsxs("select",{"aria-label":`${x.name} default`,value:X,onChange:$=>H({defaultText:$.target.value,required:!1}),style:_,children:[e.jsx("option",{value:"",children:"Required / no default"}),e.jsx("option",{value:"true",children:"True"}),e.jsx("option",{value:"false",children:"False"})]}):e.jsx("input",{"aria-label":`${x.name} default`,value:X,onChange:$=>{const G=$.target.value,J=x.type===hn(X,x.name);H({defaultText:G,required:G.trim()?!1:x.required,...J?{type:hn(G,x.name)}:{}})},placeholder:x.type.endsWith("[]")?"West, East":x.required?"Required value":"Default value",style:_}),e.jsx("select",{"aria-label":`${x.name} policy`,value:x.policy,onChange:$=>H({policy:$.target.value}),style:_,children:Lr.map($=>e.jsx("option",{value:$,children:$},$))}),e.jsx("button",{type:"button",onClick:()=>s(ir(t,x.name)),title:`Remove ${x.name}`,style:{border:"none",background:"transparent",color:r.error,cursor:"pointer",fontSize:16,padding:"3px 5px"},children:"×"})]},x.name)})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(140px, 1fr) minmax(150px, 1.3fr) 150px 130px auto",gap:7,alignItems:"center",padding:9,border:`1px dashed ${r.btnBorder}`,borderRadius:7,background:r.appBg},children:[e.jsx("input",{"aria-label":"New parameter name",value:a,onChange:x=>p(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),w())},placeholder:"region_set",style:_}),e.jsx("input",{"aria-label":"New parameter default",value:m,onChange:x=>{f(x.target.value),x.target.value.trim()&&l(!1)},onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),w())},placeholder:"Central, East or 2026-01-01",style:_}),e.jsxs("select",{"aria-label":"New parameter type",value:b,onChange:x=>P(x.target.value),style:_,children:[e.jsxs("option",{value:"auto",children:["Auto · ",L]}),Bi.map(x=>e.jsx("option",{value:x,children:x},x))]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:5,color:r.textSecondary,fontSize:11,whiteSpace:"nowrap"},children:[e.jsx("input",{type:"checkbox",checked:E&&!m.trim(),onChange:x=>l(x.target.checked)})," Required"]}),e.jsx("button",{type:"button",onClick:w,disabled:!a.trim(),style:{...Te(r),opacity:a.trim()?1:.5},children:"Add"})]}),e.jsxs("div",{style:{fontSize:10,color:r.textMuted},children:["Type is inferred from a value you enter: ",e.jsx("code",{children:"10"})," → number, ",e.jsx("code",{children:"2026-01-01"})," → date, ",e.jsx("code",{children:"West, East"})," → string[]. You can override it at any time."]})]})})}const Bi=["string","number","boolean","date","string[]","number[]","date[]"],Lr=["dynamic","static","business","derived","optional","ambiguous_review_required"];function $r({metadata:t,source:n,parameters:s,preview:r,lastRun:o,lineageDetail:a,isSemanticBlock:p,running:m,onOpenBuilder:f,onOpenSource:E,onDelete:l,onRun:h,onOpenHistory:k,t:b}){var te,Q,pe,Se,Pe;const P=((t==null?void 0:t.reviewStatus)??"").toLowerCase()==="certified",L=(t==null?void 0:t.name)||"block",K=p?Li(n):null,_=((Q=(te=n.match(/query\s*=\s*"""([\s\S]*?)"""/i))==null?void 0:te[1])==null?void 0:Q.trim())??"",w=K?Array.from(new Set([...K.dimensions,...K.timeDimension?[K.timeDimension]:[],...K.metrics])):Vi(_),x=(n.match(/^\s*assert\b.*$/gm)??[]).map(z=>z.trim()),X=((pe=a==null?void 0:a.incoming)==null?void 0:pe.length)??0,H=((Se=a==null?void 0:a.outgoing)==null?void 0:Se.length)??0,[re,$]=c.useState(!1),G=((a==null?void 0:a.incoming)??[]).map(z=>{var Y;return(Y=z.node)==null?void 0:Y.name}).filter(Boolean).slice(0,3),J=((a==null?void 0:a.outgoing)??[]).map(z=>{var Y;return(Y=z.node)==null?void 0:Y.name}).filter(Boolean).slice(0,3),I={fontSize:11,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:b.textMuted,marginBottom:8,fontFamily:b.font},N=(z,Y=!1)=>e.jsx("span",{style:{padding:"3px 9px",borderRadius:999,border:`1px solid ${Y?`${b.accent}59`:b.headerBorder}`,background:Y?"var(--accent-dim)":"var(--bg-1)",color:Y?b.accent:b.textSecondary,fontFamily:b.fontMono,fontWeight:Y?600:400,fontSize:11.5},children:z},z),q=e.jsx("span",{style:{color:b.textMuted,fontSize:11},children:"→"}),V=(r==null?void 0:r.result.executionTime)??(o==null?void 0:o.executionTime),ve=[["Last run",r||o?typeof V=="number"?`${(V/1e3).toFixed(1)}s`:"Completed":"Not run yet"],["Rows",r?String(r.result.rowCount??r.result.rows.length):o?String(o.rowCount):"—"],["Used in",H>0?`${H} downstream`:"—"],["Tests",x.length>0?`${x.length} declared`:"None yet"]];return e.jsx("div",{style:{height:"100%",overflow:"auto",background:b.appBg},children:e.jsxs("div",{style:{width:"min(860px, 100% - 48px)",margin:"0 auto",padding:"26px 0 40px",display:"flex",flexDirection:"column",gap:20,animation:"dql-agent-fadein 0.25s ease-out",fontFamily:b.font},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:14},children:[e.jsx("span",{style:{width:42,height:42,borderRadius:10,background:P?"var(--status-success-bg)":"var(--accent-dim)",color:P?"var(--status-success)":b.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border-subtle)"},children:e.jsx(Jt,{size:20,strokeWidth:1.75})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:9,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:17,fontWeight:700,color:b.textPrimary,fontFamily:b.fontMono,letterSpacing:"-0.01em"},children:L}),t!=null&&t.reviewStatus?e.jsx(qi,{status:t.reviewStatus,t:b}):null]}),e.jsx("div",{style:{fontSize:12,color:b.textMuted,marginTop:4},children:[t==null?void 0:t.domain,t!=null&&t.folderPath?`folder: ${t.folderPath}`:null,t==null?void 0:t.owner,...(Pe=t==null?void 0:t.tags)!=null&&Pe.length?[t.tags.join(", ")]:[]].filter(Boolean).join(" · ")||"Unsaved draft"})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexShrink:0},children:[e.jsxs("button",{type:"button",onClick:f,style:{display:"inline-flex",alignItems:"center",gap:7,height:32,padding:"0 14px",borderRadius:8,border:"none",background:b.accent,color:"#fff",fontSize:12.5,fontWeight:650,cursor:"pointer",fontFamily:b.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)"},children:[e.jsx(cr,{size:13,strokeWidth:1.75})," Open in builder"]}),e.jsxs("button",{type:"button",onClick:h,disabled:m,style:{display:"inline-flex",alignItems:"center",gap:6,height:32,padding:"0 13px",borderRadius:8,border:`1px solid ${b.headerBorder}`,background:b.cellBg,color:b.textSecondary,fontSize:12.5,fontWeight:600,cursor:"pointer",fontFamily:b.font,opacity:m?.7:1},children:[m?e.jsx(Ze,{size:12,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):e.jsx(Ni,{size:11,fill:"currentColor"})," Run"]}),e.jsx("button",{type:"button","aria-label":`Delete ${L}`,title:"Delete block",onClick:l,style:{width:32,height:32,borderRadius:8,border:`1px solid ${b.error}55`,background:`${b.error}0d`,color:b.error,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:e.jsx(tn,{size:14})}),e.jsx("button",{type:"button",title:"History and metadata",onClick:k,style:{width:32,height:32,borderRadius:8,border:`1px solid ${b.headerBorder}`,background:b.cellBg,color:b.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:e.jsx(ur,{size:15})})]})]}),t!=null&&t.description?e.jsx("div",{style:{fontSize:13.5,lineHeight:1.6,color:b.textSecondary,maxWidth:640},children:t.description}):null,e.jsx("div",{style:{display:"flex",border:"1px solid var(--border-subtle)",borderRadius:10,background:b.cellBg,overflow:"hidden"},children:ve.map(([z,Y],we)=>e.jsxs("div",{style:{flex:1,padding:"12px 16px",borderRight:we<ve.length-1?"1px solid var(--border-subtle)":"none"},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:b.textMuted},children:z}),e.jsx("div",{style:{fontSize:14,fontWeight:650,color:b.textPrimary,marginTop:3},children:Y})]},z))}),e.jsxs("div",{children:[e.jsx("div",{style:I,children:"Outputs"}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:w.length>0?w.map(z=>e.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11.5,padding:"4px 10px",borderRadius:999,background:"var(--accent-dim)",color:b.accent,border:`1px solid ${b.accent}33`,fontFamily:b.fontMono},children:z},z)):e.jsx("span",{style:{fontSize:11.5,color:b.textMuted},children:"Open the builder to define outputs."})})]}),e.jsxs("div",{children:[e.jsx("div",{style:I,children:"Parameters"}),e.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:9,overflow:"hidden",background:b.cellBg},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1.2fr 0.8fr 1fr 0.9fr",gap:8,padding:"7px 12px",background:"var(--bg-1)",borderBottom:"1px solid var(--border-subtle)",fontSize:10.5,fontWeight:700,color:b.textMuted,textTransform:"uppercase",letterSpacing:"0.04em"},children:[e.jsx("span",{children:"Name"}),e.jsx("span",{children:"Type"}),e.jsx("span",{children:"Default"}),e.jsx("span",{children:"Policy"})]}),s.length===0?e.jsx("div",{style:{padding:"9px 12px",fontSize:12,color:b.textMuted},children:"No parameters — this block always runs the same way."}):s.map((z,Y)=>e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1.2fr 0.8fr 1fr 0.9fr",gap:8,padding:"8px 12px",borderBottom:Y<s.length-1?"1px solid var(--border-subtle)":"none",fontSize:12,alignItems:"center"},children:[e.jsx("span",{style:{fontFamily:b.fontMono,fontWeight:600,color:b.textPrimary},children:z.name}),e.jsx("span",{style:{color:b.textSecondary},children:z.type}),e.jsx("span",{style:{fontFamily:b.fontMono,color:z.default!==void 0&&z.default!==null&&z.default!==""?"var(--status-warning)":b.textMuted},children:z.default!==void 0&&z.default!==null&&z.default!==""?JSON.stringify(z.default):z.required?"required":"—"}),e.jsx("span",{style:{color:b.textMuted},children:z.policy})]},z.name))]})]}),e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[e.jsx("span",{style:{...I,marginBottom:0},children:"DQL source"}),e.jsxs("button",{type:"button",onClick:E,style:{display:"inline-flex",alignItems:"center",gap:5,border:"none",background:"none",color:b.accent,fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:b.font,padding:0},children:["Open in DQL Source ",e.jsx(bn,{size:11,strokeWidth:2})]})]}),e.jsx("pre",{style:{margin:0,border:"1px solid var(--border-subtle)",background:b.cellBg,borderRadius:9,padding:"13px 15px",fontSize:11.5,lineHeight:1.65,fontFamily:b.fontMono,whiteSpace:"pre",overflowX:"auto",color:b.textPrimary,maxHeight:320,overflowY:"auto"},children:n.trim()||"Open the builder to author this block."})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:20},children:[e.jsxs("div",{children:[e.jsx("div",{style:I,children:"Tests"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:x.length>0?x.map(z=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12},children:[e.jsx(kt,{size:13,color:"var(--status-success)",strokeWidth:2,style:{flexShrink:0}}),e.jsx("span",{style:{fontFamily:b.fontMono,color:b.textSecondary},children:z})]},z)):e.jsx("span",{style:{fontSize:11.5,color:b.textMuted},children:"No tests yet — add assertions in the builder before certification."})})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>$(z=>!z),style:{display:"flex",alignItems:"center",gap:6,border:"none",background:"none",cursor:"pointer",padding:0,fontFamily:b.font,marginBottom:8},children:[e.jsx(bn,{size:11,color:b.textMuted,strokeWidth:2,style:{transform:re?"rotate(90deg)":"none",transition:"transform 0.12s"}}),e.jsx("span",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:b.textMuted},children:"Lineage"}),re?null:e.jsxs("span",{style:{fontSize:10.5,color:b.textMuted},children:[X," upstream · ",H," downstream"]})]}),re?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap",fontSize:11.5,animation:"dql-agent-fadein 0.18s ease-out"},children:[G.length>0?G.map(z=>N(z)):N("no upstream"),q,N(L,!0),q,J.length>0?J.map(z=>N(z)):N("no downstream yet")]}):null]})]})]})})}function Ar({source:t,metadata:n,semanticLayer:s,dbtStatus:r,domainOptions:o,chartConfig:a,onChange:p,onMetadataChange:m,onOpenAi:f,onSetupRuntime:E,t:l}){const h=Li(t),k={...h,filters:h.requestedFilters},[b,P]=c.useState([]),[L,K]=c.useState(!1),[_,w]=c.useState(null),[x,X]=c.useState(null),[H,re]=c.useState(0);c.useEffect(()=>{let u=!1;if(k.metrics.length===0){P([]),w(null),X(null),K(!1);return}return P([]),w(null),K(!0),X(null),W.getCompatibility(k.metrics).then(M=>{u||(w(M),P(M.dimensions))}).catch(M=>{u||(P([]),X(M instanceof Error?M.message:String(M)))}).finally(()=>{u||K(!1)}),()=>{u=!0}},[s.dimensions,k.metrics.join("|"),H]);const $=new Set(b.flatMap(u=>[u.reference??u.name,u.name])),G=new Map(b.flatMap(u=>[[u.reference??u.name,u.qualifiedName??void 0],[u.name,u.qualifiedName??void 0]])),J=new Map(((_==null?void 0:_.incompatible)??[]).map(u=>[u.name,wr(u.reason)])),I=new Map(b.flatMap(u=>[[u.reference??u.name,u],[u.name,u]])),N=Array.from(new Map([...s.dimensions,...s.timeDimensions].map(u=>{const M=u.reference??u.name;return[M,{...u,name:M}]})).values()),q=new Map(N.flatMap(u=>[[u.name,u],[u.reference??u.name,u]])),V=b.map(u=>{const M=u.reference??u.name;return{...q.get(M)??q.get(u.name),...u,name:M}}),ve=V.filter(u=>u.isTimeDimension||u.type==="time"),te=jn(l),[Q,pe]=c.useState(""),[Se,Pe]=c.useState(""),z=c.useMemo(()=>new Map(s.metrics.map(u=>[u.name,u])),[s.metrics]),Y=c.useMemo(()=>new Map([...N,...V].flatMap(u=>[[u.name,u],[u.reference??u.name,u]])),[N,V]),we=c.useMemo(()=>Ti(s.metrics,Q),[s.metrics,Q]),fe=c.useMemo(()=>Ti(V,Se),[V,Se]),De=Ai(t,"tests"),ge=Array.from(new Set([...k.dimensions,...k.timeDimension?[k.timeDimension]:[],...k.metrics])),Ae=(u,M)=>{m({[u]:M}),p(u==="name"?$t(t,M):ue(t,u,M))},ke=u=>{const M=k.metrics.includes(u)?k.metrics.filter(ee=>ee!==u):[...k.metrics,u];p(Ri(t,M))},Ie=u=>p(Ei(t,"dimensions",u)),Ce=u=>{const M=k.dimensions.includes(u)?k.dimensions.filter(ee=>ee!==u):[...k.dimensions,u];Ie(M)};return c.useEffect(()=>{if(!_||k.metrics.length===0)return;const u=Yo(t,Array.from($));u!==t&&p(u)},[_,t]),e.jsx("div",{style:{height:"100%",overflow:"auto",background:l.appBg},children:e.jsxs("div",{style:{width:"min(820px, 100% - 48px)",margin:"0 auto",padding:"24px 0 40px",display:"flex",flexDirection:"column",animation:"dql-agent-fadein 0.25s ease-out"},children:[e.jsx(Ui,{metadata:n,domains:o,onTextChange:Ae,onFolderChange:u=>m({folderPath:u}),onTagsChange:u=>{m({tags:u}),p(At(t,u))},t:l}),e.jsxs(be,{title:"Metric and grain",hint:"Pick governed semantic objects — they compile to the DQL script.",t:l,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[e.jsxs("span",{style:{fontSize:11,fontWeight:750,color:l.textSecondary},children:["Governed metrics · ",k.metrics.length," selected"]}),L&&e.jsx("span",{style:{fontSize:10,color:l.textMuted},children:"Checking compatibility…"})]}),e.jsx(Di,{kind:"metric",total:s.metrics.length,search:Q,onSearchChange:pe,matches:we,pool:s.metrics,selected:k.metrics,resolveLabel:u=>{var M;return((M=z.get(u))==null?void 0:M.label)||u},onToggle:ke,compatible:u=>{var M,ee,de,se;return((ee=(M=z.get(u))==null?void 0:M.execution)==null?void 0:ee.status)!=="requires_setup"&&((se=(de=z.get(u))==null?void 0:de.execution)==null?void 0:se.status)!=="unsupported"},t:l}),s.metrics.some(u=>u.execution&&u.execution.status!=="ready")&&e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",fontSize:10.5,color:l.textMuted,lineHeight:1.4},children:[e.jsx("span",{style:{flex:1},children:"Complex metrics are imported but need a full semantic runtime to execute."}),e.jsx("button",{type:"button",onClick:E,style:{border:"none",background:"transparent",color:l.accent,fontSize:10.5,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Set up runtime →"})]}),((_==null?void 0:_.engine)||(_==null?void 0:_.degraded))&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:10,color:l.textMuted,marginTop:2},children:[e.jsxs("span",{style:{padding:"1px 7px",borderRadius:999,background:"var(--accent-dim)",color:"var(--accent)",fontWeight:700},children:["Runs via ",jr[_.engine]??_.engine]}),_.degraded&&e.jsx("span",{style:{color:"var(--status-warning)"},children:_.degraded})]}),x&&e.jsxs("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,fontSize:11,color:"var(--status-warning)",lineHeight:1.4,marginTop:4},children:[e.jsx(ft,{size:14,style:{flexShrink:0}}),e.jsxs("span",{style:{flex:1},children:["Could not verify governed dimensions: ",x,". Dimension selection is paused so an unapproved join cannot be saved."]}),e.jsx("button",{type:"button",onClick:()=>re(u=>u+1),style:Z(l),children:"Retry"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 150px",gap:8},children:[e.jsx(A,{label:"Time dimension",t:l,children:e.jsxs("select",{disabled:k.metrics.length===0||L||!!x,value:k.timeDimension,onChange:u=>p(Si(t,"time_dimension",u.target.value)),style:{...te,opacity:k.metrics.length===0||L||x?.6:1},children:[e.jsx("option",{value:"",children:"None"}),ve.map(u=>e.jsxs("option",{value:u.reference??u.name,children:[u.label||u.name," · ",u.name]},u.reference??u.name))]})}),e.jsx(A,{label:"Grain",t:l,children:e.jsxs("select",{value:k.granularity,onChange:u=>p(Si(t,"granularity",u.target.value)),style:te,children:[e.jsx("option",{value:"",children:"None"}),Cr(k.timeDimension,I,s.timeDimensions).map(u=>e.jsx("option",{value:u,children:u},u))]})})]}),s.metrics.length===0&&(s.loading?e.jsxs("div",{role:"status",style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:l.textMuted,lineHeight:1.45},children:[e.jsx(Ze,{size:14,className:"dql-spin"}),"Loading ",((r==null?void 0:r.counts.metrics)??0).toLocaleString()," semantic metrics from parsed dbt artifacts… Large catalogs continue loading in the background."]}):((r==null?void 0:r.counts.metrics)??0)>0||r!=null&&r.artifacts.semanticManifest.exists?e.jsxs("div",{role:"alert",style:{fontSize:12,color:"var(--status-warning)",lineHeight:1.45},children:["dbt artifacts contain ",((r==null?void 0:r.counts.metrics)??0).toLocaleString()," metrics, but Block Studio could not load them. Refresh the semantic layer; another dbt parse is not required."]}):e.jsx("div",{style:{fontSize:12,color:"var(--status-warning)",lineHeight:1.45},children:"No semantic metrics were discovered. Run dbt parse or import a semantic layer, then refresh Block Studio."})),k.metrics.length>1&&_&&b.length===0&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"#d29922",fontSize:11,lineHeight:1.4},children:[e.jsx(ft,{size:14})," These metrics do not expose a common dimension or join path.",e.jsx("button",{type:"button",onClick:f,style:Z(l),children:"Resolve with AI"})]})]}),e.jsxs(be,{title:"Chart intent",hint:"How apps and answers render this block by default.",t:l,children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:10},children:[e.jsx(A,{label:"Type",t:l,children:e.jsxs("select",{value:a.chart??"table",onChange:u=>p(Ke(t,{...a,chart:u.target.value})),style:te,children:[e.jsx("option",{value:"table",children:"Table"}),Oi.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))]})}),e.jsx(A,{label:"X axis",t:l,children:e.jsxs("select",{value:a.x??"",onChange:u=>p(Ke(t,{...a,x:u.target.value})),style:te,children:[e.jsx("option",{value:"",children:"Auto"}),ge.map(u=>e.jsx("option",{value:u,children:Xe(u)},u))]})}),e.jsx(A,{label:"Y axis",t:l,children:e.jsxs("select",{value:a.y??"",onChange:u=>p(Ke(t,{...a,y:u.target.value})),style:te,children:[e.jsx("option",{value:"",children:"Auto"}),ge.map(u=>e.jsx("option",{value:u,children:Xe(u)},u))]})}),e.jsx(A,{label:"Series / color",t:l,children:e.jsxs("select",{value:a.color??"",onChange:u=>p(Ke(t,{...a,color:u.target.value})),style:te,children:[e.jsx("option",{value:"",children:"None"}),ge.map(u=>e.jsx("option",{value:u,children:Xe(u)},u))]})})]}),e.jsx(A,{label:"Title",t:l,children:e.jsx("input",{value:a.title??"",onChange:u=>p(Ke(t,{...a,title:u.target.value})),placeholder:"Chart title",style:te})})]}),e.jsx(be,{title:"Dimensions",hint:"Governed group-bys checked against the metric's join path.",t:l,children:k.metrics.length===0?e.jsx("div",{style:{fontSize:12,color:l.textMuted},children:"Choose one or more governed metrics first. Only their connected, approved dimensions will appear."}):L?e.jsxs("div",{role:"status",style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:l.textMuted},children:[e.jsx(Ze,{size:14,className:"dql-spin"}),"Checking common governed dimensions…"]}):x?e.jsx("div",{style:{fontSize:12,color:"var(--status-warning)"},children:"Dimension selection is unavailable until compatibility succeeds."}):V.length===0?e.jsx("div",{style:{fontSize:12,color:l.textMuted},children:"No dimensions are loaded yet."}):e.jsx(Di,{kind:"dimension",total:V.length,search:Se,onSearchChange:Pe,matches:fe,pool:V,selected:k.dimensions,resolveLabel:u=>{var M;return((M=Y.get(u))==null?void 0:M.label)||u},resolveMachineName:u=>{var M;return G.get(u)??((M=Y.get(u))==null?void 0:M.name)??u},reasonFor:u=>J.get(u),onToggle:Ce,compatible:u=>$.has(u),disabled:k.metrics.length===0||L||!!x,emptyHint:L?"Checking common governed dimensions…":x?"Retry compatibility before selecting dimensions.":"Choose a metric first; dimensions are checked against its governed join path.",t:l})}),e.jsxs(be,{title:"Filters and parameters",hint:"Values-only inputs so this block is reusable across periods and regions.",t:l,children:[e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:Array.from(new Set([...k.dimensions,...k.timeDimension?[k.timeDimension]:[]])).map(u=>{var ee;const M=k.filters.includes(u);return e.jsx("button",{type:"button",onClick:()=>p(Xo(t,M?k.filters.filter(de=>de!==u):[...k.filters,u])),style:Wt(l,M),children:((ee=Y.get(u))==null?void 0:ee.label)||u},u)})}),e.jsx("div",{style:{fontSize:10,color:l.textMuted,marginTop:8},children:k.dimensions.length===0&&!k.timeDimension?"Search and add a compatible dimension first, then choose whether it should also be a dynamic filter.":"Selected fields become governed runtime filters. Values stay dynamic rather than being hard-coded into SQL."}),k.filters.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:k.filters.map(u=>e.jsxs("span",{style:Wt(l,!0),children:[Xe(u)," · dynamic"]},u))})]}),e.jsx(Qi,{source:t,kind:"semantic",onChange:p,t:l}),e.jsx(be,{title:`Output fields${ge.length?` · ${ge.length}`:""}`,hint:"What consumers see when this block answers a question.",t:l,children:e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:ge.length>0?ge.map(u=>e.jsx("span",{style:Wt(l,!0),children:Xe(u)},u)):e.jsx("span",{style:{fontSize:11,color:l.textMuted},children:"Select metrics and dimensions to define outputs."})})}),e.jsx(be,{title:"Tests",hint:"Assertions checked on every run and required for certification.",t:l,children:e.jsx(_t,{multiline:!0,value:De,onChange:u=>p(_i(t,"tests",u)),placeholder:`assert row_count >= 1
|
|
11
|
+
assert total_revenue >= 0`,style:{...te,minHeight:64,resize:"vertical",fontFamily:l.fontMono}})}),e.jsxs("details",{style:{padding:"14px 0",color:l.textSecondary,fontFamily:l.font},children:[e.jsx("summary",{style:{cursor:"pointer",fontSize:11,fontWeight:750},children:"Generated DQL preview"}),e.jsx("pre",{style:{maxHeight:240,overflow:"auto",margin:"10px 0 0",whiteSpace:"pre-wrap",color:l.textSecondary,fontSize:11,lineHeight:1.45,fontFamily:l.fontMono,border:"1px solid var(--border-subtle)",background:"var(--bg-2)",borderRadius:9,padding:"12px 14px"},children:t})]})]})})}function Ui({metadata:t,domains:n,onTextChange:s,onFolderChange:r,onTagsChange:o,t:a}){const p=kr(t==null?void 0:t.domain,n),m=jn(a);return e.jsx(be,{title:"Details",hint:"Name, ownership, and where this block lives.",t:a,children:e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[e.jsx(A,{label:"Block name",t:a,children:e.jsx("input",{value:(t==null?void 0:t.name)??"",onChange:f=>s("name",f.target.value),style:{...m,fontFamily:a.fontMono}})}),e.jsx(A,{label:"Domain",t:a,children:e.jsxs("select",{"aria-label":"Block domain",value:(t==null?void 0:t.domain)??"",onChange:f=>s("domain",f.target.value),style:m,children:[e.jsx("option",{value:"",children:"Select domain…"}),p.map(f=>e.jsx("option",{value:f.value,disabled:f.disabled,children:f.label},f.value))]})}),e.jsx(A,{label:"Owner",t:a,children:e.jsx("input",{value:(t==null?void 0:t.owner)??"",onChange:f=>s("owner",f.target.value),placeholder:"Required to save",style:m})}),e.jsx(A,{label:"Tags",t:a,children:e.jsx(Wi,{values:(t==null?void 0:t.tags)??[],onChange:o,placeholder:"finance, emea",style:m})}),e.jsxs("div",{style:{gridColumn:"1 / -1"},children:[e.jsx(A,{label:"Folder (optional)",t:a,children:e.jsx("input",{"aria-label":"Block folder",value:(t==null?void 0:t.folderPath)??"",onChange:f=>r(f.target.value),placeholder:"executive/monthly",style:{...m,fontFamily:a.fontMono}})}),e.jsx("div",{style:{marginTop:5,fontSize:10,color:a.textMuted,fontFamily:a.fontMono},children:Gi(t)})]}),e.jsx("div",{style:{gridColumn:"1 / -1"},children:e.jsx(A,{label:"Description",t:a,children:e.jsx("input",{value:(t==null?void 0:t.description)??"",onChange:f=>s("description",f.target.value),placeholder:"What business question does this answer?",style:m})})})]})})}function Ti(t,n){const s=n.trim().toLowerCase();return s.length<2?[]:t.filter(r=>[r.name,r.label,r.description,r.domain].filter(Boolean).some(o=>o.toLowerCase().includes(s))).slice(0,30)}function Di({kind:t,total:n,search:s,onSearchChange:r,matches:o,pool:a=[],selected:p,resolveLabel:m,resolveMachineName:f,reasonFor:E,onToggle:l,compatible:h=()=>!0,disabled:k=!1,emptyHint:b,t:P}){const[L,K]=c.useState(!1),_=c.useRef(null),w=c.useRef(null),x=t==="metric"?"measures":"dimensions",X=t==="metric"?"Σ":"ab",H=t==="metric"?"var(--accent)":"var(--status-success)",re=t==="metric"?"var(--accent-dim)":"var(--status-success-bg)",$=s.trim().length>=2,G=$?o:a.filter(I=>!p.includes(I.name)).slice(0,8),J=()=>{K(!1),r("")};return c.useEffect(()=>{if(!L)return;requestAnimationFrame(()=>{var q;return(q=_.current)==null?void 0:q.focus()});const I=q=>{w.current&&!w.current.contains(q.target)&&J()},N=q=>{q.key==="Escape"&&J()};return document.addEventListener("mousedown",I),document.addEventListener("keydown",N),()=>{document.removeEventListener("mousedown",I),document.removeEventListener("keydown",N)}},[L]),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginTop:9},children:[p.map(I=>e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11.5,padding:"4px 9px",borderRadius:999,background:re,color:H,border:`1px solid ${t==="metric"?"rgba(107,93,211,0.2)":"rgba(46,139,87,0.25)"}`,fontFamily:P.fontMono},children:[t==="metric"?`Σ ${m(I)}`:m(I),e.jsx("button",{type:"button",onClick:()=>l(I),title:`Remove ${m(I)}`,style:{border:"none",background:"none",color:H,cursor:"pointer",padding:0,fontSize:12,lineHeight:1,fontFamily:"inherit"},children:"×"})]},I)),e.jsxs("span",{ref:w,style:{position:"relative"},children:[e.jsxs("button",{type:"button",disabled:k,onClick:()=>K(I=>!I),title:k?b:`Add ${t}`,style:{border:"1.5px dashed var(--border-strong)",background:"transparent",borderRadius:999,padding:"4px 10px",fontSize:11,fontFamily:P.font,color:k?P.textMuted:P.textSecondary,cursor:k?"not-allowed":"pointer",opacity:k?.6:1},children:["+ Add ",t]}),L&&!k?e.jsxs("div",{style:{position:"absolute",right:0,top:30,zIndex:40,width:300,background:P.cellBg,border:`1px solid ${P.headerBorder}`,borderRadius:10,boxShadow:"0 10px 30px rgba(26,26,26,0.14)",overflow:"hidden",animation:"dql-agent-fadein 0.12s ease-out"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,padding:"8px 10px",borderBottom:"1px solid var(--border-subtle)"},children:[e.jsx(er,{size:12,color:P.textMuted,style:{flexShrink:0}}),e.jsx("input",{ref:_,value:s,onChange:I=>r(I.target.value),placeholder:`Search ${n.toLocaleString()} ${x}…`,style:{flex:1,border:"none",background:"none",outline:"none",fontSize:12,fontFamily:P.font,color:P.textPrimary,minWidth:0}}),e.jsx("button",{type:"button",onClick:J,style:{border:"none",background:"none",color:P.textMuted,cursor:"pointer",padding:0,fontSize:13,lineHeight:1},children:"×"})]}),e.jsx("div",{style:{maxHeight:208,overflow:"auto"},children:G.length===0?e.jsx("div",{style:{padding:10,fontSize:11,color:P.textMuted},children:$?`No ${x} match “${s}”.`:`No more ${x} to add.`}):G.map(I=>{const N=p.includes(I.name),q=h(I.name),V=(f==null?void 0:f(I.name))??I.name,ve=V!==(I.label||I.name),te=q?void 0:(E==null?void 0:E(I.name))??"Not compatible with every selected metric";return e.jsxs("button",{type:"button",disabled:!q,onClick:()=>{l(I.name),N||J()},title:te??I.description??V,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 10px",border:"none",background:N?re:"none",cursor:q?"pointer":"not-allowed",textAlign:"left",fontFamily:P.font,borderBottom:"1px solid var(--border-subtle)",opacity:q?1:.5},children:[e.jsx("span",{style:{flexShrink:0,width:16,height:16,borderRadius:4,background:re,color:H,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:t==="metric"?10:9,fontWeight:700,fontFamily:P.fontMono},children:X}),e.jsxs("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:1,overflow:"hidden"},children:[e.jsx("span",{style:{fontSize:12,fontFamily:P.font,color:P.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:I.label||I.name}),ve?e.jsx("span",{style:{fontSize:10,fontFamily:P.fontMono,color:P.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:V}):null]}),e.jsx("span",{style:{flexShrink:0,fontSize:10,color:P.textMuted},children:I.domain||I.type||""})]},I.name)})}),e.jsx("div",{style:{padding:"6px 10px",background:"var(--bg-1)",fontSize:10,color:P.textMuted},children:$?`${G.length} match${G.length===1?"":"es"} · certified shown first`:`Showing top ${G.length} of ${n.toLocaleString()} · type to search all`})]}):null]})]})}function _r({mode:t,onModeChange:n,t:s}){const r=[{key:"semantic",label:"Semantic picker"},{key:"custom",label:"Raw SQL"}];return e.jsx("div",{style:{flexShrink:0,borderBottom:`1px solid ${s.headerBorder}`,background:s.appBg},children:e.jsxs("div",{style:{width:"min(820px, 100% - 48px)",margin:"0 auto",padding:"10px 0",display:"flex",alignItems:"center",gap:10},children:[e.jsx("span",{style:{fontSize:10.5,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:s.textMuted},children:"Query"}),e.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:2,padding:2,border:`1px solid ${s.headerBorder}`,borderRadius:8,background:s.cellBg},children:r.map(o=>{const a=o.key===t;return e.jsx("button",{type:"button",onClick:()=>n(o.key),style:{border:"none",borderRadius:6,padding:"5px 12px",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:s.font,background:a?"var(--accent-dim)":"transparent",color:a?s.accent:s.textMuted},children:o.label},o.key)})}),e.jsx("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font},children:t==="semantic"?"Pick governed metrics & dimensions — they compile to DQL.":"Write SQL and convert it into a governed DQL script."})]})})}function Wr({source:t,metadata:n,domainOptions:s,chartConfig:r,onChange:o,onMetadataChange:a,onConvertToDql:p,t:m}){var K,_;const f=jn(m),E=((_=(K=t.match(/query\s*=\s*"""([\s\S]*?)"""/i))==null?void 0:K[1])==null?void 0:_.trim())??"",[l,h]=c.useState(E),k=Vi(l),b=Ai(t,"tests"),P=w=>{h(w),o($i(t,w))},L=(w,x)=>{a({[w]:x}),o(w==="name"?$t(t,x):ue(t,w,x))};return e.jsx("div",{style:{height:"100%",overflow:"auto",background:m.appBg},children:e.jsxs("div",{style:{width:"min(820px, 100% - 48px)",margin:"0 auto",padding:"24px 0 40px",display:"flex",flexDirection:"column",animation:"dql-agent-fadein 0.25s ease-out"},children:[e.jsx(Ui,{metadata:n,domains:s,onTextChange:L,onFolderChange:w=>a({folderPath:w}),onTagsChange:w=>{a({tags:w}),o(At(t,w))},t:m}),e.jsxs(be,{title:"Query",hint:"Write raw SQL — it compiles into a governed DQL script.",t:m,children:[e.jsx("textarea",{rows:7,value:l,onChange:w=>P(w.target.value),spellCheck:!1,style:{border:"1px solid var(--border-default)",background:"var(--bg-1)",borderRadius:8,padding:"10px 12px",fontSize:11.5,lineHeight:1.6,fontFamily:m.fontMono,color:m.textPrimary,outline:"none",resize:"vertical"},placeholder:`SELECT
|
|
17
12
|
category,
|
|
18
13
|
SUM(revenue) AS revenue
|
|
19
14
|
FROM {{ ref('orders') }}
|
|
20
|
-
GROUP BY 1`}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsx("button",{type:"button",onClick:p,disabled:!l.trim(),style:{display:"inline-flex",alignItems:"center",gap:6,height:28,padding:"0 12px",borderRadius:8,border:`1px solid ${m.accent}`,background:"var(--accent-dim)",color:m.accent,fontSize:11.5,fontWeight:650,cursor:l.trim()?"pointer":"not-allowed",fontFamily:m.font,opacity:l.trim()?1:.6},children:"Convert to DQL script"}),e.jsxs("span",{style:{fontSize:10.5,color:m.textMuted,fontFamily:m.font},children:["Detects ",e.jsx("span",{style:{fontFamily:m.fontMono},children:"${params}"})," and grounds tables against dbt. Open the DQL Source editor for the full script."]})]})]}),e.jsxs(be,{title:"Chart intent",hint:"How apps and answers render this block by default.",t:m,children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:10},children:[e.jsx(A,{label:"Type",t:m,children:e.jsxs("select",{value:r.chart??"table",onChange:w=>o(Ke(t,{...r,chart:w.target.value})),style:f,children:[e.jsx("option",{value:"table",children:"Table"}),
|
|
21
|
-
assert revenue >= 0`,style:{...f,minHeight:64,resize:"vertical",fontFamily:m.fontMono}})}),e.jsxs("details",{style:{padding:"14px 0",color:m.textSecondary,fontFamily:m.font},children:[e.jsx("summary",{style:{cursor:"pointer",fontSize:11,fontWeight:750},children:"Generated DQL preview"}),e.jsx("pre",{style:{maxHeight:240,overflow:"auto",margin:"10px 0 0",whiteSpace:"pre-wrap",color:m.textSecondary,fontSize:11,lineHeight:1.45,fontFamily:m.fontMono,border:"1px solid var(--border-subtle)",background:"var(--bg-2)",borderRadius:9,padding:"12px 14px"},children:t})]})]})})}function Or({semanticChoice:t,databaseWarning:n,onDismiss:s,onInsertAdvanced:r,onCreateSemantic:o,t:a}){const p=t?`${t.kind==="metric"?"Metric":"Dimension"} "${t.name}" belongs in a Semantic Block. SQL Blocks can still use advanced @metric/@dim refs when you choose that explicitly.`:n??"";return e.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${a.headerBorder}`,background:`${a.accent}10`,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:12,color:a.textSecondary,lineHeight:1.4,flex:1,minWidth:260},children:p}),t&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:o,style:Z(a),children:"Create Semantic Block"}),e.jsx("button",{onClick:r,style:Te(a),children:"Insert advanced ref"})]}),e.jsx("button",{onClick:s,style:Z(a),children:"Dismiss"})]})}function Sn(t){var s,r,o,a,p;const n=((r=(s=t.preview)==null?void 0:s.result)==null?void 0:r.rowCount)??((p=(a=(o=t.preview)==null?void 0:o.result)==null?void 0:a.rows)==null?void 0:p.length);return typeof n=="number"?n:void 0}function Ft(t){return t?t.startsWith("blocks/_drafts/")||/^domains\/[^/]+\/blocks\/_drafts\//.test(t):!1}function lt(t){var n,s,r,o,a;return t.reviewStatus==="saved"?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"saved",rows:Sn(t),message:"Block saved."}:((n=t.validation)==null?void 0:n.valid)===!1?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"needs_attention",message:((s=t.validation.diagnostics.find(p=>p.severity==="error"))==null?void 0:s.message)??"DQL validation needs attention."}:t.preview?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"ready",rows:Sn(t),savedPath:t.savedPath,message:Ft(t.savedPath)?"Preview ran successfully. Draft is saved for review.":"Preview ran successfully. Nothing is written until you save."}:((r=t.draftSave)==null?void 0:r.status)==="saved"||Ft(t.savedPath)?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"ready",savedPath:((o=t.draftSave)==null?void 0:o.path)??t.savedPath,message:"Draft saved. Run preview, then certify when ready."}:((a=t.draftSave)==null?void 0:a.status)==="error"?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"needs_attention",message:t.draftSave.error??"Draft preparation failed."}:{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"queued",message:"Ready to process."}}function qr(t){return t==="retrieving"?"Checking certified blocks and semantic metrics.":t==="reviewing"?"Reviewing governed evidence and building the candidate.":t==="ready"?"Analysis ready. Preparing preview.":t==="needs_attention"?"Analysis needs attention.":"Queued for governed retrieval."}async function Nr(t,n){for(let s=0;s<240;s+=1){const r=await W.getDqlGenerationSession(t);if(n(r),r.candidates.every(o=>o.analysisStatus==="ready"||o.analysisStatus==="needs_attention"))return r;await new Promise(o=>window.setTimeout(o,500))}throw new Error("Import analysis is still running. You can leave this workspace and resume the session later.")}async function Hr(t,n,s){let r=0;const o=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;r<t.length;){const a=r;r+=1,await s(t[a])}});await Promise.all(o)}function en(t){return!!(t.generationMode||t.draftSave||Ft(t.savedPath))}function Qr(t){return t==="creating"?"Reading SQL":t==="running"?"Running previews":t==="saving"?"Saving blocks":t==="complete"?"Import complete":"Ready"}function Ur(t){return t==="needs_attention"?"needs attention":t.replace("_"," ")}function Kr(t){return t==="saved"||t==="ready"?"ok":t==="needs_attention"?"warn":"info"}function Gr({session:t,sessions:n,sessionsLoading:s,onClose:r,onSessionChange:o,onRefreshSessions:a,onSelectCandidate:p,onSavedCandidate:m,defaultDomain:f,defaultOwner:E,themeMode:l,t:h,inline:k=!1}){const[b,P]=c.useState("paste"),[L,K]=c.useState(""),[_,w]=c.useState(""),[x,X]=c.useState([]),[H,re]=c.useState(f),[$,G]=c.useState(E),[J,I]=c.useState(null),[N,q]=c.useState(!1),[V,ve]=c.useState(!1),[te,Q]=c.useState(null),[pe,Se]=c.useState(null),[Pe,z]=c.useState(!1),[Y,we]=c.useState(!0),[fe,De]=c.useState(""),[ge,Ae]=c.useState(!1),[ke,Ie]=c.useState({}),[Ce,u]=c.useState("idle"),[M,ee]=c.useState({}),de=c.useMemo(()=>t?t.candidates.find(g=>g.id===J)??t.candidates[0]??null:null,[t,J]);c.useEffect(()=>{if(!(t!=null&&t.candidates.length)){I(null);return}(!J||!t.candidates.some(g=>g.id===J))&&I(t.candidates[0].id)},[t,J]),c.useEffect(()=>{Ie({})},[t==null?void 0:t.id]),c.useEffect(()=>{we(!(t!=null&&t.candidates.length))},[t==null?void 0:t.id,t==null?void 0:t.candidates.length]),c.useEffect(()=>{if(!t){ee({}),u("idle");return}ee(Object.fromEntries(t.candidates.map(g=>[g.id,lt(g)]))),u(g=>g==="idle"?"complete":g)},[t==null?void 0:t.id]);const se=c.useMemo(()=>{const g=fe.trim().toLowerCase(),T=(t==null?void 0:t.candidates)??[];return g?T.filter(D=>[D.name,D.domain,D.sourcePath,D.description,...D.lineage.sourceTables].some(C=>C.toLowerCase().includes(g))):T},[fe,t]),qe=ge||fe.trim()?se:se.slice(0,10),le=((t==null?void 0:t.candidates.map(g=>M[g.id]??lt(g)))??[]).reduce((g,T)=>(T.status==="saved"?g.saved+=1:T.status==="ready"?g.ready+=1:T.status==="needs_attention"?g.attention+=1:g.processing+=1,g),{saved:0,ready:0,attention:0,processing:0}),Ne=t?le.saved>0?3:2:1,ae=(t==null?void 0:t.candidates.filter(g=>{var T;return((T=g.validation)==null?void 0:T.valid)!==!1}).length)??0,Je=!!(b==="paste"?_.trim():b==="upload"?x.length>0:L.trim()),et=()=>b==="paste"?{inputMode:"paste",sourceKind:"raw-sql",domain:H,owner:$,sources:[{path:"pasted.sql",content:_}],async:!0,persistence:"session-only"}:b==="upload"?{inputMode:"upload",sourceKind:"raw-sql",domain:H,owner:$,sources:x,async:!0,persistence:"session-only"}:{path:L,inputMode:"path",sourceKind:"raw-sql",domain:H,owner:$,async:!0,persistence:"session-only"},_e=async()=>{var g,T,D;q(!0),ve(!0),Q(null),Ie({}),ee({}),u("creating");try{const C=await W.createDqlGenerationSession(et());let U=C,ne=Object.fromEntries(C.candidates.map(R=>[R.id,{...lt(R),status:"queued",message:"Queued for governed retrieval."}]));const v=(R,O)=>{ne={...ne,[R]:O(ne[R])},ee(ne)},B=R=>{U={...U,candidates:U.candidates.map(O=>O.id===R.id?R:O)},o(U)};o(U),I(((g=U.candidates[0])==null?void 0:g.id)??null),ee(ne),await a(),u("running"),U=await Nr(C.id,R=>{U=R,o(R);for(const O of R.candidates)v(O.id,We=>({...We,name:O.name,sourcePath:O.sourcePath,status:O.analysisStatus==="needs_attention"?"needs_attention":O.analysisStatus==="ready"?"queued":"running",message:qr(O.analysisStatus)}))}),await Hr(U.candidates,2,async R=>{if(R.analysisStatus!=="needs_attention"){v(R.id,O=>({...O,status:"running",message:"Running preview."}));try{const O=await W.previewDqlGenerationCandidate(U.id,R.id);B(O),v(R.id,We=>{var Ee;return{...We,name:O.name,sourcePath:O.sourcePath,status:"ready",rows:Sn(O),savedPath:((Ee=O.draftSave)==null?void 0:Ee.path)??O.savedPath,message:O.recommendedAction==="reuse_existing"?"A governed block already answers this SQL. Reuse it instead of saving a duplicate.":"Preview ran successfully. Nothing is written until you save."}})}catch(O){const We=(O==null?void 0:O.message)??"Preview failed.";Ie(Ee=>({...Ee,[R.id]:We})),v(R.id,Ee=>({...Ee,status:"needs_attention",message:We}))}}}),o(U),I(((T=U.candidates.find(R=>R.reviewStatus!=="rejected"))==null?void 0:T.id)??((D=U.candidates[0])==null?void 0:D.id)??null),await a(),u("complete")}catch(C){Q((C==null?void 0:C.message)??"Import failed."),u("idle")}finally{q(!1),ve(!1)}},tt=async g=>{var T,D;q(!0),Q(null);try{const C=await W.getDqlGenerationSession(g).catch(()=>W.getBlockStudioImport(g));o(C),I(((T=C.candidates.find(U=>U.reviewStatus!=="saved"&&U.reviewStatus!=="rejected"))==null?void 0:T.id)??((D=C.candidates[0])==null?void 0:D.id)??null),Ie({}),u("complete")}catch(C){Q((C==null?void 0:C.message)??"Failed to resume import session.")}finally{q(!1)}},at=async g=>{Se({kind:"one",id:g})},dt=async()=>{n.length!==0&&Se({kind:"all"})},ht=async()=>{if(!pe)return;const g=pe;q(!0),Q(null);try{g.kind==="one"?await W.deleteBlockStudioImport(g.id):await W.clearBlockStudioImports(),(g.kind==="all"||(t==null?void 0:t.id)===g.id)&&(o(null),I(null)),Se(null),await a()}catch(T){Q((T==null?void 0:T.message)??"Failed to update import history.")}finally{q(!1)}},Re=g=>{t&&(o({...t,candidates:t.candidates.map(T=>T.id===g.id?g:T)}),ee(T=>({...T,[g.id]:lt(g)})))},mt=async g=>{if(t){q(!0),Q(null),Ie(T=>{if(!T[g.id])return T;const D={...T};return delete D[g.id],D});try{const T=en(g)?await W.previewDqlGenerationCandidate(t.id,g.id):await W.runBlockStudioImportCandidate(t.id,g.id);Re(T),I(T.id),Ie(D=>{if(!D[g.id])return D;const C={...D};return delete C[g.id],C})}catch(T){const D=(T==null?void 0:T.message)??"Candidate run failed.";Q(D),I(g.id),Ie(C=>({...C,[g.id]:D}))}finally{q(!1)}}},Ge=async g=>{if(!t)return;const T=g.owner.trim()||$.trim();if(!T){Q("Owner is required before a block can be saved or certified.");return}q(!0),Q(null);try{if(en(g)){const D=await W.saveSelectedDqlGenerationCandidates(t.id,{candidateIds:[g.id],owner:T});o(D.session);const C=D.results[0];if(!C||C.status==="error")throw new Error((C==null?void 0:C.error)??(C==null?void 0:C.blockers.join(" "))??"Candidate save failed.");C.candidate&&Re(C.candidate),C.candidate&&C.block&&m(C.candidate,C.block),C.status==="draft"&&C.blockers.length>0&&Q(`Saved as draft: ${C.blockers.join(" ")}`)}else{const D=await W.saveBlockStudioImportCandidate(t.id,g.id);Re(D.candidate),m(D.candidate,D.block)}await a()}catch(D){const C=(D==null?void 0:D.message)??"Candidate save failed.";Q(C.includes("409")||C.includes("already exists")?"A block with this name already exists. Rename this candidate, then save again.":C)}finally{q(!1)}},gt=async()=>{if(!t)return;const g=$.trim()||t.defaults.owner.trim();if(!g){Q("Owner is required before blocks can be saved or certified.");return}ve(!0),Q(null);try{const T=t.candidates.filter(B=>B.reviewStatus!=="rejected"&&B.analysisStatus!=="needs_attention").map(B=>B.id),D=await W.saveSelectedDqlGenerationCandidates(t.id,{candidateIds:T,owner:g});o(D.session);const C=new Map(D.results.filter(B=>B.status==="error").map(B=>[B.candidateId,B.error??B.blockers.join(" ")])),U=new Map(D.results.filter(B=>B.path).map(B=>[B.candidateId,B.path]));ee(Object.fromEntries(D.session.candidates.map(B=>{const R=C.get(B.id),O=U.get(B.id)??B.savedPath;return R?[B.id,{...lt(B),status:"needs_attention",message:R.includes("409")||R.includes("already exists")?"A block with this name already exists. Rename it in advanced details, then save again.":R}]:O||B.reviewStatus==="saved"?[B.id,{...lt(B),status:"saved",savedPath:O,message:"Block saved."}]:[B.id,lt(B)]}))),await a();const ne=D.results.filter(B=>B.status==="error").length,v=D.results.filter(B=>B.status==="draft").length;(ne>0||v>0)&&Q(`${D.results.length-ne} saved. ${v} stayed draft; ${ne} need attention.`)}catch(T){Q((T==null?void 0:T.message)??"Save all failed.")}finally{ve(!1)}},Ve=async g=>{if(!t)return;const T=await W.updateBlockStudioImportCandidate(t.id,g.id,{reviewStatus:"rejected"});Re(T),a()},xt=async g=>{const D=Array.from(g??[]).filter(U=>U.name.toLowerCase().endsWith(".sql")),C=await Promise.all(D.map(async U=>({path:U.name,content:await U.text()})));X(C),C.length>0&&K("")};return e.jsxs("div",{style:{position:"relative",height:"100%",display:"grid",gridTemplateRows:"80px minmax(0, 1fr)",minHeight:0,background:h.appBg,borderRadius:k?0:8},children:[e.jsxs("header",{style:{borderBottom:`1px solid ${h.headerBorder}`,background:h.cellBg,padding:"14px 14px 12px",display:"flex",alignItems:"center",gap:14,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,minWidth:260},children:[e.jsx("span",{style:{width:34,height:34,borderRadius:8,display:"inline-flex",alignItems:"center",justifyContent:"center",color:h.accent,background:`${h.accent}16`,flexShrink:0},children:e.jsx(Lt,{size:17,strokeWidth:2,"aria-hidden":"true"})}),e.jsxs("span",{style:{display:"grid",gap:2,minWidth:0},children:[e.jsx("span",{style:{fontSize:15,fontWeight:800,color:h.textPrimary,fontFamily:h.font},children:"Import SQL to DQL"}),e.jsx("span",{style:{fontSize:11,color:h.textMuted,fontFamily:h.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"SQL source to AI-grounded drafts to review and certify"})]})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(130px, 1fr))",gap:6,width:"min(560px, 44vw)",minWidth:390},children:[e.jsx(xn,{index:1,active:Ne===1,complete:!!t,title:"Source",detail:b==="paste"?"Paste SQL":b==="upload"?"Upload files":"Local path",t:h}),e.jsx(xn,{index:2,active:Ne===2,complete:le.ready>0||le.saved>0,title:"Draft",detail:t?`${t.candidates.length} blocks · ${ae} ready`:"Generate DQL",t:h}),e.jsx(xn,{index:3,active:Ne===3,complete:le.saved>0,title:"Review",detail:le.saved>0?`${le.saved} certified`:"Preview and certify",t:h})]}),e.jsx("div",{style:{flex:1}}),e.jsx("button",{onClick:r,title:"Close import","aria-label":"Close import",style:{...Z(h),width:32,height:32,padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e.jsx(br,{size:15,strokeWidth:2,"aria-hidden":"true"})})]}),e.jsxs("div",{style:{minHeight:0,display:"grid",gridTemplateColumns:"300px minmax(0, 1fr)"},children:[e.jsxs("aside",{style:{borderRight:`1px solid ${h.headerBorder}`,display:"grid",gridTemplateRows:"auto minmax(0, 1fr) auto",minHeight:0,background:h.cellBg},children:[e.jsxs("section",{style:{borderBottom:`1px solid ${h.headerBorder}`,padding:12,display:"grid",gap:10},children:[e.jsxs("button",{onClick:()=>we(g=>!g),style:{background:"transparent",border:"none",color:h.textPrimary,cursor:"pointer",display:"flex",alignItems:"center",gap:8,padding:0,fontFamily:h.font,textAlign:"left"},children:[e.jsx(Qi,{size:14,strokeWidth:2,color:h.accent,"aria-hidden":"true"}),e.jsx("span",{style:{fontSize:12,fontWeight:800,flex:1},children:"Source"}),t&&e.jsx("span",{style:{fontSize:10,color:h.textMuted},children:Y?"Hide":"Edit"})]}),Y?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:4},children:["paste","upload","path"].map(g=>e.jsx("button",{onClick:()=>P(g),style:{...Z(h),padding:"6px 4px",color:b===g?h.accent:h.textSecondary,borderColor:b===g?h.accent:h.btnBorder,background:b===g?`${h.accent}14`:h.btnBg},children:g==="paste"?"Paste SQL":g==="upload"?"Upload files":"Local path"},g))}),b==="path"&&e.jsx(A,{label:"Path",t:h,children:e.jsx("input",{value:L,onChange:g=>{K(g.target.value),g.target.value.trim()&&X([])},placeholder:"./queries or ./legacy.sql",style:ze(h)})}),b==="upload"&&e.jsxs(A,{label:"Upload SQL files",t:h,children:[e.jsx("input",{type:"file",multiple:!0,accept:".sql,text/sql,text/plain",onChange:g=>void xt(g.target.files),style:ze(h)}),e.jsx("span",{style:{fontSize:11,color:h.textMuted,fontFamily:h.font},children:x.length>0?`${x.length} SQL file(s) ready`:"Choose one or more SQL files."})]}),b==="paste"&&e.jsx(A,{label:"Paste SQL",t:h,children:e.jsx("textarea",{value:_,onChange:g=>w(g.target.value),placeholder:`select ...; go
|
|
22
|
-
select ...`,style:{...ze(h),minHeight:t?86:150,resize:"vertical",fontFamily:h.fontMono}})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(A,{label:"Domain",t:h,children:e.jsx("input",{value:H,onChange:g=>re(g.target.value),placeholder:"auto",style:ze(h)})}),e.jsx(A,{label:"Owner",t:h,children:e.jsx("input",{value:$,onChange:g=>G(g.target.value),placeholder:"analytics",style:ze(h)})})]}),e.jsx("button",{onClick:()=>void _e(),disabled:N||!Je,style:{...Te(h),padding:"8px 12px",opacity:N||!Je?.65:1,cursor:N||!Je?"not-allowed":"pointer"},children:N?Qr(Ce):"Generate DQL drafts"}),e.jsx("div",{style:{fontSize:11,color:h.textMuted,fontFamily:h.font,lineHeight:1.45},children:"Uses dbt, MetricFlow, warehouse catalog, and existing DQL context when available."})]}):e.jsxs("button",{onClick:()=>we(!0),style:{...Z(h),display:"grid",gap:4,textAlign:"left",width:"100%",justifyItems:"start"},children:[e.jsx("span",{style:{fontSize:11,color:h.textSecondary},children:b==="paste"?"Pasted SQL":b==="upload"?"Uploaded files":"Local path"}),e.jsx("span",{style:{maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:h.textMuted,fontFamily:h.fontMono},children:(t==null?void 0:t.inputPath)??(b==="paste"?"pasted.sql":b==="upload"?`${x.length} file(s)`:L||"./queries")})]})]}),e.jsx("section",{style:{minHeight:0,overflow:"auto",padding:12,display:"grid",alignContent:"start",gap:10},children:t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"grid",gap:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:12,fontWeight:800,color:h.textPrimary,fontFamily:h.font},children:"Drafts"}),e.jsx(Be,{label:`${t.candidates.length}`,tone:"info",t:h}),le.ready>0&&e.jsx(Be,{label:`${le.ready} ready`,tone:"ok",t:h}),le.attention>0&&e.jsx(Be,{label:`${le.attention} attention`,tone:"warn",t:h})]}),t.candidates.length>6&&e.jsx("input",{value:fe,onChange:g=>De(g.target.value),placeholder:"Search drafts, tables, files...",style:ze(h)})]}),qe.map(g=>{var v,B,R,O,We,Ee,wt,Ct;const T=g.id===(de==null?void 0:de.id),D=g.warnings??g.lineage.warnings,C=ke[g.id],U=((B=(v=g.preview)==null?void 0:v.result)==null?void 0:B.rowCount)??((We=(O=(R=g.preview)==null?void 0:R.result)==null?void 0:O.rows)==null?void 0:We.length),ne=M[g.id]??lt(g);return e.jsxs("button",{onClick:()=>{I(g.id)},style:{border:`1px solid ${T?h.accent:C?"#f8514955":h.headerBorder}`,borderRadius:8,background:T?`${h.accent}10`:h.appBg,color:h.textPrimary,padding:10,display:"grid",gap:6,textAlign:"left",cursor:"pointer",minWidth:0},children:[e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{minWidth:0,flex:1,fontSize:12,fontWeight:800,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.name}),e.jsx(Be,{label:Ur(ne.status),tone:Kr(ne.status),t:h})]}),e.jsxs("span",{style:{fontSize:10,color:h.textMuted,fontFamily:h.fontMono,overflowWrap:"anywhere"},children:[g.lineage.statementIndex,"/",g.lineage.totalStatements," · ",g.sourcePath]}),e.jsxs("span",{style:{display:"flex",gap:5,flexWrap:"wrap"},children:[e.jsx(Be,{label:((Ee=g.draftSave)==null?void 0:Ee.status)==="saved"||Ft(g.savedPath)?"draft saved":g.reviewStatus,tone:g.reviewStatus==="rejected"?"warn":"info",t:h}),e.jsx(Be,{label:((wt=g.validation)==null?void 0:wt.valid)===!1?"fix":"valid",tone:((Ct=g.validation)==null?void 0:Ct.valid)===!1?"warn":"ok",t:h}),typeof U=="number"&&e.jsx(Be,{label:`${U} rows`,tone:"ok",t:h}),D.length>0&&e.jsx(Be,{label:`${D.length} warning`,tone:"warn",t:h})]}),(C||ne.message)&&e.jsx("span",{style:{fontSize:11,color:C?"#f85149":h.textMuted,lineHeight:1.35,overflowWrap:"anywhere"},children:C??ne.message})]},g.id)}),!ge&&!fe.trim()&&se.length>10&&e.jsxs("button",{onClick:()=>Ae(!0),style:Z(h),children:["Show all ",se.length," drafts"]}),!t.candidates.some(en)&&le.ready>0&&e.jsx("button",{onClick:()=>void gt(),disabled:V,style:Te(h),children:V?"Saving...":"Save valid blocks"})]}):e.jsx("div",{style:{fontSize:12,color:h.textMuted,lineHeight:1.5},children:"Paste SQL, upload files, or choose a local path. Analysis stays in this session until you save a block."})}),e.jsxs("details",{open:Pe,onToggle:g=>z(g.currentTarget.open),style:{borderTop:`1px solid ${h.headerBorder}`,padding:12,display:"grid",gap:8},children:[e.jsxs("summary",{style:{cursor:"pointer",color:h.textSecondary,fontSize:11,fontWeight:800,fontFamily:h.font},children:["Import history",n.length>0?` (${n.length})`:""]}),e.jsxs("div",{style:{display:"grid",gap:8,marginTop:8},children:[e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:()=>void a(),style:Z(h),children:"Refresh"}),n.length>0&&e.jsx("button",{onClick:()=>void dt(),style:Z(h),children:"Clear"})]}),s?e.jsx("div",{style:{fontSize:12,color:h.textMuted},children:"Loading..."}):n.length===0?e.jsx("div",{style:{fontSize:12,color:h.textMuted},children:"No saved import sessions."}):e.jsx("div",{style:{display:"grid",gap:6,maxHeight:140,overflow:"auto"},children:n.slice(0,6).map(g=>e.jsxs("div",{style:{border:`1px solid ${(t==null?void 0:t.id)===g.id?h.accent:h.btnBorder}`,borderRadius:8,background:(t==null?void 0:t.id)===g.id?`${h.accent}10`:h.btnBg,display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",overflow:"hidden"},children:[e.jsxs("button",{onClick:()=>void tt(g.id),style:{background:"transparent",border:"none",color:h.textSecondary,cursor:"pointer",fontFamily:h.font,padding:"8px 9px",textAlign:"left",display:"grid",gap:3,minWidth:0},children:[e.jsxs("span",{style:{fontSize:11},children:[g.candidateCount," drafts · ",g.savedCount," certified"]}),e.jsx("span",{style:{fontSize:10,color:h.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.inputPath})]}),e.jsx("button",{onClick:()=>void at(g.id),title:"Delete local import session",style:{background:"transparent",border:"none",borderLeft:`1px solid ${h.headerBorder}`,color:h.textMuted,cursor:"pointer",fontFamily:h.font,padding:"0 8px",fontSize:11,fontWeight:700},children:"Delete"})]},g.id))})]})]})]}),e.jsxs("main",{style:{minWidth:0,minHeight:0,overflow:"auto",padding:20,background:h.appBg},children:[te&&e.jsx("div",{role:"alert",style:{padding:"10px 12px",color:"#f85149",background:"#f8514914",border:"1px solid #f8514933",borderRadius:8,marginBottom:12,fontSize:12},children:te}),!t||!de?e.jsx(Xr,{t:h}):e.jsx(Yr,{session:t,candidate:de,loading:N,onCandidateUpdated:Re,onRun:mt,onSave:Ge,onReject:Ve,onReviewInEditor:p,runError:ke[de.id]??null,themeMode:l,t:h})]})]}),pe&&e.jsx(Vr,{t:h,busy:N,title:pe.kind==="all"?"Clear import history?":"Delete import preview?",message:pe.kind==="all"?`This removes ${n.length} local import preview${n.length===1?"":"s"} from .dql/imports. Saved blocks stay in the project.`:"This removes the selected local import preview from .dql/imports. Saved blocks stay in the project.",confirmLabel:pe.kind==="all"?"Clear history":"Delete preview",onCancel:()=>Se(null),onConfirm:()=>void ht()})]})}function Vr({title:t,message:n,confirmLabel:s,busy:r,onCancel:o,onConfirm:a,t:p}){return e.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0, 0, 0, 0.22)",display:"flex",alignItems:"center",justifyContent:"center",padding:20,zIndex:20},children:e.jsxs("div",{style:{width:"min(420px, 92vw)",background:p.cellBg,color:p.textPrimary,border:`1px solid ${p.headerBorder}`,borderRadius:8,boxShadow:"0 18px 48px rgba(0, 0, 0, 0.30)",padding:16,display:"grid",gap:12},children:[e.jsx("div",{style:{fontSize:15,fontWeight:800,fontFamily:p.font},children:t}),e.jsx("div",{style:{fontSize:12,color:p.textMuted,lineHeight:1.5,fontFamily:p.font},children:n}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{onClick:o,disabled:r,style:Z(p),children:"Cancel"}),e.jsx("button",{onClick:a,disabled:r,style:{...Te(p),opacity:r?.65:1},children:r?"Working...":s})]})]})})}function Yr({session:t,candidate:n,loading:s,onCandidateUpdated:r,onRun:o,onSave:a,onReject:p,onReviewInEditor:m,runError:f,themeMode:E,t:l}){var et,_e,tt,at,dt,ht,Re,mt,Ge,gt,Ve,xt,g,T,D,C,U,ne;const[h,k]=c.useState(n.name),[b,P]=c.useState(n.domain),[L,K]=c.useState(n.owner),[_,w]=c.useState(n.description),[x,X]=c.useState(n.tags.join(", ")),[H,re]=c.useState((n.terms??[]).join(", ")),[$,G]=c.useState(n.pattern??""),[J,I]=c.useState(n.grain??""),[N,q]=c.useState((n.entities??[]).join(", ")),[V,ve]=c.useState((n.outputs??[]).join(", ")),[te,Q]=c.useState((n.dimensions??[]).join(", ")),[pe,Se]=c.useState((n.allowedFilters??[]).join(", ")),[Pe,z]=c.useState((n.sourceSystems??[]).join(", ")),[Y,we]=c.useState((n.replacementFor??[]).join(", ")),[fe,De]=c.useState(n.reviewCadence??"monthly"),[ge,Ae]=c.useState(n.sql),[ke,Ie]=c.useState(null),[Ce,u]=c.useState(null),[M,ee]=c.useState(!1);c.useEffect(()=>{k(n.name),P(n.domain),K(n.owner),w(n.description),X(n.tags.join(", ")),re((n.terms??[]).join(", ")),G(n.pattern??""),I(n.grain??""),q((n.entities??[]).join(", ")),ve((n.outputs??[]).join(", ")),Q((n.dimensions??[]).join(", ")),Se((n.allowedFilters??[]).join(", ")),z((n.sourceSystems??[]).join(", ")),we((n.replacementFor??[]).join(", ")),De(n.reviewCadence??"monthly"),Ae(n.sql),u(null),ee(!1)},[n.id,n.name,n.domain,n.owner,n.description,n.tags,n.terms,n.pattern,n.grain,n.entities,n.outputs,n.dimensions,n.allowedFilters,n.sourceSystems,n.replacementFor,n.reviewCadence,n.sql]);const de=async()=>{u(null);try{const v={name:h,domain:b,owner:L,description:_,tags:x.split(",").map(R=>R.trim()).filter(Boolean),terms:H.split(",").map(R=>R.trim()).filter(Boolean),pattern:$,grain:J,entities:N.split(",").map(R=>R.trim()).filter(Boolean),outputs:V.split(",").map(R=>R.trim()).filter(Boolean),dimensions:te.split(",").map(R=>R.trim()).filter(Boolean),allowedFilters:pe.split(",").map(R=>R.trim()).filter(Boolean),sourceSystems:Pe.split(",").map(R=>R.trim()).filter(Boolean),replacementFor:Y.split(",").map(R=>R.trim()).filter(Boolean),reviewCadence:fe,sql:ge,llmContext:n.llmContext},B=en(n)?await W.updateDqlGenerationCandidate(t.id,n.id,v):await W.updateBlockStudioImportCandidate(t.id,n.id,v);r(B)}catch(v){u((v==null?void 0:v.message)??"Could not update candidate.")}},se=async v=>{Ie(v),u(null);try{const B=await W.assistBlockStudioImportCandidate(t.id,n.id,v);r(B)}catch(B){u((B==null?void 0:B.message)??"AI assist failed.")}finally{Ie(null)}},qe=n.warnings??n.lineage.warnings,oe=ze(l),le=((_e=(et=n.preview)==null?void 0:et.result)==null?void 0:_e.rowCount)??((dt=(at=(tt=n.preview)==null?void 0:tt.result)==null?void 0:at.rows)==null?void 0:dt.length),Ne=((ht=n.draftSave)==null?void 0:ht.path)??(Ft(n.savedPath)?n.savedPath:void 0),ae=n.recommendedAction==="reuse_existing"||((Re=n.draftSave)==null?void 0:Re.status)==="skipped",Je=n.lineage.sourceTables.length+(((mt=n.evidence)==null?void 0:mt.length)??0)+n.lineage.parameters.length+qe.length;return e.jsxs("div",{style:{display:"grid",gap:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10,flexWrap:"wrap"},children:[e.jsxs("div",{style:{minWidth:0,flex:1},children:[e.jsx("div",{style:{fontSize:18,fontWeight:800,color:l.textPrimary},children:n.name}),e.jsxs("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.fontMono,marginTop:3},children:[n.sourcePath," · statement ",n.lineage.statementIndex,"/",n.lineage.totalStatements]})]}),e.jsx("button",{onClick:()=>void o(n),disabled:s,style:Z(l),children:s?"Running...":"Preview"}),e.jsx("button",{onClick:()=>ee(v=>!v),style:M?Te(l):Z(l),children:M?"Hide context":`Show context${Je>0?` (${Je})`:""}`}),e.jsx("button",{onClick:()=>m(n),style:Te(l),children:"Edit full DQL"}),e.jsx("button",{onClick:()=>void a(n),disabled:s||n.reviewStatus==="saved"||ae,style:Te(l),children:ae?"Reuse existing":n.reviewStatus==="saved"?"Certified":"Save block"})]}),Ce&&e.jsx("div",{role:"alert",style:{fontSize:12,color:"#f85149",background:"#f8514914",borderRadius:8,padding:10},children:Ce}),f&&e.jsxs("div",{role:"alert",style:{fontSize:12,color:"#f85149",background:"#f8514914",border:"1px solid #f8514933",borderRadius:8,padding:10,lineHeight:1.45,overflowWrap:"anywhere"},children:["Preview failed: ",f]}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[e.jsx(Be,{label:((Ge=n.draftSave)==null?void 0:Ge.status)==="skipped"?"reuse recommended":((gt=n.draftSave)==null?void 0:gt.status)==="saved"||Ne?"draft saved":n.reviewStatus,tone:n.reviewStatus==="rejected"?"warn":((Ve=n.draftSave)==null?void 0:Ve.status)==="skipped"?"ok":"info",t:l}),e.jsx(Be,{label:`${Math.round(n.confidence*100)}% confidence`,tone:"info",t:l}),e.jsx(Be,{label:((xt=n.validation)==null?void 0:xt.valid)===!1?"needs fixes":"valid",tone:((g=n.validation)==null?void 0:g.valid)===!1?"warn":"ok",t:l}),typeof le=="number"&&e.jsx(Be,{label:`${le} rows`,tone:"ok",t:l})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:M?"minmax(0, 1fr) minmax(320px, 380px)":"minmax(0, 1fr)",gap:12,alignItems:"start"},children:[e.jsxs("div",{style:{display:"grid",gap:12},children:[e.jsxs(be,{title:"Review details",t:l,children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(A,{label:"Name",t:l,children:e.jsx("input",{value:h,onChange:v=>k(v.target.value),style:oe})}),e.jsx(A,{label:"Domain",t:l,children:e.jsx("input",{value:b,onChange:v=>P(v.target.value),style:oe})}),e.jsx(A,{label:"Owner",t:l,children:e.jsx("input",{value:L,onChange:v=>K(v.target.value),style:oe})}),e.jsx(A,{label:"Tags",t:l,children:e.jsx("textarea",{value:x,onChange:v=>X(v.target.value),style:{...oe,minHeight:58,resize:"vertical"}})})]}),e.jsx(A,{label:"Business description",t:l,children:e.jsx("textarea",{value:_,onChange:v=>w(v.target.value),style:{...oe,minHeight:70,resize:"vertical"}})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:8},children:[e.jsx(A,{label:"Pattern",t:l,children:e.jsx("select",{value:$,onChange:v=>G(v.target.value),style:oe,children:["custom","metric_wrapper","entity_profile","entity_rollup","ranking","trend","bridge","drilldown","replacement"].map(v=>e.jsx("option",{value:v,children:v},v))})}),e.jsx(A,{label:"Grain",t:l,children:e.jsx("input",{value:J,onChange:v=>I(v.target.value),style:oe})}),e.jsx(A,{label:"Review cadence",t:l,children:e.jsx("select",{value:fe,onChange:v=>De(v.target.value),style:oe,children:["weekly","monthly","quarterly","semiannual","annual"].map(v=>e.jsx("option",{value:v,children:v},v))})})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(A,{label:"Entities",t:l,children:e.jsx("input",{value:N,onChange:v=>q(v.target.value),style:oe})}),e.jsx(A,{label:"Outputs",t:l,children:e.jsx("input",{value:V,onChange:v=>ve(v.target.value),style:oe})}),e.jsx(A,{label:"Dimensions",t:l,children:e.jsx("input",{value:te,onChange:v=>Q(v.target.value),style:oe})}),e.jsx(A,{label:"Allowed filters",t:l,children:e.jsx("input",{value:pe,onChange:v=>Se(v.target.value),style:oe})}),e.jsx(A,{label:"Source systems",t:l,children:e.jsx("input",{value:Pe,onChange:v=>z(v.target.value),style:oe})}),e.jsx(A,{label:"Terms",t:l,children:e.jsx("input",{value:H,onChange:v=>re(v.target.value),style:oe})})]}),e.jsx(A,{label:"Replaces",t:l,children:e.jsx("input",{value:Y,onChange:v=>we(v.target.value),style:oe})}),e.jsx("button",{onClick:()=>void de(),style:{...Te(l),justifySelf:"start"},children:"Apply edits"})]}),n.preview&&e.jsxs(be,{title:"Preview Results",t:l,children:[e.jsxs("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.45},children:["Query ran successfully",typeof le=="number"?` and returned ${le} rows`:"","."]}),e.jsx("div",{style:{maxHeight:320,overflow:"auto",border:`1px solid ${l.headerBorder}`,borderRadius:8},children:e.jsx(Oi,{result:n.preview.result,themeMode:E})})]}),e.jsxs("details",{style:Rt(l),children:[e.jsx("summary",{style:Et(l),children:"Original SQL"}),e.jsx("textarea",{value:ge,onChange:v=>Ae(v.target.value),style:{...oe,minHeight:210,fontFamily:l.fontMono,resize:"vertical",marginTop:10}})]}),e.jsxs("details",{style:Rt(l),children:[e.jsx("summary",{style:Et(l),children:"Draft DQL block"}),e.jsx("pre",{style:{margin:"10px 0 0",whiteSpace:"pre-wrap",fontSize:11,lineHeight:1.45,color:l.textSecondary,fontFamily:l.fontMono},children:n.dqlSource})]})]}),M&&e.jsxs("div",{style:{display:"grid",gap:12},children:[(((T=n.similarityMatches)==null?void 0:T.length)||((D=n.draftSave)==null?void 0:D.status)==="skipped")&&e.jsx(be,{title:"Reuse recommendation",t:l,children:e.jsxs("div",{style:{display:"grid",gap:8},children:[e.jsx(St,{label:"Action",value:n.recommendedAction??"create_new",t:l}),((C=n.draftSave)==null?void 0:C.reason)&&e.jsx("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.4},children:n.draftSave.reason}),(n.similarityMatches??[]).slice(0,3).map((v,B)=>e.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:7,padding:8,background:l.appBg},children:[e.jsx("div",{style:{fontSize:11,fontWeight:800,color:l.textSecondary,overflowWrap:"anywhere"},children:v.name}),e.jsxs("div",{style:{fontSize:10,color:l.textMuted,marginTop:3},children:[v.kind," · ",Math.round(v.score*100),"% · ",v.recommendedAction]}),e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:v.reason})]},`${v.objectKey??v.name}-${B}`))]})}),(((U=n.parameterDecisions)==null?void 0:U.length)||((ne=n.filterBindings)==null?void 0:ne.length))&&e.jsx(be,{title:"Parameter contract",t:l,children:e.jsxs("div",{style:{display:"grid",gap:8},children:[(n.parameterDecisions??[]).slice(0,8).map(v=>e.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:7,padding:8,background:l.appBg},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:11,fontWeight:800,color:l.textSecondary},children:v.name}),e.jsx("span",{style:{fontSize:10,color:l.textMuted},children:v.policy})]}),e.jsxs("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:[v.sourceExpression," = ",String(v.value)]}),e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:v.reason})]},v.name)),(n.filterBindings??[]).length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:(n.filterBindings??[]).map(v=>e.jsx(Be,{label:`${v.filter} -> ${v.binding}`,tone:"info",t:l},v.filter))})]})}),e.jsxs(be,{title:"Grounding",t:l,children:[e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{fontSize:10,color:l.textMuted,textTransform:"uppercase",fontWeight:800},children:"Source tables"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:n.lineage.sourceTables.length?n.lineage.sourceTables.map(v=>e.jsx(Be,{label:v,tone:"info",t:l},v)):e.jsx("span",{style:{fontSize:12,color:l.textMuted},children:"None detected"})})]}),(n.evidence??[]).length>0&&e.jsxs("div",{style:{display:"grid",gap:6},children:[e.jsx("div",{style:{fontSize:10,color:l.textMuted,textTransform:"uppercase",fontWeight:800},children:"Context used"}),(n.evidence??[]).slice(0,5).map((v,B)=>e.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:7,padding:8,background:l.appBg},children:[e.jsx("div",{style:{fontSize:11,fontWeight:800,color:l.textSecondary,overflowWrap:"anywhere"},children:v.name}),e.jsxs("div",{style:{fontSize:10,color:l.textMuted,marginTop:3},children:[v.kind,v.reason?` · ${v.reason}`:""]}),v.description&&e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:v.description})]},`${v.objectKey??v.name}-${B}`))]}),e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{fontSize:10,color:l.textMuted,textTransform:"uppercase",fontWeight:800},children:"Parameters"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:n.lineage.parameters.length?n.lineage.parameters.map(v=>e.jsx(Be,{label:v,tone:"warn",t:l},v)):e.jsx("span",{style:{fontSize:12,color:l.textMuted},children:"None detected"})})]}),qe.length>0&&e.jsxs("div",{style:{display:"grid",gap:6},children:[e.jsx("div",{style:{fontSize:10,color:"#d29922",textTransform:"uppercase",fontWeight:800},children:"Warnings"}),qe.map((v,B)=>e.jsx("div",{style:{fontSize:12,color:"#d29922",lineHeight:1.4},children:v},B))]})]}),e.jsxs("details",{style:Rt(l),children:[e.jsx("summary",{style:Et(l),children:"Generation audit"}),e.jsxs("div",{style:{display:"grid",gap:8,marginTop:10},children:[e.jsx(St,{label:"Method",value:n.generationMode==="ai"?`AI-assisted local generation (${n.generationProvider??"configured provider"})`:"Deterministic local generation",t:l}),Ne&&e.jsx(St,{label:"Draft path",value:Ne,t:l}),e.jsx(St,{label:"Default test",value:"assert row_count > 0",t:l}),e.jsx(St,{label:"Split strategy",value:n.splitStrategy??"semicolon-go",t:l}),n.llmContext&&e.jsx(St,{label:"Agent use",value:n.llmContext,t:l}),(n.conversionNotes??[]).map((v,B)=>e.jsx("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.4},children:v},B))]})]}),e.jsxs("details",{style:Rt(l),children:[e.jsx("summary",{style:Et(l),children:"AI refine tools"}),e.jsxs("div",{style:{display:"grid",gap:10,marginTop:10},children:[e.jsx("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.45},children:"Use these only when the generated draft needs a targeted improvement before certification."}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[["explain","Explain"],["fix-validation","Fix validation"],["infer-chart","Infer chart"],["propose-tests","Propose tests"]].map(([v,B])=>e.jsx("button",{onClick:()=>void se(v),disabled:!!ke,style:Z(l),children:ke===v?"Working...":B},v))}),(n.aiAssistance??[]).length>0&&e.jsx("div",{style:{display:"grid",gap:8},children:(n.aiAssistance??[]).slice().reverse().map((v,B)=>e.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:8,padding:9,background:l.appBg},children:[e.jsxs("div",{style:{fontSize:10,color:l.textMuted,fontWeight:800,textTransform:"uppercase"},children:[v.action," · ",v.status]}),e.jsx("div",{style:{fontSize:12,color:l.textSecondary,lineHeight:1.45,marginTop:5},children:v.summary})]},`${v.createdAt}-${B}`))})]})]}),e.jsx("button",{onClick:()=>void p(n),disabled:n.reviewStatus==="rejected",style:{...Z(l),justifySelf:"start"},children:n.reviewStatus==="rejected"?"Rejected":"Reject draft"})]})]})]})}function xn({index:t,active:n,complete:s,title:r,detail:o,t:a}){const p=s?"#2ea043":n?a.accent:a.textMuted;return e.jsxs("div",{style:{border:`1px solid ${n?a.accent:a.headerBorder}`,borderRadius:8,padding:"9px 10px",display:"grid",gridTemplateColumns:"24px minmax(0, 1fr)",gap:8,alignItems:"center",background:n?`${a.accent}10`:a.cellBg},children:[e.jsx("span",{style:{width:22,height:22,borderRadius:999,display:"inline-grid",placeItems:"center",background:`${p}18`,color:p,fontSize:11,fontWeight:800,fontFamily:a.font},children:s?"✓":t}),e.jsxs("span",{style:{minWidth:0},children:[e.jsx("span",{style:{display:"block",fontSize:12,fontWeight:700,color:a.textPrimary,fontFamily:a.font},children:r}),e.jsx("span",{style:{display:"block",fontSize:10,color:a.textMuted,fontFamily:a.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o})]})]})}function Xr({t}){const n=[["1","Add SQL","Paste SQL, upload files, or point to an enterprise SQL folder."],["2","Generate drafts","DQL analyzes statements, project metadata, tables, and business context."],["3","Review and certify","Preview results, edit metadata, then certify the governed block."]];return e.jsxs("div",{style:{display:"grid",gap:12},children:[e.jsx(jt,{message:"Add SQL to analyze DQL candidates without creating block files."}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:10},children:n.map(([s,r,o])=>e.jsxs("div",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.appBg,padding:12,display:"grid",gap:6},children:[e.jsx("span",{style:{width:22,height:22,borderRadius:999,display:"inline-grid",placeItems:"center",background:`${t.accent}18`,color:t.accent,fontSize:11,fontWeight:800,fontFamily:t.font},children:s}),e.jsx("span",{style:{fontSize:12,fontWeight:700,color:t.textPrimary,fontFamily:t.font},children:r}),e.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.4},children:o})]},r))})]})}function A({label:t,children:n,t:s}){return e.jsxs("label",{style:{display:"grid",gap:5},children:[e.jsx("span",{style:{fontSize:10,fontWeight:700,color:s.textMuted,letterSpacing:"0.05em",textTransform:"uppercase",fontFamily:s.font},children:t}),n]})}function be({title:t,hint:n,children:s,t:r}){return e.jsxs("section",{style:{display:"grid",gridTemplateColumns:"176px minmax(0, 1fr)",gap:24,padding:"18px 0",borderBottom:"1px solid var(--border-subtle)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:650,color:r.textPrimary,fontFamily:r.font},children:t}),n?e.jsx("div",{style:{fontSize:11,color:r.textMuted,lineHeight:1.45,marginTop:3,fontFamily:r.font},children:n}):null]}),e.jsx("div",{style:{minWidth:0,display:"grid",gap:10,alignContent:"start"},children:s})]})}function St({label:t,value:n,t:s}){return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"110px minmax(0, 1fr)",gap:8,fontSize:12,fontFamily:s.font},children:[e.jsx("span",{style:{color:s.textMuted},children:t}),e.jsx("span",{title:n,style:{color:s.textSecondary,overflowWrap:"anywhere"},children:n})]})}function Be({label:t,tone:n,t:s}){const r=n==="ok"?"#2ea043":n==="warn"?"#d29922":s.accent;return e.jsx("span",{style:{fontSize:10,fontWeight:700,color:r,background:`${r}18`,borderRadius:999,padding:"3px 7px",fontFamily:s.font,textTransform:"uppercase"},children:t})}function Rt(t){return{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:12,color:t.textPrimary,fontFamily:t.font}}function Et(t){return{cursor:"pointer",color:t.textSecondary,fontSize:11,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em",fontFamily:t.font}}function ze(t){return{background:t.inputBg,border:`1px solid ${t.inputBorder}`,borderRadius:6,color:t.textPrimary,fontSize:12,fontFamily:t.font,padding:"8px 10px",outline:"none",minWidth:0}}function jn(t){return{...ze(t),boxSizing:"border-box",fontSize:11.5,minHeight:32,padding:"6px 8px"}}function Z(t){return{background:t.btnBg,border:`1px solid ${t.btnBorder}`,borderRadius:6,color:t.textSecondary,cursor:"pointer",fontSize:11,fontFamily:t.font,padding:"6px 10px"}}function Te(t){return{...Z(t),background:`${t.accent}18`,border:`1px solid ${t.accent}`,color:t.accent,fontWeight:700}}function Zr({blockName:t,loading:n,detail:s,graph:r,paths:o,onSelectNode:a,onOpenInspector:p,t:m}){if(!t)return e.jsx(jt,{message:"Lineage will appear once the block has a name."});if(n)return e.jsx(jt,{message:"Loading block lineage…"});if(!(s!=null&&s.node))return e.jsxs("div",{style:{padding:12,display:"grid",gap:12},children:[e.jsx("div",{style:{fontSize:12,color:m.textMuted,fontFamily:m.font},children:"No lineage node was found for this block yet. Save the block to compile and refresh its focused lineage automatically."}),e.jsx("div",{children:e.jsx("button",{onClick:p,style:{background:m.btnBg,border:`1px solid ${m.btnBorder}`,borderRadius:6,color:m.textPrimary,cursor:"pointer",fontSize:11,fontFamily:m.font,padding:"6px 10px"},children:"Open Focused Lineage"})})]});const f=`block:${t}`;return e.jsxs("div",{style:{padding:12,display:"grid",gap:12,overflowY:"auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:12,fontWeight:700,color:m.textPrimary,fontFamily:m.font},children:s.node.name}),e.jsx("div",{style:{fontSize:11,color:m.textMuted,fontFamily:m.font},children:s.node.domain?`Domain: ${s.node.domain}`:"Block lineage focus"})]}),e.jsx("div",{style:{flex:1}}),e.jsx("button",{onClick:p,style:{background:m.btnBg,border:`1px solid ${m.btnBorder}`,borderRadius:6,color:m.textPrimary,cursor:"pointer",fontSize:11,fontFamily:m.font,padding:"6px 10px"},children:"Open Focused Lineage"})]}),(o==null?void 0:o.layerSummary)&&e.jsx(rr,{layerSummary:o.layerSummary,t:m}),r&&r.nodes.length>0&&e.jsx(pr,{nodes:r.nodes,edges:r.edges,focalNodeId:f,height:360,onNodeClick:a,layoutMode:"flow"}),o&&(o.upstreamPaths.length>0||o.downstreamPaths.length>0)&&e.jsxs("div",{style:{display:"grid",gap:10},children:[o.upstreamPaths.length>0&&e.jsx(ji,{title:"Source to Block",paths:o.upstreamPaths,onNodeClick:a,focalNodeId:f,t:m}),o.downstreamPaths.length>0&&e.jsx(ji,{title:"Block to Consumption",paths:o.downstreamPaths,onNodeClick:a,focalNodeId:f,t:m})]})]})}function Jr({metadata:t,draftMetadata:n,onChange:s,t:r}){const o={width:"100%",background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:12,fontFamily:r.font,padding:"8px 10px",outline:"none"},a={name:(n==null?void 0:n.name)||(t==null?void 0:t.name)||"",domain:(n==null?void 0:n.domain)||(t==null?void 0:t.domain)||"uncategorized",folderPath:(t==null?void 0:t.folderPath)||"",description:(n==null?void 0:n.description)||(t==null?void 0:t.description)||"",owner:(n==null?void 0:n.owner)||(t==null?void 0:t.owner)||"",tags:(n==null?void 0:n.tags)||(t==null?void 0:t.tags)||[]};return e.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[e.jsx("input",{value:a.name,onChange:p=>s({name:p.target.value}),placeholder:"Block name",style:o}),e.jsx("input",{value:a.domain,onChange:p=>s({domain:p.target.value}),placeholder:"Domain",style:o}),e.jsx("input",{value:a.folderPath,onChange:p=>s({folderPath:p.target.value}),placeholder:"Folder (optional), e.g. executive/monthly",style:{...o,fontFamily:r.fontMono}}),e.jsx("input",{value:a.owner,onChange:p=>s({owner:p.target.value}),placeholder:"Owner",style:o}),e.jsx("input",{value:a.description,onChange:p=>s({description:p.target.value}),placeholder:"Description",style:o}),e.jsx(Fi,{values:a.tags,onChange:p=>s({tags:p}),placeholder:"Tags",style:o})]})}function es({parameters:t,values:n,onChange:s,onReset:r,onRun:o,running:a,t:p}){return t.length===0?e.jsx(jt,{message:"This block has no runtime parameters. Add typed params in DQL Source when scope should be configurable."}):e.jsxs("div",{style:{padding:14,display:"grid",gap:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontSize:13,fontWeight:800,color:p.textPrimary},children:"Test parameter values"}),e.jsx("div",{style:{fontSize:11,color:p.textMuted,marginTop:3},children:"These values affect only the preview. Save defaults in the block definition."})]}),e.jsx("button",{type:"button",onClick:o,disabled:a,style:Te(p),children:a?"Running…":"Run preview"})]}),e.jsx(hr,{parameters:t,values:n,onChange:s,onReset:r,t:p,includeNonRuntime:!0,card:!0})]})}function ts({values:t,t:n}){return e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:t.map(s=>e.jsxs("span",{style:{fontSize:10,color:n.textSecondary,background:n.appBg,border:`1px solid ${n.cellBorder}`,borderRadius:999,padding:"4px 7px"},children:[s.name," = ",Array.isArray(s.value)?s.value.join(", "):String(s.value)," ",e.jsxs("span",{style:{color:n.textMuted},children:["(",s.source,")"]})]},s.name))})}function jt({message:t}){const n=qt[Ot(s=>s.themeMode)];return e.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:t})}function ns({elapsedMs:t}){const n=qt[Ot(s=>s.themeMode)];return e.jsx("div",{style:{padding:12},children:e.jsxs("div",{style:{display:"grid",gap:8,border:`1px solid ${n.headerBorder}`,borderRadius:8,background:n.cellBg,padding:12,color:n.textPrimary,fontFamily:n.font},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:700},children:[e.jsx(Ze,{size:16,strokeWidth:2,color:n.accent,"aria-hidden":"true"}),e.jsx("span",{children:"Running preview"}),e.jsx("span",{style:{marginLeft:"auto",color:n.textMuted,fontSize:11,fontWeight:500},children:os(t)})]}),e.jsx("div",{style:{color:n.textMuted,fontSize:12,lineHeight:1.45},children:"Executing the block query against the active connection."})]})})}function Ii(t){if(!(t instanceof Jo)||!t.details||typeof t.details!="object"||Array.isArray(t.details))return null;const n=t.details.technicalDetails;return typeof n=="string"&&n.trim()?n:null}function is({message:t,technicalDetails:n,repairing:s,onFix:r,onEdit:o}){const a=qt[Ot(p=>p.themeMode)];return e.jsx("div",{style:{padding:12},children:e.jsxs("div",{style:{display:"grid",gap:8,border:"1px solid rgba(248, 81, 73, 0.35)",borderRadius:8,background:"rgba(248, 81, 73, 0.08)",color:a.textPrimary,fontFamily:a.font,padding:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:700,color:"#f85149"},children:[e.jsx(ft,{size:16,strokeWidth:2,"aria-hidden":"true"}),e.jsx("span",{children:"Preview failed"})]}),e.jsx("div",{style:{color:a.textPrimary,fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t}),e.jsx("div",{style:{color:a.textMuted,fontSize:11.5,lineHeight:1.45},children:"Correct the named field or runtime problem, then run the same draft again. Nothing was saved or certified."}),e.jsxs("div",{style:{display:"flex",gap:7,flexWrap:"wrap"},children:[e.jsxs("button",{type:"button",onClick:r,disabled:s,style:{...Te(a),display:"inline-flex",alignItems:"center",gap:6,opacity:s?.72:1},children:[s?e.jsx(Ze,{size:13,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):e.jsx(Lt,{size:13}),s?"Fixing & running…":"Fix with AI & run"]}),e.jsx("button",{type:"button",onClick:o,style:Z(a),children:"Edit DQL"})]}),n&&n!==t&&e.jsxs("details",{style:{borderTop:`1px solid ${a.headerBorder}`,paddingTop:7},children:[e.jsx("summary",{style:{cursor:"pointer",color:a.textMuted,fontSize:10.5,fontWeight:700},children:"Technical details"}),e.jsx("pre",{style:{margin:"7px 0 0",maxHeight:180,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",color:a.textMuted,fontSize:10,lineHeight:1.4,fontFamily:a.fontMono},children:n})]})]})})}function os(t){const n=Math.max(0,Math.floor(t/1e3));if(n<60)return`${n}s`;const s=Math.floor(n/60),r=n%60;return`${s}m ${r}s`}const Mi={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},rs={draft:[],review:["draft"],certified:["deprecated"],deprecated:["draft"]};function ss({currentStatus:t,blockPath:n,onStatusChanged:s,t:r}){const[o,a]=c.useState(!1),p=rs[t]??[],m=async f=>{if(n){a(!0);try{const E=await W.updateBlockStatus(n,f);E.ok&&E.status&&s(E.status)}finally{a(!1)}}};return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",background:r.pillBg,borderRadius:8},children:[e.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"Status:"}),e.jsx("span",{style:{fontSize:11,fontWeight:600,color:Mi[t]??r.textMuted,background:`${Mi[t]??r.textMuted}18`,padding:"2px 8px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:r.font},children:t}),e.jsx("span",{style:{flex:1}}),p.map(f=>e.jsx("button",{onClick:()=>void m(f),disabled:o,style:{background:f==="certified"?"#3fb950":f==="deprecated"?"#f85149":r.btnBg,border:`1px solid ${f==="certified"?"#3fb950":f==="deprecated"?"#f85149":r.btnBorder}`,borderRadius:4,color:f==="certified"||f==="deprecated"?"#fff":r.textSecondary,cursor:o?"not-allowed":"pointer",fontSize:10,fontWeight:600,fontFamily:r.font,padding:"3px 10px",textTransform:"capitalize",opacity:o?.5:1},children:o?"...":f==="certified"?"Certify":f==="deprecated"?"Deprecate":`Move to ${f}`},f))]})}function ls({result:t,t:n,repairing:s,onEditSource:r,onEditParameters:o,onReviewMetrics:a,onRun:p,onFix:m}){var P,L,K,_,w;const f=t.checklist,E=!!((P=f==null?void 0:f.issues)!=null&&P.some(x=>x.code==="tests_failed")||f!=null&&f.blockers.some(x=>/tests? must pass|test failed/i.test(x))),l=f?[["Metadata",f.metadata,!0],["Validation",f.validation,!0],["Run",f.run,!0],["Tests",f.tests,E],["Chart",f.chart,!1],["Lineage",f.lineage,!1]]:[],h=Array.from(new Set(((L=t.blockers)!=null&&L.length?t.blockers:(f==null?void 0:f.blockers)??[]).map(as))),k=(K=f==null?void 0:f.issues)!=null&&K.length?f.issues:h.map(x=>({severity:"error",code:"certification_blocker",title:"Certification requirement is not ready",message:x,correction:"Update the block, run it again, and retry certification.",action:x==="The query must run successfully."?"run_again":"edit_source"})),b=t.pending?n.accent:t.ok?"#3fb950":"#d29922";return e.jsxs("div",{style:{margin:"12px 12px 0",border:`1px solid ${b}55`,borderRadius:8,background:`${b}0d`,padding:12,display:"grid",gap:10},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:12,fontWeight:800,color:b,fontFamily:n.font},children:t.pending?"Certification running":t.ok?"Block certified":"Unable to certify"}),(f==null?void 0:f.checkedAt)&&e.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:f.checkedAt})]}),e.jsx("div",{style:{fontSize:12,color:n.textMuted,lineHeight:1.45},children:t.pending?t.message??"The exact draft is saved and the certification gates are running in the background.":t.ok?f!=null&&f.tests?"Latest edits were saved, the block ran successfully, tests passed, and status was updated to certified.":"Latest edits were saved, the block ran successfully, no block tests are defined, and status was updated to certified.":`The draft is saved. Certification stopped with ${k.length||1} required fix${k.length===1?"":"es"}; nothing was partially certified.`}),t.pending&&e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{height:5,borderRadius:999,background:n.headerBorder,overflow:"hidden"},children:e.jsx("div",{style:{height:"100%",width:`${Math.max(4,Math.min(100,t.progress??4))}%`,borderRadius:999,background:n.accent,transition:"width 180ms ease"}})}),e.jsxs("div",{style:{fontSize:10.5,color:n.textMuted,display:"flex",justifyContent:"space-between"},children:[e.jsx("span",{children:t.phase?t.phase.replace(/_/g," "):"queued"}),e.jsxs("span",{children:[Math.round(t.progress??0),"%"]})]})]}),l.length>0&&e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:l.map(([x,X,H])=>e.jsxs("span",{title:!X&&!H?`${x} is optional for local certification.`:void 0,style:{fontSize:11,fontWeight:700,color:X?"#3fb950":H?"#d29922":n.textMuted,background:X?"#3fb95018":H?"#d2992218":n.pillBg,borderRadius:999,padding:"4px 8px"},children:[X?"✓":H?"!":"○"," ",x,!X&&!H?" · optional":""]},x))}),t.error&&k.length===0&&e.jsx("div",{style:{fontSize:12,color:"#f85149"},children:t.error}),!t.pending&&!t.ok&&k.length>0&&e.jsxs("div",{style:{display:"grid",gap:8},children:[e.jsxs("div",{style:{fontSize:10,color:"#d29922",textTransform:"uppercase",fontWeight:800},children:["Fixes before certification · ",k.length]}),k.map((x,X)=>{var $;const H=x.action==="review_metrics"?"Review metrics":x.action==="run_again"?"Run block":x.action==="edit_parameters"?"Edit run inputs":x.action==="configure_runtime"?"Review runtime":"Edit source",re=x.action==="review_metrics"||x.action==="configure_runtime"?a:x.action==="run_again"?p:x.action==="edit_parameters"?o:r;return e.jsxs("div",{style:{display:"grid",gap:7,border:`1px solid ${b}44`,borderRadius:8,background:n.cellBg,padding:10},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[e.jsx(ft,{size:14,color:b,style:{marginTop:1,flexShrink:0}}),e.jsxs("div",{style:{minWidth:0},children:[e.jsxs("div",{style:{display:"flex",gap:7,alignItems:"baseline",flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:12,fontWeight:800,color:n.textPrimary},children:x.title??"Certification requirement is not ready"}),x.field&&e.jsx("span",{style:{fontSize:10,color:n.textMuted},children:x.field})]}),((($=x.references)==null?void 0:$.length)??0)>0&&e.jsx("div",{style:{display:"flex",gap:5,flexWrap:"wrap",marginTop:5},children:x.references.map(G=>e.jsx("code",{style:{fontSize:10,color:n.accent,background:n.pillBg,borderRadius:4,padding:"2px 5px"},children:G},G))})]})]}),e.jsx("div",{style:{fontSize:11.5,lineHeight:1.45,color:n.textSecondary},children:x.message}),x.correction&&e.jsxs("div",{style:{fontSize:11.5,lineHeight:1.45,color:n.textPrimary},children:[e.jsx("strong",{children:"How to fix:"})," ",x.correction]}),e.jsxs("div",{style:{display:"flex",gap:7,flexWrap:"wrap"},children:[e.jsx("button",{type:"button",onClick:re,style:Z(n),children:H}),x.technicalDetails&&e.jsx("button",{type:"button",onClick:()=>m(x),disabled:s,style:Z(n),children:s?"Fixing…":"Fix with AI & run"})]}),x.technicalDetails&&x.technicalDetails!==x.message&&e.jsxs("details",{children:[e.jsx("summary",{style:{cursor:"pointer",color:n.textMuted,fontSize:10.5,fontWeight:700},children:"Technical details"}),e.jsx("pre",{style:{margin:"6px 0 0",maxHeight:160,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",color:n.textMuted,fontSize:10,lineHeight:1.4,fontFamily:n.fontMono},children:x.technicalDetails})]})]},`${x.code??x.message}-${X}`)})]}),(((w=(_=t.certification)==null?void 0:_.warnings)==null?void 0:w.length)??0)>0&&e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{fontSize:10,color:n.textMuted,textTransform:"uppercase",fontWeight:800},children:"Warnings"}),t.certification.warnings.map(x=>e.jsxs("div",{style:{fontSize:12,color:n.textMuted},children:[x.rule,": ",x.message]},`${x.rule}-${x.message}`))]})]})}function as(t){const n=t.trim(),s=n.toLowerCase();return s==="missing owner"||s==="block has owner: missing owner"?"Owner is required.":s==="missing domain"||s==="block has domain: missing domain"?"Domain is required.":s==="missing description"||s==="block has description: missing description"?"Description is required.":s==="block has not run successfully"?"The query must run successfully.":s==="tests must pass before certification"||s.startsWith("all tests pass:")?"Tests must pass.":s==="at least one test assertion is required before certification"||s.startsWith("block has tests:")?"Add at least one test assertion.":s==="visualization config is missing"?"Choose a visualization.":n}function ds({entries:t,t:n}){return t.length===0?e.jsx(jt,{message:"No version history available. Commit changes to build history."}):e.jsxs("div",{style:{padding:12,display:"grid",gap:8},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:"Version History"}),t.map(s=>e.jsxs("div",{style:{padding:"8px 12px",border:`1px solid ${n.cellBorder}`,borderRadius:8,background:n.inputBg},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[e.jsx("span",{style:{fontSize:10,fontFamily:n.fontMono,color:n.accent,background:`${n.accent}12`,padding:"1px 6px",borderRadius:4},children:s.hash.slice(0,7)}),e.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:new Date(s.date).toLocaleDateString()}),e.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,marginLeft:"auto"},children:s.author})]}),e.jsx("div",{style:{fontSize:12,color:n.textPrimary,fontFamily:n.font},children:s.message})]},s.hash))]})}function cs(t,n){const s=t.match(/query\s*=\s*"""([\s\S]*?)"""/i);return s?t.replace(s[0],`query = """${s[1].trimEnd()}
|
|
15
|
+
GROUP BY 1`}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsx("button",{type:"button",onClick:p,disabled:!l.trim(),style:{display:"inline-flex",alignItems:"center",gap:6,height:28,padding:"0 12px",borderRadius:8,border:`1px solid ${m.accent}`,background:"var(--accent-dim)",color:m.accent,fontSize:11.5,fontWeight:650,cursor:l.trim()?"pointer":"not-allowed",fontFamily:m.font,opacity:l.trim()?1:.6},children:"Convert to DQL script"}),e.jsxs("span",{style:{fontSize:10.5,color:m.textMuted,fontFamily:m.font},children:["Detects ",e.jsx("span",{style:{fontFamily:m.fontMono},children:"${params}"})," and grounds tables against dbt. Open the DQL Source editor for the full script."]})]})]}),e.jsxs(be,{title:"Chart intent",hint:"How apps and answers render this block by default.",t:m,children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:10},children:[e.jsx(A,{label:"Type",t:m,children:e.jsxs("select",{value:r.chart??"table",onChange:w=>o(Ke(t,{...r,chart:w.target.value})),style:f,children:[e.jsx("option",{value:"table",children:"Table"}),Oi.map(w=>e.jsx("option",{value:w.value,children:w.label},w.value))]})}),e.jsx(A,{label:"X axis",t:m,children:e.jsxs("select",{value:r.x??"",onChange:w=>o(Ke(t,{...r,x:w.target.value})),style:f,children:[e.jsx("option",{value:"",children:"Auto"}),k.map(w=>e.jsx("option",{value:w,children:Xe(w)},w))]})}),e.jsx(A,{label:"Y axis",t:m,children:e.jsxs("select",{value:r.y??"",onChange:w=>o(Ke(t,{...r,y:w.target.value})),style:f,children:[e.jsx("option",{value:"",children:"Auto"}),k.map(w=>e.jsx("option",{value:w,children:Xe(w)},w))]})}),e.jsx(A,{label:"Series / color",t:m,children:e.jsxs("select",{value:r.color??"",onChange:w=>o(Ke(t,{...r,color:w.target.value})),style:f,children:[e.jsx("option",{value:"",children:"None"}),k.map(w=>e.jsx("option",{value:w,children:Xe(w)},w))]})})]}),e.jsx(A,{label:"Title",t:m,children:e.jsx("input",{value:r.title??"",onChange:w=>o(Ke(t,{...r,title:w.target.value})),style:f})})]}),e.jsx(be,{title:"Business outputs",hint:"What consumers see when this block answers a question.",t:m,children:e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:k.length>0?k.map(w=>e.jsx("span",{style:Wt(m,!0),children:Xe(w)},w)):e.jsx("span",{style:{fontSize:11,color:m.textMuted},children:"Add aliases in DQL Source to expose business-friendly output names."})})}),e.jsx(Qi,{source:t,kind:"custom",onChange:o,t:m}),e.jsx(be,{title:"Tests",hint:"Assertions checked on every run and required for certification.",t:m,children:e.jsx(_t,{multiline:!0,value:b,onChange:w=>o(_i(t,"tests",w)),placeholder:`assert row_count >= 1
|
|
16
|
+
assert revenue >= 0`,style:{...f,minHeight:64,resize:"vertical",fontFamily:m.fontMono}})}),e.jsxs("details",{style:{padding:"14px 0",color:m.textSecondary,fontFamily:m.font},children:[e.jsx("summary",{style:{cursor:"pointer",fontSize:11,fontWeight:750},children:"Generated DQL preview"}),e.jsx("pre",{style:{maxHeight:240,overflow:"auto",margin:"10px 0 0",whiteSpace:"pre-wrap",color:m.textSecondary,fontSize:11,lineHeight:1.45,fontFamily:m.fontMono,border:"1px solid var(--border-subtle)",background:"var(--bg-2)",borderRadius:9,padding:"12px 14px"},children:t})]})]})})}function Fr({semanticChoice:t,databaseWarning:n,onDismiss:s,onInsertAdvanced:r,onCreateSemantic:o,t:a}){const p=t?`${t.kind==="metric"?"Metric":"Dimension"} "${t.name}" belongs in a Semantic Block. SQL Blocks can still use advanced @metric/@dim refs when you choose that explicitly.`:n??"";return e.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${a.headerBorder}`,background:`${a.accent}10`,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:12,color:a.textSecondary,lineHeight:1.4,flex:1,minWidth:260},children:p}),t&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:o,style:Z(a),children:"Create Semantic Block"}),e.jsx("button",{onClick:r,style:Te(a),children:"Insert advanced ref"})]}),e.jsx("button",{onClick:s,style:Z(a),children:"Dismiss"})]})}function Sn(t){var s,r,o,a,p;const n=((r=(s=t.preview)==null?void 0:s.result)==null?void 0:r.rowCount)??((p=(a=(o=t.preview)==null?void 0:o.result)==null?void 0:a.rows)==null?void 0:p.length);return typeof n=="number"?n:void 0}function Ft(t){return t?t.startsWith("blocks/_drafts/")||/^domains\/[^/]+\/blocks\/_drafts\//.test(t):!1}function lt(t){var n,s,r,o,a;return t.reviewStatus==="saved"?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"saved",rows:Sn(t),message:"Block saved."}:((n=t.validation)==null?void 0:n.valid)===!1?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"needs_attention",message:((s=t.validation.diagnostics.find(p=>p.severity==="error"))==null?void 0:s.message)??"DQL validation needs attention."}:t.preview?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"ready",rows:Sn(t),savedPath:t.savedPath,message:Ft(t.savedPath)?"Preview ran successfully. Draft is saved for review.":"Preview ran successfully. Nothing is written until you save."}:((r=t.draftSave)==null?void 0:r.status)==="saved"||Ft(t.savedPath)?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"ready",savedPath:((o=t.draftSave)==null?void 0:o.path)??t.savedPath,message:"Draft saved. Run preview, then certify when ready."}:((a=t.draftSave)==null?void 0:a.status)==="error"?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"needs_attention",message:t.draftSave.error??"Draft preparation failed."}:{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"queued",message:"Ready to process."}}function Or(t){return t==="retrieving"?"Checking certified blocks and semantic metrics.":t==="reviewing"?"Reviewing governed evidence and building the candidate.":t==="ready"?"Analysis ready. Preparing preview.":t==="needs_attention"?"Analysis needs attention.":"Queued for governed retrieval."}async function qr(t,n){for(let s=0;s<240;s+=1){const r=await W.getDqlGenerationSession(t);if(n(r),r.candidates.every(o=>o.analysisStatus==="ready"||o.analysisStatus==="needs_attention"))return r;await new Promise(o=>window.setTimeout(o,500))}throw new Error("Import analysis is still running. You can leave this workspace and resume the session later.")}async function Nr(t,n,s){let r=0;const o=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;r<t.length;){const a=r;r+=1,await s(t[a])}});await Promise.all(o)}function en(t){return!!(t.generationMode||t.draftSave||Ft(t.savedPath))}function Hr(t){return t==="creating"?"Reading SQL":t==="running"?"Running previews":t==="saving"?"Saving blocks":t==="complete"?"Import complete":"Ready"}function Qr(t){return t==="needs_attention"?"needs attention":t.replace("_"," ")}function Ur(t){return t==="saved"||t==="ready"?"ok":t==="needs_attention"?"warn":"info"}function Kr({session:t,sessions:n,sessionsLoading:s,onClose:r,onSessionChange:o,onRefreshSessions:a,onSelectCandidate:p,onSavedCandidate:m,defaultDomain:f,defaultOwner:E,themeMode:l,t:h,inline:k=!1}){const[b,P]=c.useState("paste"),[L,K]=c.useState(""),[_,w]=c.useState(""),[x,X]=c.useState([]),[H,re]=c.useState(f),[$,G]=c.useState(E),[J,I]=c.useState(null),[N,q]=c.useState(!1),[V,ve]=c.useState(!1),[te,Q]=c.useState(null),[pe,Se]=c.useState(null),[Pe,z]=c.useState(!1),[Y,we]=c.useState(!0),[fe,De]=c.useState(""),[ge,Ae]=c.useState(!1),[ke,Ie]=c.useState({}),[Ce,u]=c.useState("idle"),[M,ee]=c.useState({}),de=c.useMemo(()=>t?t.candidates.find(g=>g.id===J)??t.candidates[0]??null:null,[t,J]);c.useEffect(()=>{if(!(t!=null&&t.candidates.length)){I(null);return}(!J||!t.candidates.some(g=>g.id===J))&&I(t.candidates[0].id)},[t,J]),c.useEffect(()=>{Ie({})},[t==null?void 0:t.id]),c.useEffect(()=>{we(!(t!=null&&t.candidates.length))},[t==null?void 0:t.id,t==null?void 0:t.candidates.length]),c.useEffect(()=>{if(!t){ee({}),u("idle");return}ee(Object.fromEntries(t.candidates.map(g=>[g.id,lt(g)]))),u(g=>g==="idle"?"complete":g)},[t==null?void 0:t.id]);const se=c.useMemo(()=>{const g=fe.trim().toLowerCase(),T=(t==null?void 0:t.candidates)??[];return g?T.filter(D=>[D.name,D.domain,D.sourcePath,D.description,...D.lineage.sourceTables].some(C=>C.toLowerCase().includes(g))):T},[fe,t]),qe=ge||fe.trim()?se:se.slice(0,10),le=((t==null?void 0:t.candidates.map(g=>M[g.id]??lt(g)))??[]).reduce((g,T)=>(T.status==="saved"?g.saved+=1:T.status==="ready"?g.ready+=1:T.status==="needs_attention"?g.attention+=1:g.processing+=1,g),{saved:0,ready:0,attention:0,processing:0}),Ne=t?le.saved>0?3:2:1,ae=(t==null?void 0:t.candidates.filter(g=>{var T;return((T=g.validation)==null?void 0:T.valid)!==!1}).length)??0,Je=!!(b==="paste"?_.trim():b==="upload"?x.length>0:L.trim()),et=()=>b==="paste"?{inputMode:"paste",sourceKind:"raw-sql",domain:H,owner:$,sources:[{path:"pasted.sql",content:_}],async:!0,persistence:"session-only"}:b==="upload"?{inputMode:"upload",sourceKind:"raw-sql",domain:H,owner:$,sources:x,async:!0,persistence:"session-only"}:{path:L,inputMode:"path",sourceKind:"raw-sql",domain:H,owner:$,async:!0,persistence:"session-only"},_e=async()=>{var g,T,D;q(!0),ve(!0),Q(null),Ie({}),ee({}),u("creating");try{const C=await W.createDqlGenerationSession(et());let U=C,ne=Object.fromEntries(C.candidates.map(R=>[R.id,{...lt(R),status:"queued",message:"Queued for governed retrieval."}]));const v=(R,O)=>{ne={...ne,[R]:O(ne[R])},ee(ne)},B=R=>{U={...U,candidates:U.candidates.map(O=>O.id===R.id?R:O)},o(U)};o(U),I(((g=U.candidates[0])==null?void 0:g.id)??null),ee(ne),await a(),u("running"),U=await qr(C.id,R=>{U=R,o(R);for(const O of R.candidates)v(O.id,We=>({...We,name:O.name,sourcePath:O.sourcePath,status:O.analysisStatus==="needs_attention"?"needs_attention":O.analysisStatus==="ready"?"queued":"running",message:Or(O.analysisStatus)}))}),await Nr(U.candidates,2,async R=>{if(R.analysisStatus!=="needs_attention"){v(R.id,O=>({...O,status:"running",message:"Running preview."}));try{const O=await W.previewDqlGenerationCandidate(U.id,R.id);B(O),v(R.id,We=>{var Ee;return{...We,name:O.name,sourcePath:O.sourcePath,status:"ready",rows:Sn(O),savedPath:((Ee=O.draftSave)==null?void 0:Ee.path)??O.savedPath,message:O.recommendedAction==="reuse_existing"?"A governed block already answers this SQL. Reuse it instead of saving a duplicate.":"Preview ran successfully. Nothing is written until you save."}})}catch(O){const We=(O==null?void 0:O.message)??"Preview failed.";Ie(Ee=>({...Ee,[R.id]:We})),v(R.id,Ee=>({...Ee,status:"needs_attention",message:We}))}}}),o(U),I(((T=U.candidates.find(R=>R.reviewStatus!=="rejected"))==null?void 0:T.id)??((D=U.candidates[0])==null?void 0:D.id)??null),await a(),u("complete")}catch(C){Q((C==null?void 0:C.message)??"Import failed."),u("idle")}finally{q(!1),ve(!1)}},tt=async g=>{var T,D;q(!0),Q(null);try{const C=await W.getDqlGenerationSession(g).catch(()=>W.getBlockStudioImport(g));o(C),I(((T=C.candidates.find(U=>U.reviewStatus!=="saved"&&U.reviewStatus!=="rejected"))==null?void 0:T.id)??((D=C.candidates[0])==null?void 0:D.id)??null),Ie({}),u("complete")}catch(C){Q((C==null?void 0:C.message)??"Failed to resume import session.")}finally{q(!1)}},at=async g=>{Se({kind:"one",id:g})},dt=async()=>{n.length!==0&&Se({kind:"all"})},ht=async()=>{if(!pe)return;const g=pe;q(!0),Q(null);try{g.kind==="one"?await W.deleteBlockStudioImport(g.id):await W.clearBlockStudioImports(),(g.kind==="all"||(t==null?void 0:t.id)===g.id)&&(o(null),I(null)),Se(null),await a()}catch(T){Q((T==null?void 0:T.message)??"Failed to update import history.")}finally{q(!1)}},Re=g=>{t&&(o({...t,candidates:t.candidates.map(T=>T.id===g.id?g:T)}),ee(T=>({...T,[g.id]:lt(g)})))},mt=async g=>{if(t){q(!0),Q(null),Ie(T=>{if(!T[g.id])return T;const D={...T};return delete D[g.id],D});try{const T=en(g)?await W.previewDqlGenerationCandidate(t.id,g.id):await W.runBlockStudioImportCandidate(t.id,g.id);Re(T),I(T.id),Ie(D=>{if(!D[g.id])return D;const C={...D};return delete C[g.id],C})}catch(T){const D=(T==null?void 0:T.message)??"Candidate run failed.";Q(D),I(g.id),Ie(C=>({...C,[g.id]:D}))}finally{q(!1)}}},Ge=async g=>{if(!t)return;const T=g.owner.trim()||$.trim();if(!T){Q("Owner is required before a block can be saved or certified.");return}q(!0),Q(null);try{if(en(g)){const D=await W.saveSelectedDqlGenerationCandidates(t.id,{candidateIds:[g.id],owner:T});o(D.session);const C=D.results[0];if(!C||C.status==="error")throw new Error((C==null?void 0:C.error)??(C==null?void 0:C.blockers.join(" "))??"Candidate save failed.");C.candidate&&Re(C.candidate),C.candidate&&C.block&&m(C.candidate,C.block),C.status==="draft"&&C.blockers.length>0&&Q(`Saved as draft: ${C.blockers.join(" ")}`)}else{const D=await W.saveBlockStudioImportCandidate(t.id,g.id);Re(D.candidate),m(D.candidate,D.block)}await a()}catch(D){const C=(D==null?void 0:D.message)??"Candidate save failed.";Q(C.includes("409")||C.includes("already exists")?"A block with this name already exists. Rename this candidate, then save again.":C)}finally{q(!1)}},gt=async()=>{if(!t)return;const g=$.trim()||t.defaults.owner.trim();if(!g){Q("Owner is required before blocks can be saved or certified.");return}ve(!0),Q(null);try{const T=t.candidates.filter(B=>B.reviewStatus!=="rejected"&&B.analysisStatus!=="needs_attention").map(B=>B.id),D=await W.saveSelectedDqlGenerationCandidates(t.id,{candidateIds:T,owner:g});o(D.session);const C=new Map(D.results.filter(B=>B.status==="error").map(B=>[B.candidateId,B.error??B.blockers.join(" ")])),U=new Map(D.results.filter(B=>B.path).map(B=>[B.candidateId,B.path]));ee(Object.fromEntries(D.session.candidates.map(B=>{const R=C.get(B.id),O=U.get(B.id)??B.savedPath;return R?[B.id,{...lt(B),status:"needs_attention",message:R.includes("409")||R.includes("already exists")?"A block with this name already exists. Rename it in advanced details, then save again.":R}]:O||B.reviewStatus==="saved"?[B.id,{...lt(B),status:"saved",savedPath:O,message:"Block saved."}]:[B.id,lt(B)]}))),await a();const ne=D.results.filter(B=>B.status==="error").length,v=D.results.filter(B=>B.status==="draft").length;(ne>0||v>0)&&Q(`${D.results.length-ne} saved. ${v} stayed draft; ${ne} need attention.`)}catch(T){Q((T==null?void 0:T.message)??"Save all failed.")}finally{ve(!1)}},Ve=async g=>{if(!t)return;const T=await W.updateBlockStudioImportCandidate(t.id,g.id,{reviewStatus:"rejected"});Re(T),a()},xt=async g=>{const D=Array.from(g??[]).filter(U=>U.name.toLowerCase().endsWith(".sql")),C=await Promise.all(D.map(async U=>({path:U.name,content:await U.text()})));X(C),C.length>0&&K("")};return e.jsxs("div",{style:{position:"relative",height:"100%",display:"grid",gridTemplateRows:"80px minmax(0, 1fr)",minHeight:0,background:h.appBg,borderRadius:k?0:8},children:[e.jsxs("header",{style:{borderBottom:`1px solid ${h.headerBorder}`,background:h.cellBg,padding:"14px 14px 12px",display:"flex",alignItems:"center",gap:14,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,minWidth:260},children:[e.jsx("span",{style:{width:34,height:34,borderRadius:8,display:"inline-flex",alignItems:"center",justifyContent:"center",color:h.accent,background:`${h.accent}16`,flexShrink:0},children:e.jsx(Lt,{size:17,strokeWidth:2,"aria-hidden":"true"})}),e.jsxs("span",{style:{display:"grid",gap:2,minWidth:0},children:[e.jsx("span",{style:{fontSize:15,fontWeight:800,color:h.textPrimary,fontFamily:h.font},children:"Import SQL to DQL"}),e.jsx("span",{style:{fontSize:11,color:h.textMuted,fontFamily:h.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"SQL source to AI-grounded drafts to review and certify"})]})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(130px, 1fr))",gap:6,width:"min(560px, 44vw)",minWidth:390},children:[e.jsx(xn,{index:1,active:Ne===1,complete:!!t,title:"Source",detail:b==="paste"?"Paste SQL":b==="upload"?"Upload files":"Local path",t:h}),e.jsx(xn,{index:2,active:Ne===2,complete:le.ready>0||le.saved>0,title:"Draft",detail:t?`${t.candidates.length} blocks · ${ae} ready`:"Generate DQL",t:h}),e.jsx(xn,{index:3,active:Ne===3,complete:le.saved>0,title:"Review",detail:le.saved>0?`${le.saved} certified`:"Preview and certify",t:h})]}),e.jsx("div",{style:{flex:1}}),e.jsx("button",{onClick:r,title:"Close import","aria-label":"Close import",style:{...Z(h),width:32,height:32,padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e.jsx(vr,{size:15,strokeWidth:2,"aria-hidden":"true"})})]}),e.jsxs("div",{style:{minHeight:0,display:"grid",gridTemplateColumns:"300px minmax(0, 1fr)"},children:[e.jsxs("aside",{style:{borderRight:`1px solid ${h.headerBorder}`,display:"grid",gridTemplateRows:"auto minmax(0, 1fr) auto",minHeight:0,background:h.cellBg},children:[e.jsxs("section",{style:{borderBottom:`1px solid ${h.headerBorder}`,padding:12,display:"grid",gap:10},children:[e.jsxs("button",{onClick:()=>we(g=>!g),style:{background:"transparent",border:"none",color:h.textPrimary,cursor:"pointer",display:"flex",alignItems:"center",gap:8,padding:0,fontFamily:h.font,textAlign:"left"},children:[e.jsx(Hi,{size:14,strokeWidth:2,color:h.accent,"aria-hidden":"true"}),e.jsx("span",{style:{fontSize:12,fontWeight:800,flex:1},children:"Source"}),t&&e.jsx("span",{style:{fontSize:10,color:h.textMuted},children:Y?"Hide":"Edit"})]}),Y?e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:4},children:["paste","upload","path"].map(g=>e.jsx("button",{onClick:()=>P(g),style:{...Z(h),padding:"6px 4px",color:b===g?h.accent:h.textSecondary,borderColor:b===g?h.accent:h.btnBorder,background:b===g?`${h.accent}14`:h.btnBg},children:g==="paste"?"Paste SQL":g==="upload"?"Upload files":"Local path"},g))}),b==="path"&&e.jsx(A,{label:"Path",t:h,children:e.jsx("input",{value:L,onChange:g=>{K(g.target.value),g.target.value.trim()&&X([])},placeholder:"./queries or ./legacy.sql",style:ze(h)})}),b==="upload"&&e.jsxs(A,{label:"Upload SQL files",t:h,children:[e.jsx("input",{type:"file",multiple:!0,accept:".sql,text/sql,text/plain",onChange:g=>void xt(g.target.files),style:ze(h)}),e.jsx("span",{style:{fontSize:11,color:h.textMuted,fontFamily:h.font},children:x.length>0?`${x.length} SQL file(s) ready`:"Choose one or more SQL files."})]}),b==="paste"&&e.jsx(A,{label:"Paste SQL",t:h,children:e.jsx("textarea",{value:_,onChange:g=>w(g.target.value),placeholder:`select ...; go
|
|
17
|
+
select ...`,style:{...ze(h),minHeight:t?86:150,resize:"vertical",fontFamily:h.fontMono}})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(A,{label:"Domain",t:h,children:e.jsx("input",{value:H,onChange:g=>re(g.target.value),placeholder:"auto",style:ze(h)})}),e.jsx(A,{label:"Owner",t:h,children:e.jsx("input",{value:$,onChange:g=>G(g.target.value),placeholder:"analytics",style:ze(h)})})]}),e.jsx("button",{onClick:()=>void _e(),disabled:N||!Je,style:{...Te(h),padding:"8px 12px",opacity:N||!Je?.65:1,cursor:N||!Je?"not-allowed":"pointer"},children:N?Hr(Ce):"Generate DQL drafts"}),e.jsx("div",{style:{fontSize:11,color:h.textMuted,fontFamily:h.font,lineHeight:1.45},children:"Uses dbt, MetricFlow, warehouse catalog, and existing DQL context when available."})]}):e.jsxs("button",{onClick:()=>we(!0),style:{...Z(h),display:"grid",gap:4,textAlign:"left",width:"100%",justifyItems:"start"},children:[e.jsx("span",{style:{fontSize:11,color:h.textSecondary},children:b==="paste"?"Pasted SQL":b==="upload"?"Uploaded files":"Local path"}),e.jsx("span",{style:{maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:h.textMuted,fontFamily:h.fontMono},children:(t==null?void 0:t.inputPath)??(b==="paste"?"pasted.sql":b==="upload"?`${x.length} file(s)`:L||"./queries")})]})]}),e.jsx("section",{style:{minHeight:0,overflow:"auto",padding:12,display:"grid",alignContent:"start",gap:10},children:t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"grid",gap:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:12,fontWeight:800,color:h.textPrimary,fontFamily:h.font},children:"Drafts"}),e.jsx(Be,{label:`${t.candidates.length}`,tone:"info",t:h}),le.ready>0&&e.jsx(Be,{label:`${le.ready} ready`,tone:"ok",t:h}),le.attention>0&&e.jsx(Be,{label:`${le.attention} attention`,tone:"warn",t:h})]}),t.candidates.length>6&&e.jsx("input",{value:fe,onChange:g=>De(g.target.value),placeholder:"Search drafts, tables, files...",style:ze(h)})]}),qe.map(g=>{var v,B,R,O,We,Ee,wt,Ct;const T=g.id===(de==null?void 0:de.id),D=g.warnings??g.lineage.warnings,C=ke[g.id],U=((B=(v=g.preview)==null?void 0:v.result)==null?void 0:B.rowCount)??((We=(O=(R=g.preview)==null?void 0:R.result)==null?void 0:O.rows)==null?void 0:We.length),ne=M[g.id]??lt(g);return e.jsxs("button",{onClick:()=>{I(g.id)},style:{border:`1px solid ${T?h.accent:C?"#f8514955":h.headerBorder}`,borderRadius:8,background:T?`${h.accent}10`:h.appBg,color:h.textPrimary,padding:10,display:"grid",gap:6,textAlign:"left",cursor:"pointer",minWidth:0},children:[e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{minWidth:0,flex:1,fontSize:12,fontWeight:800,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.name}),e.jsx(Be,{label:Qr(ne.status),tone:Ur(ne.status),t:h})]}),e.jsxs("span",{style:{fontSize:10,color:h.textMuted,fontFamily:h.fontMono,overflowWrap:"anywhere"},children:[g.lineage.statementIndex,"/",g.lineage.totalStatements," · ",g.sourcePath]}),e.jsxs("span",{style:{display:"flex",gap:5,flexWrap:"wrap"},children:[e.jsx(Be,{label:((Ee=g.draftSave)==null?void 0:Ee.status)==="saved"||Ft(g.savedPath)?"draft saved":g.reviewStatus,tone:g.reviewStatus==="rejected"?"warn":"info",t:h}),e.jsx(Be,{label:((wt=g.validation)==null?void 0:wt.valid)===!1?"fix":"valid",tone:((Ct=g.validation)==null?void 0:Ct.valid)===!1?"warn":"ok",t:h}),typeof U=="number"&&e.jsx(Be,{label:`${U} rows`,tone:"ok",t:h}),D.length>0&&e.jsx(Be,{label:`${D.length} warning`,tone:"warn",t:h})]}),(C||ne.message)&&e.jsx("span",{style:{fontSize:11,color:C?"#f85149":h.textMuted,lineHeight:1.35,overflowWrap:"anywhere"},children:C??ne.message})]},g.id)}),!ge&&!fe.trim()&&se.length>10&&e.jsxs("button",{onClick:()=>Ae(!0),style:Z(h),children:["Show all ",se.length," drafts"]}),!t.candidates.some(en)&&le.ready>0&&e.jsx("button",{onClick:()=>void gt(),disabled:V,style:Te(h),children:V?"Saving...":"Save valid blocks"})]}):e.jsx("div",{style:{fontSize:12,color:h.textMuted,lineHeight:1.5},children:"Paste SQL, upload files, or choose a local path. Analysis stays in this session until you save a block."})}),e.jsxs("details",{open:Pe,onToggle:g=>z(g.currentTarget.open),style:{borderTop:`1px solid ${h.headerBorder}`,padding:12,display:"grid",gap:8},children:[e.jsxs("summary",{style:{cursor:"pointer",color:h.textSecondary,fontSize:11,fontWeight:800,fontFamily:h.font},children:["Import history",n.length>0?` (${n.length})`:""]}),e.jsxs("div",{style:{display:"grid",gap:8,marginTop:8},children:[e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:()=>void a(),style:Z(h),children:"Refresh"}),n.length>0&&e.jsx("button",{onClick:()=>void dt(),style:Z(h),children:"Clear"})]}),s?e.jsx("div",{style:{fontSize:12,color:h.textMuted},children:"Loading..."}):n.length===0?e.jsx("div",{style:{fontSize:12,color:h.textMuted},children:"No saved import sessions."}):e.jsx("div",{style:{display:"grid",gap:6,maxHeight:140,overflow:"auto"},children:n.slice(0,6).map(g=>e.jsxs("div",{style:{border:`1px solid ${(t==null?void 0:t.id)===g.id?h.accent:h.btnBorder}`,borderRadius:8,background:(t==null?void 0:t.id)===g.id?`${h.accent}10`:h.btnBg,display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",overflow:"hidden"},children:[e.jsxs("button",{onClick:()=>void tt(g.id),style:{background:"transparent",border:"none",color:h.textSecondary,cursor:"pointer",fontFamily:h.font,padding:"8px 9px",textAlign:"left",display:"grid",gap:3,minWidth:0},children:[e.jsxs("span",{style:{fontSize:11},children:[g.candidateCount," drafts · ",g.savedCount," certified"]}),e.jsx("span",{style:{fontSize:10,color:h.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.inputPath})]}),e.jsx("button",{onClick:()=>void at(g.id),title:"Delete local import session",style:{background:"transparent",border:"none",borderLeft:`1px solid ${h.headerBorder}`,color:h.textMuted,cursor:"pointer",fontFamily:h.font,padding:"0 8px",fontSize:11,fontWeight:700},children:"Delete"})]},g.id))})]})]})]}),e.jsxs("main",{style:{minWidth:0,minHeight:0,overflow:"auto",padding:20,background:h.appBg},children:[te&&e.jsx("div",{role:"alert",style:{padding:"10px 12px",color:"#f85149",background:"#f8514914",border:"1px solid #f8514933",borderRadius:8,marginBottom:12,fontSize:12},children:te}),!t||!de?e.jsx(Yr,{t:h}):e.jsx(Vr,{session:t,candidate:de,loading:N,onCandidateUpdated:Re,onRun:mt,onSave:Ge,onReject:Ve,onReviewInEditor:p,runError:ke[de.id]??null,themeMode:l,t:h})]})]}),pe&&e.jsx(Gr,{t:h,busy:N,title:pe.kind==="all"?"Clear import history?":"Delete import preview?",message:pe.kind==="all"?`This removes ${n.length} local import preview${n.length===1?"":"s"} from .dql/imports. Saved blocks stay in the project.`:"This removes the selected local import preview from .dql/imports. Saved blocks stay in the project.",confirmLabel:pe.kind==="all"?"Clear history":"Delete preview",onCancel:()=>Se(null),onConfirm:()=>void ht()})]})}function Gr({title:t,message:n,confirmLabel:s,busy:r,onCancel:o,onConfirm:a,t:p}){return e.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0, 0, 0, 0.22)",display:"flex",alignItems:"center",justifyContent:"center",padding:20,zIndex:20},children:e.jsxs("div",{style:{width:"min(420px, 92vw)",background:p.cellBg,color:p.textPrimary,border:`1px solid ${p.headerBorder}`,borderRadius:8,boxShadow:"0 18px 48px rgba(0, 0, 0, 0.30)",padding:16,display:"grid",gap:12},children:[e.jsx("div",{style:{fontSize:15,fontWeight:800,fontFamily:p.font},children:t}),e.jsx("div",{style:{fontSize:12,color:p.textMuted,lineHeight:1.5,fontFamily:p.font},children:n}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{onClick:o,disabled:r,style:Z(p),children:"Cancel"}),e.jsx("button",{onClick:a,disabled:r,style:{...Te(p),opacity:r?.65:1},children:r?"Working...":s})]})]})})}function Vr({session:t,candidate:n,loading:s,onCandidateUpdated:r,onRun:o,onSave:a,onReject:p,onReviewInEditor:m,runError:f,themeMode:E,t:l}){var et,_e,tt,at,dt,ht,Re,mt,Ge,gt,Ve,xt,g,T,D,C,U,ne;const[h,k]=c.useState(n.name),[b,P]=c.useState(n.domain),[L,K]=c.useState(n.owner),[_,w]=c.useState(n.description),[x,X]=c.useState(n.tags.join(", ")),[H,re]=c.useState((n.terms??[]).join(", ")),[$,G]=c.useState(n.pattern??""),[J,I]=c.useState(n.grain??""),[N,q]=c.useState((n.entities??[]).join(", ")),[V,ve]=c.useState((n.outputs??[]).join(", ")),[te,Q]=c.useState((n.dimensions??[]).join(", ")),[pe,Se]=c.useState((n.allowedFilters??[]).join(", ")),[Pe,z]=c.useState((n.sourceSystems??[]).join(", ")),[Y,we]=c.useState((n.replacementFor??[]).join(", ")),[fe,De]=c.useState(n.reviewCadence??"monthly"),[ge,Ae]=c.useState(n.sql),[ke,Ie]=c.useState(null),[Ce,u]=c.useState(null),[M,ee]=c.useState(!1);c.useEffect(()=>{k(n.name),P(n.domain),K(n.owner),w(n.description),X(n.tags.join(", ")),re((n.terms??[]).join(", ")),G(n.pattern??""),I(n.grain??""),q((n.entities??[]).join(", ")),ve((n.outputs??[]).join(", ")),Q((n.dimensions??[]).join(", ")),Se((n.allowedFilters??[]).join(", ")),z((n.sourceSystems??[]).join(", ")),we((n.replacementFor??[]).join(", ")),De(n.reviewCadence??"monthly"),Ae(n.sql),u(null),ee(!1)},[n.id,n.name,n.domain,n.owner,n.description,n.tags,n.terms,n.pattern,n.grain,n.entities,n.outputs,n.dimensions,n.allowedFilters,n.sourceSystems,n.replacementFor,n.reviewCadence,n.sql]);const de=async()=>{u(null);try{const v={name:h,domain:b,owner:L,description:_,tags:x.split(",").map(R=>R.trim()).filter(Boolean),terms:H.split(",").map(R=>R.trim()).filter(Boolean),pattern:$,grain:J,entities:N.split(",").map(R=>R.trim()).filter(Boolean),outputs:V.split(",").map(R=>R.trim()).filter(Boolean),dimensions:te.split(",").map(R=>R.trim()).filter(Boolean),allowedFilters:pe.split(",").map(R=>R.trim()).filter(Boolean),sourceSystems:Pe.split(",").map(R=>R.trim()).filter(Boolean),replacementFor:Y.split(",").map(R=>R.trim()).filter(Boolean),reviewCadence:fe,sql:ge,llmContext:n.llmContext},B=en(n)?await W.updateDqlGenerationCandidate(t.id,n.id,v):await W.updateBlockStudioImportCandidate(t.id,n.id,v);r(B)}catch(v){u((v==null?void 0:v.message)??"Could not update candidate.")}},se=async v=>{Ie(v),u(null);try{const B=await W.assistBlockStudioImportCandidate(t.id,n.id,v);r(B)}catch(B){u((B==null?void 0:B.message)??"AI assist failed.")}finally{Ie(null)}},qe=n.warnings??n.lineage.warnings,oe=ze(l),le=((_e=(et=n.preview)==null?void 0:et.result)==null?void 0:_e.rowCount)??((dt=(at=(tt=n.preview)==null?void 0:tt.result)==null?void 0:at.rows)==null?void 0:dt.length),Ne=((ht=n.draftSave)==null?void 0:ht.path)??(Ft(n.savedPath)?n.savedPath:void 0),ae=n.recommendedAction==="reuse_existing"||((Re=n.draftSave)==null?void 0:Re.status)==="skipped",Je=n.lineage.sourceTables.length+(((mt=n.evidence)==null?void 0:mt.length)??0)+n.lineage.parameters.length+qe.length;return e.jsxs("div",{style:{display:"grid",gap:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10,flexWrap:"wrap"},children:[e.jsxs("div",{style:{minWidth:0,flex:1},children:[e.jsx("div",{style:{fontSize:18,fontWeight:800,color:l.textPrimary},children:n.name}),e.jsxs("div",{style:{fontSize:11,color:l.textMuted,fontFamily:l.fontMono,marginTop:3},children:[n.sourcePath," · statement ",n.lineage.statementIndex,"/",n.lineage.totalStatements]})]}),e.jsx("button",{onClick:()=>void o(n),disabled:s,style:Z(l),children:s?"Running...":"Preview"}),e.jsx("button",{onClick:()=>ee(v=>!v),style:M?Te(l):Z(l),children:M?"Hide context":`Show context${Je>0?` (${Je})`:""}`}),e.jsx("button",{onClick:()=>m(n),style:Te(l),children:"Edit full DQL"}),e.jsx("button",{onClick:()=>void a(n),disabled:s||n.reviewStatus==="saved"||ae,style:Te(l),children:ae?"Reuse existing":n.reviewStatus==="saved"?"Certified":"Save block"})]}),Ce&&e.jsx("div",{role:"alert",style:{fontSize:12,color:"#f85149",background:"#f8514914",borderRadius:8,padding:10},children:Ce}),f&&e.jsxs("div",{role:"alert",style:{fontSize:12,color:"#f85149",background:"#f8514914",border:"1px solid #f8514933",borderRadius:8,padding:10,lineHeight:1.45,overflowWrap:"anywhere"},children:["Preview failed: ",f]}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[e.jsx(Be,{label:((Ge=n.draftSave)==null?void 0:Ge.status)==="skipped"?"reuse recommended":((gt=n.draftSave)==null?void 0:gt.status)==="saved"||Ne?"draft saved":n.reviewStatus,tone:n.reviewStatus==="rejected"?"warn":((Ve=n.draftSave)==null?void 0:Ve.status)==="skipped"?"ok":"info",t:l}),e.jsx(Be,{label:`${Math.round(n.confidence*100)}% confidence`,tone:"info",t:l}),e.jsx(Be,{label:((xt=n.validation)==null?void 0:xt.valid)===!1?"needs fixes":"valid",tone:((g=n.validation)==null?void 0:g.valid)===!1?"warn":"ok",t:l}),typeof le=="number"&&e.jsx(Be,{label:`${le} rows`,tone:"ok",t:l})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:M?"minmax(0, 1fr) minmax(320px, 380px)":"minmax(0, 1fr)",gap:12,alignItems:"start"},children:[e.jsxs("div",{style:{display:"grid",gap:12},children:[e.jsxs(be,{title:"Review details",t:l,children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(A,{label:"Name",t:l,children:e.jsx("input",{value:h,onChange:v=>k(v.target.value),style:oe})}),e.jsx(A,{label:"Domain",t:l,children:e.jsx("input",{value:b,onChange:v=>P(v.target.value),style:oe})}),e.jsx(A,{label:"Owner",t:l,children:e.jsx("input",{value:L,onChange:v=>K(v.target.value),style:oe})}),e.jsx(A,{label:"Tags",t:l,children:e.jsx("textarea",{value:x,onChange:v=>X(v.target.value),style:{...oe,minHeight:58,resize:"vertical"}})})]}),e.jsx(A,{label:"Business description",t:l,children:e.jsx("textarea",{value:_,onChange:v=>w(v.target.value),style:{...oe,minHeight:70,resize:"vertical"}})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:8},children:[e.jsx(A,{label:"Pattern",t:l,children:e.jsx("select",{value:$,onChange:v=>G(v.target.value),style:oe,children:["custom","metric_wrapper","entity_profile","entity_rollup","ranking","trend","bridge","drilldown","replacement"].map(v=>e.jsx("option",{value:v,children:v},v))})}),e.jsx(A,{label:"Grain",t:l,children:e.jsx("input",{value:J,onChange:v=>I(v.target.value),style:oe})}),e.jsx(A,{label:"Review cadence",t:l,children:e.jsx("select",{value:fe,onChange:v=>De(v.target.value),style:oe,children:["weekly","monthly","quarterly","semiannual","annual"].map(v=>e.jsx("option",{value:v,children:v},v))})})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(A,{label:"Entities",t:l,children:e.jsx("input",{value:N,onChange:v=>q(v.target.value),style:oe})}),e.jsx(A,{label:"Outputs",t:l,children:e.jsx("input",{value:V,onChange:v=>ve(v.target.value),style:oe})}),e.jsx(A,{label:"Dimensions",t:l,children:e.jsx("input",{value:te,onChange:v=>Q(v.target.value),style:oe})}),e.jsx(A,{label:"Allowed filters",t:l,children:e.jsx("input",{value:pe,onChange:v=>Se(v.target.value),style:oe})}),e.jsx(A,{label:"Source systems",t:l,children:e.jsx("input",{value:Pe,onChange:v=>z(v.target.value),style:oe})}),e.jsx(A,{label:"Terms",t:l,children:e.jsx("input",{value:H,onChange:v=>re(v.target.value),style:oe})})]}),e.jsx(A,{label:"Replaces",t:l,children:e.jsx("input",{value:Y,onChange:v=>we(v.target.value),style:oe})}),e.jsx("button",{onClick:()=>void de(),style:{...Te(l),justifySelf:"start"},children:"Apply edits"})]}),n.preview&&e.jsxs(be,{title:"Preview Results",t:l,children:[e.jsxs("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.45},children:["Query ran successfully",typeof le=="number"?` and returned ${le} rows`:"","."]}),e.jsx("div",{style:{maxHeight:320,overflow:"auto",border:`1px solid ${l.headerBorder}`,borderRadius:8},children:e.jsx(Fi,{result:n.preview.result,themeMode:E})})]}),e.jsxs("details",{style:Rt(l),children:[e.jsx("summary",{style:Et(l),children:"Original SQL"}),e.jsx("textarea",{value:ge,onChange:v=>Ae(v.target.value),style:{...oe,minHeight:210,fontFamily:l.fontMono,resize:"vertical",marginTop:10}})]}),e.jsxs("details",{style:Rt(l),children:[e.jsx("summary",{style:Et(l),children:"Draft DQL block"}),e.jsx("pre",{style:{margin:"10px 0 0",whiteSpace:"pre-wrap",fontSize:11,lineHeight:1.45,color:l.textSecondary,fontFamily:l.fontMono},children:n.dqlSource})]})]}),M&&e.jsxs("div",{style:{display:"grid",gap:12},children:[(((T=n.similarityMatches)==null?void 0:T.length)||((D=n.draftSave)==null?void 0:D.status)==="skipped")&&e.jsx(be,{title:"Reuse recommendation",t:l,children:e.jsxs("div",{style:{display:"grid",gap:8},children:[e.jsx(St,{label:"Action",value:n.recommendedAction??"create_new",t:l}),((C=n.draftSave)==null?void 0:C.reason)&&e.jsx("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.4},children:n.draftSave.reason}),(n.similarityMatches??[]).slice(0,3).map((v,B)=>e.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:7,padding:8,background:l.appBg},children:[e.jsx("div",{style:{fontSize:11,fontWeight:800,color:l.textSecondary,overflowWrap:"anywhere"},children:v.name}),e.jsxs("div",{style:{fontSize:10,color:l.textMuted,marginTop:3},children:[v.kind," · ",Math.round(v.score*100),"% · ",v.recommendedAction]}),e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:v.reason})]},`${v.objectKey??v.name}-${B}`))]})}),(((U=n.parameterDecisions)==null?void 0:U.length)||((ne=n.filterBindings)==null?void 0:ne.length))&&e.jsx(be,{title:"Parameter contract",t:l,children:e.jsxs("div",{style:{display:"grid",gap:8},children:[(n.parameterDecisions??[]).slice(0,8).map(v=>e.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:7,padding:8,background:l.appBg},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:8},children:[e.jsx("span",{style:{fontSize:11,fontWeight:800,color:l.textSecondary},children:v.name}),e.jsx("span",{style:{fontSize:10,color:l.textMuted},children:v.policy})]}),e.jsxs("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:[v.sourceExpression," = ",String(v.value)]}),e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:v.reason})]},v.name)),(n.filterBindings??[]).length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:(n.filterBindings??[]).map(v=>e.jsx(Be,{label:`${v.filter} -> ${v.binding}`,tone:"info",t:l},v.filter))})]})}),e.jsxs(be,{title:"Grounding",t:l,children:[e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{fontSize:10,color:l.textMuted,textTransform:"uppercase",fontWeight:800},children:"Source tables"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:n.lineage.sourceTables.length?n.lineage.sourceTables.map(v=>e.jsx(Be,{label:v,tone:"info",t:l},v)):e.jsx("span",{style:{fontSize:12,color:l.textMuted},children:"None detected"})})]}),(n.evidence??[]).length>0&&e.jsxs("div",{style:{display:"grid",gap:6},children:[e.jsx("div",{style:{fontSize:10,color:l.textMuted,textTransform:"uppercase",fontWeight:800},children:"Context used"}),(n.evidence??[]).slice(0,5).map((v,B)=>e.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:7,padding:8,background:l.appBg},children:[e.jsx("div",{style:{fontSize:11,fontWeight:800,color:l.textSecondary,overflowWrap:"anywhere"},children:v.name}),e.jsxs("div",{style:{fontSize:10,color:l.textMuted,marginTop:3},children:[v.kind,v.reason?` · ${v.reason}`:""]}),v.description&&e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:v.description})]},`${v.objectKey??v.name}-${B}`))]}),e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{fontSize:10,color:l.textMuted,textTransform:"uppercase",fontWeight:800},children:"Parameters"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:n.lineage.parameters.length?n.lineage.parameters.map(v=>e.jsx(Be,{label:v,tone:"warn",t:l},v)):e.jsx("span",{style:{fontSize:12,color:l.textMuted},children:"None detected"})})]}),qe.length>0&&e.jsxs("div",{style:{display:"grid",gap:6},children:[e.jsx("div",{style:{fontSize:10,color:"#d29922",textTransform:"uppercase",fontWeight:800},children:"Warnings"}),qe.map((v,B)=>e.jsx("div",{style:{fontSize:12,color:"#d29922",lineHeight:1.4},children:v},B))]})]}),e.jsxs("details",{style:Rt(l),children:[e.jsx("summary",{style:Et(l),children:"Generation audit"}),e.jsxs("div",{style:{display:"grid",gap:8,marginTop:10},children:[e.jsx(St,{label:"Method",value:n.generationMode==="ai"?`AI-assisted local generation (${n.generationProvider??"configured provider"})`:"Deterministic local generation",t:l}),Ne&&e.jsx(St,{label:"Draft path",value:Ne,t:l}),e.jsx(St,{label:"Default test",value:"assert row_count > 0",t:l}),e.jsx(St,{label:"Split strategy",value:n.splitStrategy??"semicolon-go",t:l}),n.llmContext&&e.jsx(St,{label:"Agent use",value:n.llmContext,t:l}),(n.conversionNotes??[]).map((v,B)=>e.jsx("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.4},children:v},B))]})]}),e.jsxs("details",{style:Rt(l),children:[e.jsx("summary",{style:Et(l),children:"AI refine tools"}),e.jsxs("div",{style:{display:"grid",gap:10,marginTop:10},children:[e.jsx("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.45},children:"Use these only when the generated draft needs a targeted improvement before certification."}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[["explain","Explain"],["fix-validation","Fix validation"],["infer-chart","Infer chart"],["propose-tests","Propose tests"]].map(([v,B])=>e.jsx("button",{onClick:()=>void se(v),disabled:!!ke,style:Z(l),children:ke===v?"Working...":B},v))}),(n.aiAssistance??[]).length>0&&e.jsx("div",{style:{display:"grid",gap:8},children:(n.aiAssistance??[]).slice().reverse().map((v,B)=>e.jsxs("div",{style:{border:`1px solid ${l.headerBorder}`,borderRadius:8,padding:9,background:l.appBg},children:[e.jsxs("div",{style:{fontSize:10,color:l.textMuted,fontWeight:800,textTransform:"uppercase"},children:[v.action," · ",v.status]}),e.jsx("div",{style:{fontSize:12,color:l.textSecondary,lineHeight:1.45,marginTop:5},children:v.summary})]},`${v.createdAt}-${B}`))})]})]}),e.jsx("button",{onClick:()=>void p(n),disabled:n.reviewStatus==="rejected",style:{...Z(l),justifySelf:"start"},children:n.reviewStatus==="rejected"?"Rejected":"Reject draft"})]})]})]})}function xn({index:t,active:n,complete:s,title:r,detail:o,t:a}){const p=s?"#2ea043":n?a.accent:a.textMuted;return e.jsxs("div",{style:{border:`1px solid ${n?a.accent:a.headerBorder}`,borderRadius:8,padding:"9px 10px",display:"grid",gridTemplateColumns:"24px minmax(0, 1fr)",gap:8,alignItems:"center",background:n?`${a.accent}10`:a.cellBg},children:[e.jsx("span",{style:{width:22,height:22,borderRadius:999,display:"inline-grid",placeItems:"center",background:`${p}18`,color:p,fontSize:11,fontWeight:800,fontFamily:a.font},children:s?"✓":t}),e.jsxs("span",{style:{minWidth:0},children:[e.jsx("span",{style:{display:"block",fontSize:12,fontWeight:700,color:a.textPrimary,fontFamily:a.font},children:r}),e.jsx("span",{style:{display:"block",fontSize:10,color:a.textMuted,fontFamily:a.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o})]})]})}function Yr({t}){const n=[["1","Add SQL","Paste SQL, upload files, or point to an enterprise SQL folder."],["2","Generate drafts","DQL analyzes statements, project metadata, tables, and business context."],["3","Review and certify","Preview results, edit metadata, then certify the governed block."]];return e.jsxs("div",{style:{display:"grid",gap:12},children:[e.jsx(jt,{message:"Add SQL to analyze DQL candidates without creating block files."}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:10},children:n.map(([s,r,o])=>e.jsxs("div",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.appBg,padding:12,display:"grid",gap:6},children:[e.jsx("span",{style:{width:22,height:22,borderRadius:999,display:"inline-grid",placeItems:"center",background:`${t.accent}18`,color:t.accent,fontSize:11,fontWeight:800,fontFamily:t.font},children:s}),e.jsx("span",{style:{fontSize:12,fontWeight:700,color:t.textPrimary,fontFamily:t.font},children:r}),e.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.4},children:o})]},r))})]})}function A({label:t,children:n,t:s}){return e.jsxs("label",{style:{display:"grid",gap:5},children:[e.jsx("span",{style:{fontSize:10,fontWeight:700,color:s.textMuted,letterSpacing:"0.05em",textTransform:"uppercase",fontFamily:s.font},children:t}),n]})}function be({title:t,hint:n,children:s,t:r}){return e.jsxs("section",{style:{display:"grid",gridTemplateColumns:"176px minmax(0, 1fr)",gap:24,padding:"18px 0",borderBottom:"1px solid var(--border-subtle)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:650,color:r.textPrimary,fontFamily:r.font},children:t}),n?e.jsx("div",{style:{fontSize:11,color:r.textMuted,lineHeight:1.45,marginTop:3,fontFamily:r.font},children:n}):null]}),e.jsx("div",{style:{minWidth:0,display:"grid",gap:10,alignContent:"start"},children:s})]})}function St({label:t,value:n,t:s}){return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"110px minmax(0, 1fr)",gap:8,fontSize:12,fontFamily:s.font},children:[e.jsx("span",{style:{color:s.textMuted},children:t}),e.jsx("span",{title:n,style:{color:s.textSecondary,overflowWrap:"anywhere"},children:n})]})}function Be({label:t,tone:n,t:s}){const r=n==="ok"?"#2ea043":n==="warn"?"#d29922":s.accent;return e.jsx("span",{style:{fontSize:10,fontWeight:700,color:r,background:`${r}18`,borderRadius:999,padding:"3px 7px",fontFamily:s.font,textTransform:"uppercase"},children:t})}function Rt(t){return{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:12,color:t.textPrimary,fontFamily:t.font}}function Et(t){return{cursor:"pointer",color:t.textSecondary,fontSize:11,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em",fontFamily:t.font}}function ze(t){return{background:t.inputBg,border:`1px solid ${t.inputBorder}`,borderRadius:6,color:t.textPrimary,fontSize:12,fontFamily:t.font,padding:"8px 10px",outline:"none",minWidth:0}}function jn(t){return{...ze(t),boxSizing:"border-box",fontSize:11.5,minHeight:32,padding:"6px 8px"}}function Z(t){return{background:t.btnBg,border:`1px solid ${t.btnBorder}`,borderRadius:6,color:t.textSecondary,cursor:"pointer",fontSize:11,fontFamily:t.font,padding:"6px 10px"}}function Te(t){return{...Z(t),background:`${t.accent}18`,border:`1px solid ${t.accent}`,color:t.accent,fontWeight:700}}function Xr({blockName:t,loading:n,detail:s,graph:r,paths:o,onSelectNode:a,onOpenInspector:p,t:m}){if(!t)return e.jsx(jt,{message:"Lineage will appear once the block has a name."});if(n)return e.jsx(jt,{message:"Loading block lineage…"});if(!(s!=null&&s.node))return e.jsxs("div",{style:{padding:12,display:"grid",gap:12},children:[e.jsx("div",{style:{fontSize:12,color:m.textMuted,fontFamily:m.font},children:"No lineage node was found for this block yet. Save the block to compile and refresh its focused lineage automatically."}),e.jsx("div",{children:e.jsx("button",{onClick:p,style:{background:m.btnBg,border:`1px solid ${m.btnBorder}`,borderRadius:6,color:m.textPrimary,cursor:"pointer",fontSize:11,fontFamily:m.font,padding:"6px 10px"},children:"Open Focused Lineage"})})]});const f=`block:${t}`;return e.jsxs("div",{style:{padding:12,display:"grid",gap:12,overflowY:"auto"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:12,fontWeight:700,color:m.textPrimary,fontFamily:m.font},children:s.node.name}),e.jsx("div",{style:{fontSize:11,color:m.textMuted,fontFamily:m.font},children:s.node.domain?`Domain: ${s.node.domain}`:"Block lineage focus"})]}),e.jsx("div",{style:{flex:1}}),e.jsx("button",{onClick:p,style:{background:m.btnBg,border:`1px solid ${m.btnBorder}`,borderRadius:6,color:m.textPrimary,cursor:"pointer",fontSize:11,fontFamily:m.font,padding:"6px 10px"},children:"Open Focused Lineage"})]}),(o==null?void 0:o.layerSummary)&&e.jsx(rr,{layerSummary:o.layerSummary,t:m}),r&&r.nodes.length>0&&e.jsx(pr,{nodes:r.nodes,edges:r.edges,focalNodeId:f,height:360,onNodeClick:a,layoutMode:"flow"}),o&&(o.upstreamPaths.length>0||o.downstreamPaths.length>0)&&e.jsxs("div",{style:{display:"grid",gap:10},children:[o.upstreamPaths.length>0&&e.jsx(ji,{title:"Source to Block",paths:o.upstreamPaths,onNodeClick:a,focalNodeId:f,t:m}),o.downstreamPaths.length>0&&e.jsx(ji,{title:"Block to Consumption",paths:o.downstreamPaths,onNodeClick:a,focalNodeId:f,t:m})]})]})}function Zr({metadata:t,draftMetadata:n,onChange:s,t:r}){const o={width:"100%",background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:6,color:r.textPrimary,fontSize:12,fontFamily:r.font,padding:"8px 10px",outline:"none"},a={name:(n==null?void 0:n.name)||(t==null?void 0:t.name)||"",domain:(n==null?void 0:n.domain)||(t==null?void 0:t.domain)||"uncategorized",folderPath:(t==null?void 0:t.folderPath)||"",description:(n==null?void 0:n.description)||(t==null?void 0:t.description)||"",owner:(n==null?void 0:n.owner)||(t==null?void 0:t.owner)||"",tags:(n==null?void 0:n.tags)||(t==null?void 0:t.tags)||[]};return e.jsxs("div",{style:{display:"grid",gap:10,padding:12},children:[e.jsx("input",{value:a.name,onChange:p=>s({name:p.target.value}),placeholder:"Block name",style:o}),e.jsx("input",{value:a.domain,onChange:p=>s({domain:p.target.value}),placeholder:"Domain",style:o}),e.jsx("input",{value:a.folderPath,onChange:p=>s({folderPath:p.target.value}),placeholder:"Folder (optional), e.g. executive/monthly",style:{...o,fontFamily:r.fontMono}}),e.jsx("input",{value:a.owner,onChange:p=>s({owner:p.target.value}),placeholder:"Owner",style:o}),e.jsx("input",{value:a.description,onChange:p=>s({description:p.target.value}),placeholder:"Description",style:o}),e.jsx(Wi,{values:a.tags,onChange:p=>s({tags:p}),placeholder:"Tags",style:o})]})}function Jr({parameters:t,values:n,onChange:s,onReset:r,onRun:o,running:a,t:p}){return t.length===0?e.jsx(jt,{message:"This block has no runtime parameters. Add typed params in DQL Source when scope should be configurable."}):e.jsxs("div",{style:{padding:14,display:"grid",gap:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontSize:13,fontWeight:800,color:p.textPrimary},children:"Test parameter values"}),e.jsx("div",{style:{fontSize:11,color:p.textMuted,marginTop:3},children:"These values affect only the preview. Save defaults in the block definition."})]}),e.jsx("button",{type:"button",onClick:o,disabled:a,style:Te(p),children:a?"Running…":"Run preview"})]}),e.jsx(hr,{parameters:t,values:n,onChange:s,onReset:r,t:p,includeNonRuntime:!0,card:!0})]})}function es({values:t,t:n}){return e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:t.map(s=>e.jsxs("span",{style:{fontSize:10,color:n.textSecondary,background:n.appBg,border:`1px solid ${n.cellBorder}`,borderRadius:999,padding:"4px 7px"},children:[s.name," = ",Array.isArray(s.value)?s.value.join(", "):String(s.value)," ",e.jsxs("span",{style:{color:n.textMuted},children:["(",s.source,")"]})]},s.name))})}function jt({message:t}){const n=qt[Ot(s=>s.themeMode)];return e.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:t})}function ts({elapsedMs:t}){const n=qt[Ot(s=>s.themeMode)];return e.jsx("div",{style:{padding:12},children:e.jsxs("div",{style:{display:"grid",gap:8,border:`1px solid ${n.headerBorder}`,borderRadius:8,background:n.cellBg,padding:12,color:n.textPrimary,fontFamily:n.font},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:700},children:[e.jsx(Ze,{size:16,strokeWidth:2,color:n.accent,"aria-hidden":"true"}),e.jsx("span",{children:"Running preview"}),e.jsx("span",{style:{marginLeft:"auto",color:n.textMuted,fontSize:11,fontWeight:500},children:is(t)})]}),e.jsx("div",{style:{color:n.textMuted,fontSize:12,lineHeight:1.45},children:"Executing the block query against the active connection."})]})})}function Ii(t){if(!(t instanceof Jo)||!t.details||typeof t.details!="object"||Array.isArray(t.details))return null;const n=t.details.technicalDetails;return typeof n=="string"&&n.trim()?n:null}function ns({message:t,technicalDetails:n,repairing:s,onFix:r,onEdit:o}){const a=qt[Ot(p=>p.themeMode)];return e.jsx("div",{style:{padding:12},children:e.jsxs("div",{style:{display:"grid",gap:8,border:"1px solid rgba(248, 81, 73, 0.35)",borderRadius:8,background:"rgba(248, 81, 73, 0.08)",color:a.textPrimary,fontFamily:a.font,padding:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:700,color:"#f85149"},children:[e.jsx(ft,{size:16,strokeWidth:2,"aria-hidden":"true"}),e.jsx("span",{children:"Preview failed"})]}),e.jsx("div",{style:{color:a.textPrimary,fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t}),e.jsx("div",{style:{color:a.textMuted,fontSize:11.5,lineHeight:1.45},children:"Correct the named field or runtime problem, then run the same draft again. Nothing was saved or certified."}),e.jsxs("div",{style:{display:"flex",gap:7,flexWrap:"wrap"},children:[e.jsxs("button",{type:"button",onClick:r,disabled:s,style:{...Te(a),display:"inline-flex",alignItems:"center",gap:6,opacity:s?.72:1},children:[s?e.jsx(Ze,{size:13,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):e.jsx(Lt,{size:13}),s?"Fixing & running…":"Fix with AI & run"]}),e.jsx("button",{type:"button",onClick:o,style:Z(a),children:"Edit DQL"})]}),n&&n!==t&&e.jsxs("details",{style:{borderTop:`1px solid ${a.headerBorder}`,paddingTop:7},children:[e.jsx("summary",{style:{cursor:"pointer",color:a.textMuted,fontSize:10.5,fontWeight:700},children:"Technical details"}),e.jsx("pre",{style:{margin:"7px 0 0",maxHeight:180,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",color:a.textMuted,fontSize:10,lineHeight:1.4,fontFamily:a.fontMono},children:n})]})]})})}function is(t){const n=Math.max(0,Math.floor(t/1e3));if(n<60)return`${n}s`;const s=Math.floor(n/60),r=n%60;return`${s}m ${r}s`}const Mi={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},os={draft:[],review:["draft"],certified:["deprecated"],deprecated:["draft"]};function rs({currentStatus:t,blockPath:n,onStatusChanged:s,t:r}){const[o,a]=c.useState(!1),p=os[t]??[],m=async f=>{if(n){a(!0);try{const E=await W.updateBlockStatus(n,f);E.ok&&E.status&&s(E.status)}finally{a(!1)}}};return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",background:r.pillBg,borderRadius:8},children:[e.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:"Status:"}),e.jsx("span",{style:{fontSize:11,fontWeight:600,color:Mi[t]??r.textMuted,background:`${Mi[t]??r.textMuted}18`,padding:"2px 8px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:r.font},children:t}),e.jsx("span",{style:{flex:1}}),p.map(f=>e.jsx("button",{onClick:()=>void m(f),disabled:o,style:{background:f==="certified"?"#3fb950":f==="deprecated"?"#f85149":r.btnBg,border:`1px solid ${f==="certified"?"#3fb950":f==="deprecated"?"#f85149":r.btnBorder}`,borderRadius:4,color:f==="certified"||f==="deprecated"?"#fff":r.textSecondary,cursor:o?"not-allowed":"pointer",fontSize:10,fontWeight:600,fontFamily:r.font,padding:"3px 10px",textTransform:"capitalize",opacity:o?.5:1},children:o?"...":f==="certified"?"Certify":f==="deprecated"?"Deprecate":`Move to ${f}`},f))]})}function ss({result:t,t:n,repairing:s,onEditSource:r,onEditParameters:o,onReviewMetrics:a,onRun:p,onFix:m}){var P,L,K,_,w;const f=t.checklist,E=!!((P=f==null?void 0:f.issues)!=null&&P.some(x=>x.code==="tests_failed")||f!=null&&f.blockers.some(x=>/tests? must pass|test failed/i.test(x))),l=f?[["Metadata",f.metadata,!0],["Validation",f.validation,!0],["Run",f.run,!0],["Tests",f.tests,E],["Chart",f.chart,!1],["Lineage",f.lineage,!1]]:[],h=Array.from(new Set(((L=t.blockers)!=null&&L.length?t.blockers:(f==null?void 0:f.blockers)??[]).map(ls))),k=(K=f==null?void 0:f.issues)!=null&&K.length?f.issues:h.map(x=>({severity:"error",code:"certification_blocker",title:"Certification requirement is not ready",message:x,correction:"Update the block, run it again, and retry certification.",action:x==="The query must run successfully."?"run_again":"edit_source"})),b=t.pending?n.accent:t.ok?"#3fb950":"#d29922";return e.jsxs("div",{style:{margin:"12px 12px 0",border:`1px solid ${b}55`,borderRadius:8,background:`${b}0d`,padding:12,display:"grid",gap:10},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:12,fontWeight:800,color:b,fontFamily:n.font},children:t.pending?"Certification running":t.ok?"Block certified":"Unable to certify"}),(f==null?void 0:f.checkedAt)&&e.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:f.checkedAt})]}),e.jsx("div",{style:{fontSize:12,color:n.textMuted,lineHeight:1.45},children:t.pending?t.message??"The exact draft is saved and the certification gates are running in the background.":t.ok?f!=null&&f.tests?"Latest edits were saved, the block ran successfully, tests passed, and status was updated to certified.":"Latest edits were saved, the block ran successfully, no block tests are defined, and status was updated to certified.":`The draft is saved. Certification stopped with ${k.length||1} required fix${k.length===1?"":"es"}; nothing was partially certified.`}),t.pending&&e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{height:5,borderRadius:999,background:n.headerBorder,overflow:"hidden"},children:e.jsx("div",{style:{height:"100%",width:`${Math.max(4,Math.min(100,t.progress??4))}%`,borderRadius:999,background:n.accent,transition:"width 180ms ease"}})}),e.jsxs("div",{style:{fontSize:10.5,color:n.textMuted,display:"flex",justifyContent:"space-between"},children:[e.jsx("span",{children:t.phase?t.phase.replace(/_/g," "):"queued"}),e.jsxs("span",{children:[Math.round(t.progress??0),"%"]})]})]}),l.length>0&&e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:l.map(([x,X,H])=>e.jsxs("span",{title:!X&&!H?`${x} is optional for local certification.`:void 0,style:{fontSize:11,fontWeight:700,color:X?"#3fb950":H?"#d29922":n.textMuted,background:X?"#3fb95018":H?"#d2992218":n.pillBg,borderRadius:999,padding:"4px 8px"},children:[X?"✓":H?"!":"○"," ",x,!X&&!H?" · optional":""]},x))}),t.error&&k.length===0&&e.jsx("div",{style:{fontSize:12,color:"#f85149"},children:t.error}),!t.pending&&!t.ok&&k.length>0&&e.jsxs("div",{style:{display:"grid",gap:8},children:[e.jsxs("div",{style:{fontSize:10,color:"#d29922",textTransform:"uppercase",fontWeight:800},children:["Fixes before certification · ",k.length]}),k.map((x,X)=>{var $;const H=x.action==="review_metrics"?"Review metrics":x.action==="run_again"?"Run block":x.action==="edit_parameters"?"Edit run inputs":x.action==="configure_runtime"?"Review runtime":"Edit source",re=x.action==="review_metrics"||x.action==="configure_runtime"?a:x.action==="run_again"?p:x.action==="edit_parameters"?o:r;return e.jsxs("div",{style:{display:"grid",gap:7,border:`1px solid ${b}44`,borderRadius:8,background:n.cellBg,padding:10},children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8},children:[e.jsx(ft,{size:14,color:b,style:{marginTop:1,flexShrink:0}}),e.jsxs("div",{style:{minWidth:0},children:[e.jsxs("div",{style:{display:"flex",gap:7,alignItems:"baseline",flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:12,fontWeight:800,color:n.textPrimary},children:x.title??"Certification requirement is not ready"}),x.field&&e.jsx("span",{style:{fontSize:10,color:n.textMuted},children:x.field})]}),((($=x.references)==null?void 0:$.length)??0)>0&&e.jsx("div",{style:{display:"flex",gap:5,flexWrap:"wrap",marginTop:5},children:x.references.map(G=>e.jsx("code",{style:{fontSize:10,color:n.accent,background:n.pillBg,borderRadius:4,padding:"2px 5px"},children:G},G))})]})]}),e.jsx("div",{style:{fontSize:11.5,lineHeight:1.45,color:n.textSecondary},children:x.message}),x.correction&&e.jsxs("div",{style:{fontSize:11.5,lineHeight:1.45,color:n.textPrimary},children:[e.jsx("strong",{children:"How to fix:"})," ",x.correction]}),e.jsxs("div",{style:{display:"flex",gap:7,flexWrap:"wrap"},children:[e.jsx("button",{type:"button",onClick:re,style:Z(n),children:H}),x.technicalDetails&&e.jsx("button",{type:"button",onClick:()=>m(x),disabled:s,style:Z(n),children:s?"Fixing…":"Fix with AI & run"})]}),x.technicalDetails&&x.technicalDetails!==x.message&&e.jsxs("details",{children:[e.jsx("summary",{style:{cursor:"pointer",color:n.textMuted,fontSize:10.5,fontWeight:700},children:"Technical details"}),e.jsx("pre",{style:{margin:"6px 0 0",maxHeight:160,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",color:n.textMuted,fontSize:10,lineHeight:1.4,fontFamily:n.fontMono},children:x.technicalDetails})]})]},`${x.code??x.message}-${X}`)})]}),(((w=(_=t.certification)==null?void 0:_.warnings)==null?void 0:w.length)??0)>0&&e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{fontSize:10,color:n.textMuted,textTransform:"uppercase",fontWeight:800},children:"Warnings"}),t.certification.warnings.map(x=>e.jsxs("div",{style:{fontSize:12,color:n.textMuted},children:[x.rule,": ",x.message]},`${x.rule}-${x.message}`))]})]})}function ls(t){const n=t.trim(),s=n.toLowerCase();return s==="missing owner"||s==="block has owner: missing owner"?"Owner is required.":s==="missing domain"||s==="block has domain: missing domain"?"Domain is required.":s==="missing description"||s==="block has description: missing description"?"Description is required.":s==="block has not run successfully"?"The query must run successfully.":s==="tests must pass before certification"||s.startsWith("all tests pass:")?"Tests must pass.":s==="at least one test assertion is required before certification"||s.startsWith("block has tests:")?"Add at least one test assertion.":s==="visualization config is missing"?"Choose a visualization.":n}function as({entries:t,t:n}){return t.length===0?e.jsx(jt,{message:"No version history available. Commit changes to build history."}):e.jsxs("div",{style:{padding:12,display:"grid",gap:8},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.font},children:"Version History"}),t.map(s=>e.jsxs("div",{style:{padding:"8px 12px",border:`1px solid ${n.cellBorder}`,borderRadius:8,background:n.inputBg},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[e.jsx("span",{style:{fontSize:10,fontFamily:n.fontMono,color:n.accent,background:`${n.accent}12`,padding:"1px 6px",borderRadius:4},children:s.hash.slice(0,7)}),e.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:new Date(s.date).toLocaleDateString()}),e.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,marginLeft:"auto"},children:s.author})]}),e.jsx("div",{style:{fontSize:12,color:n.textPrimary,fontFamily:n.font},children:s.message})]},s.hash))]})}function ds(t,n){const s=t.match(/query\s*=\s*"""([\s\S]*?)"""/i);return s?t.replace(s[0],`query = """${s[1].trimEnd()}
|
|
23
18
|
${n}
|
|
24
19
|
"""`):/^\s*block\s+"/i.test(t.trim())?t.replace(/\n\}\s*$/,`
|
|
25
20
|
|
|
@@ -52,4 +47,4 @@ SELECT 1 AS value
|
|
|
52
47
|
}
|
|
53
48
|
}
|
|
54
49
|
|
|
55
|
-
`}const
|
|
50
|
+
`}const Ki="dql.block-studio.draft-session";function kn(){const t=`draft-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;try{window.localStorage.setItem(Ki,t)}catch{}return t}function cs(){var t;try{const n=(t=window.localStorage.getItem(Ki))==null?void 0:t.trim();if(n)return n}catch{}return kn()}function us(){var t;if(typeof window>"u")return"";try{return((t=window.localStorage.getItem("dql.block-studio.domain"))==null?void 0:t.trim())??""}catch{return""}}function ps(t,n){try{const s=window.localStorage.getItem(t);return s==null?n:s==="1"}catch{return n}}function fs(t,n,s,r){try{const o=Number(window.localStorage.getItem(t));return Number.isFinite(o)?Math.min(r,Math.max(s,o)):n}catch{return n}}function hs(t){return!!(t.blockStudioDraft.trim()||t.blockStudioMetadata||t.activeBlockPath)}function Gi(t){var o,a;const n=((o=t==null?void 0:t.domain)==null?void 0:o.trim())||"uncategorized",s=(a=t==null?void 0:t.folderPath)==null?void 0:a.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,""),r=((t==null?void 0:t.name)||"new_block").toLowerCase().replace(/[^a-z0-9_]+/g,"-").replace(/^[-_]+|[-_]+$/g,"")||"new-block";return`domains/${n}/blocks/${s?`${s}/`:""}${r}.dql`}function Vi(t){var s;const n=((s=t.match(/\bselect\b([\s\S]*?)\bfrom\b/i))==null?void 0:s[1])??"";return n?Array.from(new Set(n.split(",").map(r=>{var p,m;const o=(p=r.match(/\bas\s+([a-zA-Z_][\w$]*)\s*$/i))==null?void 0:p[1];return o||(((m=r.trim().match(/(?:^|\.)([a-zA-Z_][\w$]*)$/))==null?void 0:m[1])??"")}).filter(Boolean))).slice(0,24):[]}function Xe(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,n=>n.toUpperCase())}function ms(t,n){const s=n.trim().toLowerCase();if(!s)return t;const r=o=>{const a=[o.label,o.path,o.type].filter(m=>!!m).some(m=>m.toLowerCase().includes(s)),p=(o.children??[]).map(m=>r(m)).filter(m=>!!m);return a||p.length>0?{...o,children:p}:null};return t.map(o=>r(o)).filter(o=>!!o)}function gs(t){let n=0,s=0,r=0;const o=a=>{a.kind==="schema"&&(n+=1),a.kind==="table"&&(s+=1),a.kind==="column"&&(r+=1);for(const p of a.children??[])o(p)};for(const a of t)o(a);return{schemas:n,tables:s,columns:r}}function xs(t){const n=[],s=r=>{r.kind==="table"&&r.path&&n.push({path:r.path,columns:(r.children??[]).filter(o=>o.kind==="column").map(o=>o.label)});for(const o of r.children??[])s(o)};for(const r of t)s(r);return n}function Pi(t){return["businessOutcome","llmContext","primaryTerms","sourceSystems","synonyms","caveats"].filter(s=>new RegExp(`\\b${s}\\s*=`,"i").test(t)).length}function ys(t){return t.metrics+t.measures+t.dimensions+t.timeDimensions+t.entities+t.hierarchies+t.semanticModels+t.savedQueries}export{Ns as BlockStudio};
|