@duckcodeailabs/dql-cli 1.13.0 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/apps-api.d.ts +225 -5
  2. package/dist/apps-api.d.ts.map +1 -1
  3. package/dist/apps-api.js +1950 -117
  4. package/dist/apps-api.js.map +1 -1
  5. package/dist/args.d.ts +2 -0
  6. package/dist/args.d.ts.map +1 -1
  7. package/dist/args.js +3 -0
  8. package/dist/args.js.map +1 -1
  9. package/dist/assets/dql-notebook/assets/{AgentLogPage-CBGEoGmU.js → AgentLogPage-BlUE3qsX.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/{AiBuildDialog-CwAD3tXE.js → AiBuildDialog-O88iK6UW.js} +1 -1
  11. package/dist/assets/dql-notebook/assets/AiBuildResult-D-6G4Sh3.js +33 -0
  12. package/dist/assets/dql-notebook/assets/{AiSidePanel-DjB8PWHG.js → AiSidePanel-MRSGtQDV.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/AnalyticsHome-CcRVO6zN.js +6 -0
  14. package/dist/assets/dql-notebook/assets/AppsView-BTkGC-wl.js +5588 -0
  15. package/dist/assets/dql-notebook/assets/BlockStudio-BrTNaDpb.js +55 -0
  16. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-C4SZVNW-.js → BusinessArtifactView-itEIUrYy.js} +1 -1
  17. package/dist/assets/dql-notebook/assets/DbtFirstModelingPage-CbAqOpNc.js +22 -0
  18. package/dist/assets/dql-notebook/assets/{GitPage-BfVD4tVq.js → GitPage-BxOqRYu2.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/GlobalAiRail-Tfkx76CI.js +1 -0
  20. package/dist/assets/dql-notebook/assets/GovernedContextPage-CeaDbepP.js +7 -0
  21. package/dist/assets/dql-notebook/assets/{HelpDocsPage-BDPNVot1.js → HelpDocsPage-D1lAryYv.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{HomePage-DiOnRhEG.js → HomePage-GB6se6xW.js} +1 -1
  23. package/dist/assets/dql-notebook/assets/{LineageDAG-BiUFX2KL.js → LineageDAG-zCyN-hdg.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{LineageDetailView-CfbSvlPJ.js → LineageDetailView-Cg0TgG2Y.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{LineageDrawer-CgTScaGB.js → LineageDrawer-DwMcenDf.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-D7ZA7k68.js → LineagePathBreadcrumb-DUZx3ksU.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-GkD4y17x.js → MiniLineageGraph-DT_ycl6s.js} +1 -1
  28. package/dist/assets/dql-notebook/assets/{NewBlockModal-B9TfRjt7.js → NewBlockModal-qdhzeJPF.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{NewNotebookModal-BbO9NKUl.js → NewNotebookModal-BnaDzs1A.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{NotebookEditor-CuMpvXR9.js → NotebookEditor-CouPFzdo.js} +26 -31
  31. package/dist/assets/dql-notebook/assets/{ReadinessPage-BROJ9YBM.js → ReadinessPage-DB_KbH9Y.js} +1 -1
  32. package/dist/assets/dql-notebook/assets/{SetupOnboarding-BCcZlpuQ.js → SetupOnboarding-CamQq_N2.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/SkillsPage--mYkOAK2.js +10 -0
  34. package/dist/assets/dql-notebook/assets/{TrustBadge-vQQh8d0D.js → TrustBadge-ClEYiYeA.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-DBfsmXes.js +88 -0
  36. package/dist/assets/dql-notebook/assets/{answer-to-notebook-DuqCcDDl.js → answer-to-notebook-Cg3UyGwh.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{arrow-left-CMe1kkOL.js → arrow-left-DnYPGqlr.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/{arrow-right-DvB_DONr.js → arrow-right-Ct_YGrmU.js} +1 -1
  39. package/dist/assets/dql-notebook/assets/{book-open-text-CJ3NAvrs.js → book-open-text-DULlwbj6.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/{circle-x-BCgtha1W.js → circle-x-ByYxoiS9.js} +1 -1
  41. package/dist/assets/dql-notebook/assets/{dagre.esm-GKp7qoUL.js → dagre.esm-BjYSO53F.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{external-link-C-PXokWV.js → external-link-DprWh9Yf.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{grip-vertical-B4EHbGXW.js → grip-vertical-CrEEYkXN.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{index-1mIC_XX4.js → index-9w93YPF9.js} +127 -126
  45. package/dist/assets/dql-notebook/assets/index-B3shyZsg.css +1 -0
  46. package/dist/assets/dql-notebook/assets/{link-2-BLx-goet.js → link-2-BkW-rkEC.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{list-tree-BRFpEmvV.js → list-tree-BipBLmIE.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/{minimize-2-CDwSCGlO.js → minimize-2-BhXsglrO.js} +1 -1
  49. package/dist/assets/dql-notebook/assets/{panel-right-open-CunA1xO7.js → panel-right-open-BoCSilYB.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{bot-CV8DYRrt.js → play-mdoZawPu.js} +7 -2
  51. package/dist/assets/dql-notebook/assets/{rotate-ccw-DOrfTZk8.js → rotate-ccw-ELiDRUmj.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{semantic-fields-AfQvjt5R.js → semantic-fields-DVNRLfeU.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/sliders-horizontal-GeUzpmKz.js +6 -0
  54. package/dist/assets/dql-notebook/assets/{star-DDhv4e8M.js → star-D63O81Wp.js} +1 -1
  55. package/dist/assets/dql-notebook/assets/{triangle-alert-2ZXx8wAu.js → triangle-alert-BWrCxQVE.js} +1 -1
  56. package/dist/assets/dql-notebook/assets/upload-CI-ldXhC.js +6 -0
  57. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-Cv7Yq2hK.js +32 -0
  58. package/dist/assets/dql-notebook/assets/{user-round-BA074kiQ.js → user-round-Do21aFGo.js} +1 -1
  59. package/dist/assets/dql-notebook/assets/{wand-sparkles-CEYHLt9b.js → wand-sparkles-DT7u7F_x.js} +1 -1
  60. package/dist/assets/dql-notebook/assets/{workflow-CZtyrcR-.js → workflow-DHh2mMbn.js} +1 -1
  61. package/dist/assets/dql-notebook/assets/{wrench-Ong23-wu.js → wrench-7tYr_GKb.js} +1 -1
  62. package/dist/assets/dql-notebook/assets/{x-CSo1M3tu.js → x-CcYceFMz.js} +1 -1
  63. package/dist/assets/dql-notebook/index.html +2 -2
  64. package/dist/commands/app.d.ts.map +1 -1
  65. package/dist/commands/app.js +65 -133
  66. package/dist/commands/app.js.map +1 -1
  67. package/dist/commands/model.d.ts.map +1 -1
  68. package/dist/commands/model.js +83 -3
  69. package/dist/commands/model.js.map +1 -1
  70. package/dist/index.js +3 -0
  71. package/dist/index.js.map +1 -1
  72. package/dist/llm/providers/dql-agent-provider.d.ts +16 -0
  73. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  74. package/dist/llm/providers/dql-agent-provider.js +65 -2
  75. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  76. package/dist/local-runtime.d.ts +75 -0
  77. package/dist/local-runtime.d.ts.map +1 -1
  78. package/dist/local-runtime.js +2015 -88
  79. package/dist/local-runtime.js.map +1 -1
  80. package/dist/package.json +10 -10
  81. package/dist/sql-result-filter.d.ts +9 -0
  82. package/dist/sql-result-filter.d.ts.map +1 -1
  83. package/dist/sql-result-filter.js +25 -0
  84. package/dist/sql-result-filter.js.map +1 -1
  85. package/package.json +10 -10
  86. package/dist/assets/dql-notebook/assets/AgentAnswerCard-Cp0eh6zU.js +0 -5
  87. package/dist/assets/dql-notebook/assets/AiBuildResult-CyqTuQe5.js +0 -33
  88. package/dist/assets/dql-notebook/assets/AnalyticsHome-B7BkvA-R.js +0 -6
  89. package/dist/assets/dql-notebook/assets/AppsView-CUrqtEGC.js +0 -4583
  90. package/dist/assets/dql-notebook/assets/BlockStudio-Bl0aGQJR.js +0 -60
  91. package/dist/assets/dql-notebook/assets/DbtFirstModelingPage-B0uxitnx.js +0 -22
  92. package/dist/assets/dql-notebook/assets/GlobalAiRail-DUwdy3fB.js +0 -1
  93. package/dist/assets/dql-notebook/assets/GovernedContextPage-D9f26ZFb.js +0 -7
  94. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-Dj4AXAhT.js +0 -83
  95. package/dist/assets/dql-notebook/assets/chevron-up-HxU1l85K.js +0 -6
  96. package/dist/assets/dql-notebook/assets/index-DKu4CZt3.css +0 -1
  97. package/dist/assets/dql-notebook/assets/maximize-2-CCd5uRIZ.js +0 -6
  98. package/dist/assets/dql-notebook/assets/pencil-D_I14Wyk.js +0 -6
  99. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-3rzkZrqc.js +0 -18
@@ -0,0 +1,55 @@
1
+ import{c as bi,r as c,j as e,a5 as bo,h as Pt,i as vo,k as So,a6 as jo,t as Rt,a7 as on,a as W,a8 as dt,a9 as ko,e as cn,D as un,T as Kt,P as wo,S as Ht,f as ut,l as Co,L as ot,aa as Bo,ab as To,ac as se,ad as Bt,ae as Tt,af as vi,ag as Si,b as Io,ah as Do,B as Qt,A as ji,ai as ki,aj as wi,ak as Mo,al as ai,am as Ae,z as zo,an as Ci,Q as Bi,ao as Po,ap as Ro,w as Lo,E as rn,x as Eo,y as $o,H as di}from"./index-9w93YPF9.js";import{S as Ao,a as _o,b as ci}from"./LineagePathBreadcrumb-DUZx3ksU.js";import{u as Wo,a as Fo,T as Ti,b as Oo,d as qo,P as No,E as Ho,C as Ii}from"./usePersistedAgentThreadId-Cv7Yq2hK.js";import{M as Qo}from"./MiniLineageGraph-DT_ycl6s.js";import{b as Di,U as Uo,B as Ko}from"./UnifiedAgentRunPanel-DBfsmXes.js";import{a as Go,A as Vo}from"./AiSidePanel-MRSGtQDV.js";import{P as Mi,B as Yo}from"./play-mdoZawPu.js";import{T as Mt}from"./triangle-alert-BWrCxQVE.js";import{P as Xo}from"./panel-right-open-BoCSilYB.js";import{X as Zo}from"./x-CcYceFMz.js";import"./react-CRB3T2We.js";import"./codemirror-DXt7RW72.js";import"./TrustBadge-ClEYiYeA.js";import"./AiBuildResult-D-6G4Sh3.js";import"./user-round-Do21aFGo.js";import"./rotate-ccw-ELiDRUmj.js";import"./wrench-7tYr_GKb.js";import"./dagre.esm-BjYSO53F.js";import"./list-tree-BipBLmIE.js";import"./minimize-2-BhXsglrO.js";import"./arrow-right-Ct_YGrmU.js";/**
2
+ * @license lucide-react v0.563.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Jo=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],er=bi("chevron-left",Jo);/**
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 tr=[["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"}]],zi=bi("file-input",tr);function It({value:t,onChange:n,multiline:r,placeholder:s,style:i,ariaLabel:d,rows:p}){const[m,x]=c.useState(t),P=c.useRef(!1);c.useEffect(()=>{P.current||x(t)},[t]);const l={value:m,placeholder:s,style:i,"aria-label":d,onFocus:()=>{P.current=!0},onBlur:()=>{P.current=!1,x(t)},onChange:f=>{x(f.target.value),n(f.target.value)}};return r?e.jsx("textarea",{...l,rows:p}):e.jsx("input",{type:"text",...l})}function nr(t,n){return bo(t,n)}const ir={native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function or(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 ui=["day","week","month","quarter","year"];function rr(t,n,r){var d,p;if(!t)return ui;const s=(d=n.get(t))==null?void 0:d.granularities;if(s&&s.length>0)return s;const i=(p=r.find(m=>(m.reference??m.name)===t||m.name===t))==null?void 0:p.granularities;return i&&i.length>0?i:ui}function js(){var Rn,Ln,En,$n,An,_n,Wn,Fn,On,qn,Nn,Hn,Qn,Un,Kn,Gn,Vn,Yn,Xn,Zn,Jn,ei,ti,ni,ii,oi,ri;const t=Pt(vo(o=>({activeBlockPath:o.activeBlockPath,authoredDomains:o.authoredDomains,blockStudioDbtStatus:o.blockStudioDbtStatus,blockStudioDirty:o.blockStudioDirty,blockStudioDraft:o.blockStudioDraft,blockStudioImportOpen:o.blockStudioImportOpen,blockStudioMetadata:o.blockStudioMetadata,blockStudioPreview:o.blockStudioPreview,blockStudioValidation:o.blockStudioValidation,files:o.files,schemaTables:o.schemaTables,semanticLayer:o.semanticLayer,themeMode:o.themeMode}))),n=So(),{operations:r,track:s}=jo(),i=Rt[t.themeMode],[d,p]=c.useState(()=>Qr()),m=t.activeBlockPath?`block-studio.block.${encodeURIComponent(t.activeBlockPath)}`:`block-studio.draft.${d}`,x=Wo(m),[P,l]=c.useState("blocks"),[f,h]=c.useState("results"),[I,L]=c.useState(()=>Ur()),[$,J]=c.useState([]),[_,k]=c.useState({}),[S,te]=c.useState(""),[X,he]=c.useState(new Set),A=c.useMemo(()=>{const o=t.schemaTables.map(b=>[b.name,b.columns.map(j=>j.name)]),u=Zr($).map(b=>[b.path,b.columns]),v=new Map;for(const[b,j]of[...u,...o])b&&v.set(b,j);return v.size>0?Object.fromEntries(v):void 0},[t.schemaTables,$]),[K,G]=c.useState(!1),[D,Q]=c.useState(null),[F,V]=c.useState(null),[me,ee]=c.useState(0),[N,de]=c.useState({}),[M,U]=c.useState(!1),[ge,Te]=c.useState(!1),[Se,ce]=c.useState(null),[_e,ie]=c.useState(null),[Ie,ze]=c.useState(null),xe=c.useRef(!1),Pe=c.useRef(null),[a,w]=c.useState(null),[Z,ue]=c.useState(!1),[ye,We]=c.useState(null),[ne,oe]=c.useState(!1),[Fe,Oe]=c.useState(null),[Ge,qe]=c.useState(0),[rt,Ne]=c.useState(!1),[st,He]=c.useState(!1),Re=c.useRef(null),Be=c.useRef(!1),[ft,Ve]=c.useState(null),[lt,et]=c.useState([]),[tt,g]=c.useState(!1),[T,z]=c.useState(!1),[C,q]=c.useState(null),[re,y]=c.useState(null),[B,R]=c.useState(null),[O,De]=c.useState(340),[je,Lt]=c.useState(320),[be,Gt]=c.useState(!1),[mn,Et]=c.useState(!1),[le,Ai]=c.useState(()=>typeof window<"u"?window.innerWidth<900:!1),[gn,Le]=c.useState(()=>t.blockStudioImportOpen?"import":"start"),[ht,ae]=c.useState("visual"),[Ye,Vt]=c.useState(()=>Kr("dql.block-studio.ai.open",!1)),[$t,_i]=c.useState(()=>Gr("dql.block-studio.ai.width",420,360,520)),[xn,yn]=c.useState(!1),[Wi,Fi]=c.useState(!1),[Oi,qi]=c.useState(0),[Ee,At]=c.useState(null),[Ni,bn]=c.useState([]),[Hi,vn]=c.useState(!1),[mt,Yt]=c.useState(null),[Sn,Xt]=c.useState(null),[jn,Qi]=c.useState("ask"),[Ui,Ki]=c.useState(""),[Gi,Vi]=c.useState(void 0),[Yi,Xi]=c.useState(!1),[kn,_t]=c.useState(null),wn=c.useRef(t.activeBlockPath),Zt=c.useRef(t.blockStudioDraft);Zt.current=t.blockStudioDraft;const $e=on({queryKey:["block-studio","catalog","summary"],queryFn:()=>W.getBlockStudioCatalog({includeSemantic:!1}),staleTime:3e4}),gt=on({queryKey:["block-studio","dbt-status"],queryFn:()=>W.getBlockStudioDbtStatus(),staleTime:3e4}),xt=on({queryKey:["semantic-layer"],queryFn:()=>W.getSemanticLayer(),staleTime:3e4});c.useEffect(()=>{const o=()=>qe(u=>u+1);return window.addEventListener("dql:block-library-invalidated",o),()=>window.removeEventListener("dql:block-library-invalidated",o)},[]),c.useEffect(()=>{var u,v,b;if(!Ie)return;const o=r.find(j=>j.id===Ie);if(!(!o||o.status==="queued"||o.status==="running")){if(o.status==="succeeded"){const j=o.result;_t({pending:!1,ok:(j==null?void 0:j.outcome)==="certified",checklist:j==null?void 0:j.checklist,blockers:(j==null?void 0:j.blockers)??((u=j==null?void 0:j.checklist)==null?void 0:u.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}),(j==null?void 0:j.outcome)==="draft_saved_with_blockers"&&w("Draft saved. Certification needs attention; review the checklist below.")}else w(((v=o.error)==null?void 0:v.message)??"Certification did not complete. The draft remains saved."),_t({pending:!1,error:((b=o.error)==null?void 0:b.message)??o.message});ze(null),h("save")}},[Ie,r]),c.useEffect(()=>{n({type:"SET_BLOCK_STUDIO_CATALOG_LOADING",loading:$e.isLoading}),$e.data?(n({type:"SET_BLOCK_STUDIO_CATALOG",catalog:$e.data}),J($e.data.databaseTree),Ve(null)):$e.isError&&Ve("Failed to load schema. Check your connection and try refreshing.")},[$e.data,$e.isError,$e.isLoading,n]),c.useEffect(()=>{gt.data?n({type:"SET_BLOCK_STUDIO_DBT_STATUS",status:gt.data}):gt.isError&&n({type:"SET_BLOCK_STUDIO_DBT_STATUS",status:null})},[gt.data,gt.isError,n]),c.useEffect(()=>{n({type:"SET_SEMANTIC_LOADING",loading:xt.isLoading}),xt.data&&n({type:"SET_SEMANTIC_LAYER",layer:xt.data})},[n,xt.data,xt.isLoading]);const Wt=c.useCallback(async()=>{vn(!0);try{const o=await W.listBlockStudioImports();bn(o.sessions??[])}catch{bn([])}finally{vn(!1)}},[]);c.useEffect(()=>{Wt()},[Wt]),c.useEffect(()=>{const o=wn.current,u=t.activeBlockPath;u&&u!==o&&n({type:"CLOSE_BLOCK_IMPORT"}),wn.current=u},[t.activeBlockPath,n]),c.useEffect(()=>{const o=new AbortController,u=window.setTimeout(()=>{t.blockStudioDraft.trim()&&W.validateBlockStudio(t.blockStudioDraft,t.activeBlockPath,o.signal).then(v=>{o.signal.aborted||n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:v})}).catch(()=>{})},250);return()=>{window.clearTimeout(u),o.abort()}},[t.blockStudioDraft,t.activeBlockPath,n]),c.useMemo(()=>Yr($,S),[$,S]);const Ft=c.useMemo(()=>Xr($),[$]),Cn={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},Bn=Jr(Cn);c.useEffect(()=>{const o=()=>Ai(window.innerWidth<900);return o(),window.addEventListener("resize",o),()=>window.removeEventListener("resize",o)},[]),c.useEffect(()=>{try{window.localStorage.setItem("dql.block-studio.ai.open",Ye?"1":"0")}catch{}},[Ye]),c.useEffect(()=>{try{window.localStorage.setItem("dql.block-studio.ai.width",String($t))}catch{}},[$t]),c.useEffect(()=>{if(I)try{window.localStorage.setItem("dql.block-studio.domain",I)}catch{}},[I]),c.useEffect(()=>{var u,v;const o=(v=(u=t.blockStudioMetadata)==null?void 0:u.domain)==null?void 0:v.trim();o&&o!=="uncategorized"&&L(o)},[t.activeBlockPath,(Rn=t.blockStudioMetadata)==null?void 0:Rn.domain]),c.useEffect(()=>{t.blockStudioImportOpen&&(Le("import"),n({type:"CLOSE_BLOCK_IMPORT"}))},[n,t.blockStudioImportOpen]),c.useEffect(()=>{var o;Le(Vr(t)?"manual":"start"),ae(((o=dt(t.blockStudioDraft))==null?void 0:o.blockType)==="semantic"?"visual":"source")},[t.activeBlockPath]);const nt=c.useMemo(()=>{var u;const o=dt(t.blockStudioDraft);return t.blockStudioMetadata?{...o,name:(o==null?void 0:o.name)||t.blockStudioMetadata.name,domain:(o==null?void 0:o.domain)||t.blockStudioMetadata.domain,description:(o==null?void 0:o.description)||t.blockStudioMetadata.description,owner:(o==null?void 0:o.owner)||t.blockStudioMetadata.owner,tags:(u=o==null?void 0:o.tags)!=null&&u.length?o.tags:t.blockStudioMetadata.tags,blockType:(o==null?void 0:o.blockType)||"custom",status:(o==null?void 0:o.status)||t.blockStudioMetadata.reviewStatus||"draft"}:o},[t.blockStudioDraft,t.blockStudioMetadata]),pe=(nt==null?void 0:nt.name)??((Ln=t.blockStudioMetadata)==null?void 0:Ln.name)??null,Xe=((nt==null?void 0:nt.blockType)??"custom")==="semantic",Qe=!!(t.blockStudioDraft.trim()||t.blockStudioMetadata||t.activeBlockPath);c.useEffect(()=>{var o;if(t.activeBlockPath){if(Pe.current==="builder"){Pe.current=null,ae(((o=dt(t.blockStudioDraft))==null?void 0:o.blockType)==="semantic"?"visual":"source");return}t.activeBlockPath&&ae("detail")}},[t.activeBlockPath]);const Jt=c.useCallback(async o=>{const u=`block:${o}`;n({type:"SET_LINEAGE_FOCUS",nodeId:u}),z(!0);try{const[v,b,j]=await Promise.all([W.fetchLineageNode(u),W.queryLineage({focus:u,upstreamDepth:3,downstreamDepth:2}),W.fetchLineagePaths(u,{maxDepth:6,maxPaths:6})]);q(v),y(b.graph??null),R(j)}catch{q(null),y(null),R(null)}finally{z(!1)}},[n]);c.useEffect(()=>{pe&&Jt(pe)},[pe,Jt]);const Me=o=>{Q(null),w(null),ce(null),ie(null),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:o});const u=dt(o),v=t.blockStudioMetadata;if(!u||!v)return;const b={...v,name:u.name||v.name,domain:u.domain||v.domain,description:u.description,owner:u.owner,tags:u.tags,reviewStatus:u.status||v.reviewStatus};(b.name!==v.name||b.domain!==v.domain||b.description!==v.description||b.owner!==v.owner||b.reviewStatus!==v.reviewStatus||b.tags.join("\0")!==v.tags.join("\0"))&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:b})},Zi=o=>{if(o==="semantic"===Xe)return;const u=t.blockStudioMetadata,v=(u==null?void 0:u.name)||(o==="semantic"?"new_semantic_block":"new_sql_block");let b=o==="semantic"?dn(v):Nt(v);b=Bt(b,v),o==="custom"&&(b=ki(b,"")),u&&(b=se(b,"domain",u.domain||"uncategorized"),b=se(b,"description",u.description??""),b=se(b,"owner",u.owner??""),b=Tt(b,u.tags??[])),Me(b),ae("visual")},Ji=(o,u)=>{const v=t.blockStudioMetadata;let b=Xe?t.blockStudioDraft:dn((v==null?void 0:v.name)||"new_semantic_block");!Xe&&v&&(b=se(b,"domain",v.domain||"uncategorized"),b=se(b,"description",v.description??""),b=se(b,"owner",v.owner??""),b=Tt(b,v.tags??[])),b=vi(b,o),b=Si(b,"dimensions",u),Me(b),Yt(null),Xt(null),Le("manual"),ae("visual")},Ot=()=>{n({type:"START_NEW_BLOCK_WORKSPACE"}),Q(null),w(null),ce(null),ie(null),p(fn()),At(null),Le("start"),ae("visual")},Tn=()=>{if(t.blockStudioDirty){He(!0);return}Ot()},In=()=>{Tn()},Dn=o=>{const u=o==="semantic"?"new_semantic_block":"new_sql_block",v=I||"uncategorized",b=o==="semantic"?dn(u):Nt(u),j=se(b,"domain",v);n({type:"SET_BLOCK_STUDIO_DRAFT",draft:j}),n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{name:u,path:null,domain:v,folderPath:"",description:"",owner:"",tags:[],reviewStatus:"draft",sourceKind:"manual"}}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:null}),n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:null}),Le("manual"),ae("visual")},qt=async()=>{G(!0),Q(null),V(Date.now()),ee(0),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:null});try{const o=await W.runBlockStudio(t.blockStudioDraft,t.activeBlockPath,N);n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:o}),h("results")}catch(o){const u=o instanceof Error?o.message:String(o);Q(u),ce(u),h(/required parameter|provide required parameter/i.test(u)?"parameters":"results")}finally{G(!1),V(null)}},eo=async()=>{var u,v;if(ge||!Se)return;const o=t.blockStudioDraft;Te(!0),w(null),ie(null);try{const b=await W.repairAndRunBlockStudio(o,Se,N,pe??((u=t.blockStudioMetadata)==null?void 0:u.name)??void 0);if(Zt.current!==o)throw new Error("The block changed while AI repair was running. The stale repair was not applied.");const j=await W.validateBlockStudio(b.source,t.activeBlockPath);if(j.saveable===!1)throw new Error(((v=j.diagnostics.find(H=>H.severity==="error"))==null?void 0:v.message)??"The repaired DQL still has an authoring error.");if(Zt.current!==o)throw new Error("The block changed while AI repair was running. The stale repair was not applied.");Me(b.source),n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:j}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:b.preview}),Q(null),ce(null),ie(`${b.repairMode==="ai"?"AI fixed":"DQL fixed"} the draft and the corrected block ran successfully. Review the changes, then save the draft.`),ae("source"),h("results"),Et(!1)}catch(b){const j=b instanceof Error?b.message:String(b);w(j)}finally{Te(!1)}},to=async(o=t.blockStudioDraft)=>{var b,j;if(!t.blockStudioMetadata)throw new Error("Block metadata is required before saving.");const u=await W.saveBlockStudio({path:t.activeBlockPath,source:o,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 qe(H=>H+1),n({type:"OPEN_BLOCK_STUDIO",file:{name:`${u.metadata.name}.dql`,path:u.path,type:"block",folder:"blocks"},payload:u}),t.files.some(H=>H.path===u.path)||n({type:"FILE_ADDED",file:{name:`${u.metadata.name}.dql`,path:u.path,type:"block",folder:"blocks"}}),((b=u.lineageRefresh)==null?void 0:b.status)==="ready"?Jt(u.metadata.name):((j=u.lineageRefresh)==null?void 0:j.status)==="failed"&&(w(`Block saved, but lineage refresh failed: ${u.lineageRefresh.message??"compile failed"}`),setTimeout(()=>w(null),7e3)),u},en=async()=>{var o,u;if(!((o=t.blockStudioMetadata)!=null&&o.name.trim())||!t.blockStudioMetadata.owner.trim())return Re.current="save",Ne(!0),!1;U(!0),w(null);try{const v=t.blockStudioMetadata.reviewStatus==="certified"&&t.blockStudioDirty?se(t.blockStudioDraft,"status","draft"):t.blockStudioDraft,b=await W.validateBlockStudio(v,t.activeBlockPath);if(n({type:"SET_BLOCK_STUDIO_VALIDATION",validation:b}),b.saveable===!1||b.saveable===void 0&&!b.valid){const j=((u=b.diagnostics.find(H=>H.severity==="error"))==null?void 0:u.message)??"Fix the block errors before saving.";return w(`Draft not saved: ${j}`),ce(j),ae("source"),!1}return await to(v),ce(null),ie(null),h("save"),!0}catch(v){const b=(v==null?void 0:v.message)??"Save failed";return w(b.includes("409")||b.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":b),!1}finally{U(!1)}},tn=(o,u)=>{Oe(null),We({path:o,name:u}),ue(!0)},no=async()=>{var u;const o=ye==null?void 0:ye.path;if(o){oe(!0),Oe(null);try{const v=await W.deleteBlockStudio(o);n({type:"FILE_REMOVED",path:v.path}),t.activeBlockPath===v.path&&(n({type:"START_NEW_BLOCK_WORKSPACE"}),p(fn()),At(null),Le("start"),ae("visual")),ue(!1),We(null),qe(b=>b+1),((u=v.lineageRefresh)==null?void 0:u.status)==="failed"&&Ve(`Block deleted, but lineage refresh failed: ${v.lineageRefresh.message??"compile failed"}`)}catch(v){Oe(v instanceof Error?v.message:String(v))}finally{oe(!1)}}},Mn=async()=>{var o;if(!((o=t.blockStudioMetadata)!=null&&o.name.trim())||!t.blockStudioMetadata.owner.trim())return Re.current="certify",Ne(!0),!1;if(xe.current||Ie)return!1;xe.current=!0,U(!0),w(null);try{_t(null);const u=t.blockStudioMetadata.reviewStatus==="certified"&&t.blockStudioDirty?se(t.blockStudioDraft,"status","draft"):t.blockStudioDraft,v=`${t.blockStudioMetadata.sourceFingerprint??"new"}:${Date.now()}`,b=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`block-certification-${v}`,j=await W.requestBlockStudioCertification({source:u,path:t.activeBlockPath,metadata:t.blockStudioMetadata,expectedSourceFingerprint:t.blockStudioMetadata.sourceFingerprint,clientRevision:v,idempotencyKey:b});return s(j.operation),ze(j.operation.id),n({type:"BLOCK_CERTIFICATION_ACCEPTED",source:u}),_t({pending:!0}),h("save"),!0}catch(u){const v=(u==null?void 0:u.message)??"Save failed";return w(v.includes("409")||v.includes("BLOCK_EXISTS")?"A block with this name already exists. Rename and try again.":v),setTimeout(()=>w(null),5e3),!1}finally{xe.current=!1,U(!1)}};c.useEffect(()=>{var v;const o=Re.current;if(!o||!((v=t.blockStudioMetadata)!=null&&v.name.trim())||!t.blockStudioMetadata.owner.trim())return;Re.current=null,(o==="certify"?Mn():en()).then(b=>{b&&Be.current&&(Be.current=!1,Ot())})},[(En=t.blockStudioMetadata)==null?void 0:En.name,($n=t.blockStudioMetadata)==null?void 0:$n.owner,t.blockStudioDraft]);const io=o=>{var b;const u=o.savedPath??((b=o.draftSave)==null?void 0:b.path)??"",v={path:u,source:o.dqlSource,metadata:{name:o.name,path:u||null,domain:o.domain,description:o.description,owner:o.owner,tags:o.tags,reviewStatus:o.reviewStatus,sourceKind:o.sourceKind,sourcePath:o.sourcePath,importId:Ee==null?void 0:Ee.id,candidateId:o.id,lineage:o.lineage.sourceTables},companionPath:null,validation:o.validation??{valid:!0,diagnostics:[],semanticRefs:{metrics:[],dimensions:[],segments:[]},executableSql:null}};n({type:"OPEN_BLOCK_STUDIO",file:{name:`${o.name}.dql`,path:u,type:"block",folder:"blocks",isNew:!u},payload:v}),n({type:"SET_BLOCK_STUDIO_PREVIEW",preview:o.preview}),h("results"),Le("manual"),ae("visual")},oo=(o,u)=>{t.files.some(b=>b.path===u.path)||n({type:"FILE_ADDED",file:{name:`${u.metadata.name}.dql`,path:u.path,type:"block",folder:"blocks"}}),At(b=>b&&{...b,candidates:b.candidates.map(j=>j.id===o.id?o:j)}),Wt()},ro=(o,u)=>{var H,Ue,yt,bt,vt,St,jt;const v=t.blockStudioDraft.trim()?t.blockStudioDraft:Nt(((H=u==null?void 0:u.title)==null?void 0:H.trim())||"AI Generated Block"),b=(Ue=u==null?void 0:u.blockSource)!=null&&Ue.trim()?u.blockSource.trim():xi(v,o);Me(b);const j=dt(b);j&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{name:j.name||(u==null?void 0:u.title)||"AI Generated Block",path:t.activeBlockPath,domain:j.domain||(u==null?void 0:u.domain)||"analytics",description:j.description||(u==null?void 0:u.description)||`AI generated block for ${(u==null?void 0:u.question)??"analysis"}`,owner:j.owner||(u==null?void 0:u.owner)||"",tags:j.tags.length>0?j.tags:(u==null?void 0:u.tags)??["ai-generated","review-required"],reviewStatus:j.status||"draft",sourceKind:((yt=t.blockStudioMetadata)==null?void 0:yt.sourceKind)??"ai-generated",sourcePath:(bt=t.blockStudioMetadata)==null?void 0:bt.sourcePath,importId:(vt=t.blockStudioMetadata)==null?void 0:vt.importId,candidateId:(St=t.blockStudioMetadata)==null?void 0:St.candidateId,lineage:(jt=t.blockStudioMetadata)==null?void 0:jt.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:o.trim()}}),h("results")},so=async o=>{var yt,bt,vt,St,jt,si,li;const u=(bt=(yt=o.dqlArtifact)==null?void 0:yt.source)==null?void 0:bt.trim(),v=(o.sql??"").trim();if(!u&&!v)return;let b;if((vt=o.question)!=null&&vt.trim())try{const ke=await W.composeSemanticBlock(o.question.trim());ke.ok&&ke.source.trim()&&(b=ke.source.trim())}catch{}const j=b||u||xi(Nt(((St=o.title)==null?void 0:St.trim())||"AI Generated Block"),v),H=dt(j),Ue=(H==null?void 0:H.name)||((jt=o.dqlArtifact)==null?void 0:jt.name)||o.title||"AI Generated Block";U(!0),w(null);try{const ke=await W.saveAgentBlockDraft({source:j,name:Ue,domain:(H==null?void 0:H.domain)||((si=t.blockStudioMetadata)==null?void 0:si.domain)||"uncategorized",description:(H==null?void 0:H.description)||`AI-generated draft for ${o.title??Ue}`,tags:(li=H==null?void 0:H.tags)!=null&&li.length?H.tags:["ai-generated","review-required"],runId:o.sourceRunId});Pe.current="builder",n({type:"OPEN_BLOCK_STUDIO",file:{name:`${ke.metadata.name}.dql`,path:ke.path,type:"block",folder:"blocks",isNew:!1},payload:ke}),t.files.some(nn=>nn.path===ke.path)||n({type:"FILE_ADDED",file:{name:`${ke.metadata.name}.dql`,path:ke.path,type:"block",folder:"blocks"}}),qe(nn=>nn+1),Le("manual"),ae("visual"),h("save")}catch(ke){w(ke instanceof Error?ke.message:String(ke))}finally{U(!1)}},at=o=>{const u=(o==null?void 0:o.kind)??"ask";h("results"),Qi(u),Ki((o==null?void 0:o.initialInput)??""),Vi(o!=null&&o.autoRun?{text:o.autoRun,mode:"block",nonce:Date.now()}:void 0),Vt(!0)};c.useCallback(async()=>{try{const o=(await $e.refetch()).data;o!=null&&o.databaseTree&&J(o.databaseTree),o&&n({type:"SET_BLOCK_STUDIO_CATALOG",catalog:o})}catch{}},[$e,n]),c.useEffect(()=>{if(!K||!F)return;const o=()=>ee(Date.now()-F);o();const u=window.setInterval(o,1e3);return()=>window.clearInterval(u)},[K,F]);const zn=((An=t.blockStudioValidation)==null?void 0:An.chartConfig)??((_n=t.blockStudioPreview)==null?void 0:_n.chartConfig)??{chart:"table"},lo=t.blockStudioPreview?Fo(t.blockStudioPreview.result,t.blockStudioPreview.chartConfig):"table",ao=o=>{o.preventDefault();const u=o.clientX,v=O,b=H=>{const Ue=Math.min(560,Math.max(300,v+H.clientX-u));De(Ue)},j=()=>{window.removeEventListener("mousemove",b),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",b),window.addEventListener("mouseup",j)},co=o=>{o.preventDefault();const u=o.clientY,v=je,b=H=>{const Ue=Math.min(500,Math.max(180,v-(H.clientY-u)));Lt(Ue)},j=()=>{window.removeEventListener("mousemove",b),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",b),window.addEventListener("mouseup",j)},uo=o=>{o.preventDefault();const u=o.clientX,v=$t,b=H=>{_i(Math.min(520,Math.max(360,v-(H.clientX-u))))},j=()=>{window.removeEventListener("mousemove",b),window.removeEventListener("mouseup",j)};window.addEventListener("mousemove",b),window.addEventListener("mouseup",j)},it=Qe&&!mn,po=le?"minmax(0, 1fr)":`${be?0:O}px ${be?0:6}px minmax(0, 1fr) ${Ye?6:0}px ${Ye?xn?`min(${Go}px, 52vw)`:`${$t}px`:0}`,fo=le?be?it?`minmax(0, 1fr) 6px ${je}px`:"minmax(0, 1fr) 0 0":it?`minmax(220px, 34vh) minmax(320px, 1fr) 6px ${je}px`:"minmax(220px, 34vh) minmax(0, 1fr) 0 0":it?`minmax(0, 1fr) 6px ${je}px`:"minmax(0, 1fr) 0 0",ho=le?"1":"3",Pn=le?be?"1":"2":"1",mo=le?"1":"3",go=le?be?"2":"3":"2",xo=le?"1":"3",yo=le?be?"3":"4":"3";return e.jsxs("div",{style:{flex:1,position:"relative",display:"grid",gridTemplateColumns:po,gridTemplateRows:fo,overflow:"hidden",background:i.appBg},children:[e.jsx("div",{style:{gridColumn:"1",gridRow:le?"1":"1 / 4",borderRight:be?"none":`1px solid ${i.headerBorder}`,borderBottom:le&&!be?`1px solid ${i.headerBorder}`:"none",display:be?"none":"flex",flexDirection:"column",overflow:"hidden",background:i.sidebarBg,minWidth:0},children:e.jsx("div",{style:{flex:1,minHeight:0,overflow:"hidden"},children:e.jsx(ko,{tabs:["blocks","semantic","database"],defaultTab:P,blockDomain:I,onBlockDomainChange:L,onInsertText:o=>{if(Xe){Xt("That snippet is SQL. Use a SQL Block for raw SELECT work, or keep this Semantic Block on metrics and dimensions.");return}Me(Hr(t.blockStudioDraft,o))},onSemanticCompose:Ji,onNewBlock:In,onDeleteBlock:o=>tn(o.path,o.name),blockLibraryRefreshKey:Ge,onCollapse:()=>Gt(!0),footer:t.semanticLayer.loading?`Loading ${(((Wn=t.blockStudioDbtStatus)==null?void 0:Wn.counts.metrics)??0).toLocaleString()} semantic metrics…`:`${t.semanticLayer.provider?`${t.semanticLayer.provider} synced`:"dbt synced"} · ${Ft.tables} table${Ft.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:be?void 0:ao,style:{gridColumn:"2",gridRow:"1 / 4",display:be||le?"none":"block",cursor:"col-resize",background:i.headerBorder}}),e.jsxs("div",{style:{display:le&&Ye?"none":"flex",flexDirection:"column",minWidth:0,overflow:"hidden",gridColumn:ho,gridRow:Pn},children:[e.jsx("style",{children:`
12
+ @keyframes dql-agent-fadein { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }
13
+ @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 ${i.headerBorder}`,background:i.cellBg,overflowX:"auto"},children:[be&&e.jsx("button",{onClick:()=>Gt(!1),style:{background:"transparent",border:"none",color:i.textMuted,cursor:"pointer",fontSize:14,fontFamily:i.font,padding:0,lineHeight:1},title:"Open explorer",children:"›"}),e.jsxs("button",{type:"button",onClick:Tn,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:i.textMuted,fontSize:12,fontFamily:i.font,whiteSpace:"nowrap",cursor:"pointer"},children:[e.jsx(er,{size:12,strokeWidth:2})," Blocks"]}),e.jsx(cn,{size:11,color:i.textMuted,style:{flexShrink:0}}),e.jsx("span",{style:{fontSize:12.5,fontWeight:600,color:i.textPrimary,fontFamily:i.fontMono,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:220},children:pe||((Fn=t.blockStudioMetadata)==null?void 0:Fn.name)||(Qe?"new_block":Xe?"semantic":"sql")}),((On=t.blockStudioMetadata)==null?void 0:On.reviewStatus)&&e.jsx(Di,{status:t.blockStudioMetadata.reviewStatus,t:i}),Qe&&gn==="manual"&&ht!=="detail"&&e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:2,padding:2,border:`1px solid ${i.headerBorder}`,borderRadius:7,background:i.appBg,marginLeft:6,flexShrink:0},children:[e.jsx("button",{type:"button",onClick:()=>ae("visual"),style:pi(i,ht==="visual"),children:"Visual Builder"}),e.jsx("button",{type:"button",onClick:()=>ae("source"),style:pi(i,ht==="source"),children:"DQL Source"})]}),Qe&&e.jsx(Ze,{label:`Context${yi(t.blockStudioDraft)?` (${yi(t.blockStudioDraft)})`:""}`,Icon:un,onClick:()=>Xi(o=>!o)}),e.jsx("div",{style:{flex:1}}),t.activeBlockPath&&e.jsx(Ze,{label:"Delete",Icon:Kt,variant:"danger",title:"Delete this saved block",onClick:()=>{var o;return tn(t.activeBlockPath,((o=t.blockStudioMetadata)==null?void 0:o.name)||pe||t.activeBlockPath)}}),e.jsx(Ze,{label:"New block",Icon:wo,onClick:In}),Qe&&e.jsxs(e.Fragment,{children:[e.jsx(Ze,{label:"Ask AI",Icon:Ht,onClick:()=>at({kind:"ask"})}),t.activeBlockPath&&e.jsx(Ze,{label:"Modify with AI",Icon:Ht,onClick:()=>at({kind:"edit",initialInput:`Modify this block${pe?` (${pe})`:""}: `})}),e.jsx(Ze,{label:"Run",Icon:Mi,onClick:()=>void qt(),busy:K}),e.jsx(Ze,{label:M?"Saving":"Save draft",Icon:ut,variant:"secondary",busy:M,onClick:()=>void en(),title:"Save changes as a review-required draft"}),e.jsx(Ze,{label:((qn=t.blockStudioMetadata)==null?void 0:qn.reviewStatus)==="certified"?"Re-certify":"Certify",Icon:Co,variant:"primary",busy:M||!!Ie,onClick:()=>void Mn(),title:"Run validation, query, tests, chart, and lineage gates before certification"})]}),a&&e.jsx("span",{style:{fontSize:11,color:"var(--status-error)",fontFamily:i.font,padding:"4px 8px",background:"var(--status-error-bg)",borderRadius:6},children:a})]}),Se&&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:i.textPrimary,fontFamily:i.font},children:[e.jsx(Mt,{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:i.textSecondary},children:Se}),(((Nn=t.blockStudioValidation)==null?void 0:Nn.diagnostics.filter(o=>o.severity==="error").length)??0)>1&&e.jsx("div",{style:{marginTop:4,fontSize:10.5,color:i.textMuted},children:t.blockStudioValidation.diagnostics.filter(o=>o.severity==="error").slice(1,3).map(o=>o.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 eo(),disabled:ge,style:{...Ce(i),display:"inline-flex",alignItems:"center",gap:6,opacity:ge?.72:1},children:[ge?e.jsx(ot,{size:13,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):e.jsx(Ht,{size:13}),ge?"Fixing & running…":"Fix with AI & run"]}),e.jsx("button",{type:"button",onClick:()=>ae("source"),style:Y(i),children:"Edit DQL"}),e.jsx("button",{type:"button",onClick:()=>at({kind:"edit",initialInput:`Help me fix this block error without changing its intended grain, parameters, or trust state: ${Se} `}),style:Y(i),children:"Open Block AI"})]})]}),_e&&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:i.textSecondary,fontSize:11.5,fontFamily:i.font},children:[e.jsx(ut,{size:14,color:"var(--status-success)"})," ",_e]}),Qe&&Yi&&e.jsx(fr,{source:t.blockStudioDraft,databaseStats:Ft,semanticCount:Bn,onChange:Me,onOpenExplorer:()=>{Gt(!1),l("database")},onOpenAi:()=>at({kind:"edit",initialInput:"Review and improve this block context. Keep only grounded business references, sources, constraints, and caveats: "}),t:i}),e.jsx("div",{style:{flex:1,overflow:"hidden"},children:gn==="import"?e.jsx(Tr,{session:Ee,sessions:Ni,sessionsLoading:Hi,onClose:()=>Le(Qe?"manual":"start"),onSessionChange:At,onRefreshSessions:Wt,onSelectCandidate:io,onSavedCandidate:oo,defaultDomain:((Hn=t.blockStudioMetadata)==null?void 0:Hn.domain)??I,defaultOwner:((Qn=t.blockStudioMetadata)==null?void 0:Qn.owner)??"",themeMode:t.themeMode,t:i,inline:!0}):Qe?ht==="detail"?e.jsx(gr,{metadata:t.blockStudioMetadata,source:t.blockStudioDraft,parameters:((Un=t.blockStudioValidation)==null?void 0:Un.parameters)??[],preview:t.blockStudioPreview,lineageDetail:C,isSemanticBlock:Xe,running:K,onOpenBuilder:()=>ae("visual"),onOpenSource:()=>ae("source"),onDelete:()=>{var o;return t.activeBlockPath&&tn(t.activeBlockPath,((o=t.blockStudioMetadata)==null?void 0:o.name)||pe||t.activeBlockPath)},onRun:()=>void qt(),onOpenHistory:()=>{h("history"),Et(!1),!tt&&t.activeBlockPath&&W.getBlockHistory(t.activeBlockPath).then(o=>{et(o.entries),g(!0)})},t:i}):ht==="visual"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},children:[e.jsx(yr,{mode:Xe?"semantic":"custom",onModeChange:Zi,t:i}),e.jsx("div",{style:{flex:1,minHeight:0},children:Xe?e.jsx(xr,{source:t.blockStudioDraft,metadata:t.blockStudioMetadata,semanticLayer:t.semanticLayer,dbtStatus:t.blockStudioDbtStatus,domainOptions:t.authoredDomains,chartConfig:zn,onChange:Me,onMetadataChange:o=>t.blockStudioMetadata&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...o}}),onOpenAi:()=>at({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:i},`sem-${t.activeBlockPath??d}`):e.jsx(br,{source:t.blockStudioDraft,metadata:t.blockStudioMetadata,domainOptions:t.authoredDomains,chartConfig:zn,onChange:Me,onMetadataChange:o=>t.blockStudioMetadata&&n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...o}}),onConvertToDql:()=>ae("source"),t:i},`sql-${t.activeBlockPath??d}`)})]}):e.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(mt||Sn)&&e.jsx(vr,{semanticChoice:mt,databaseWarning:Sn,onDismiss:()=>{Yt(null),Xt(null)},onInsertAdvanced:()=>{if(!mt)return;const o=Bo(mt.kind==="metric"?"metric":"dimension",mt.name);Me(To(t.blockStudioDraft,o)),Yt(null)},onCreateSemantic:()=>n({type:"OPEN_NEW_BLOCK_MODAL",blockType:"semantic"}),t:i}),e.jsxs("div",{style:{height:34,flexShrink:0,display:"flex",alignItems:"center",gap:10,padding:"0 14px",borderBottom:"1px solid var(--border-subtle)",background:i.appBg},children:[e.jsx("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.activeBlockPath??Ei(t.blockStudioMetadata)}),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}}),(((Kn=t.blockStudioValidation)==null?void 0:Kn.diagnostics.filter(o=>o.severity==="error").length)??0)===0?e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:"var(--status-success)",fontWeight:600,whiteSpace:"nowrap",fontFamily:i.font},children:[e.jsx(ut,{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:i.font},children:[e.jsx(Mt,{size:12})," ",t.blockStudioValidation.diagnostics.filter(o=>o.severity==="error").length," problem",t.blockStudioValidation.diagnostics.filter(o=>o.severity==="error").length===1?"":"s"]})]}),e.jsxs("div",{style:{flex:1,minHeight:0,display:"flex",overflow:"hidden"},children:[e.jsx("div",{style:{flex:1,minWidth:0,overflow:"hidden",background:i.cellBg,borderRight:"1px solid var(--border-subtle)"},children:e.jsx(Ao,{value:t.blockStudioDraft,onChange:Me,onRun:()=>void qt(),themeMode:t.themeMode,autoFocus:!0,wrap:!1,fillHeight:!0,schema:A,dqlMode:!0,errorMessage:(Vn=(Gn=t.blockStudioValidation)==null?void 0:Gn.diagnostics.find(o=>o.severity==="error"))==null?void 0:Vn.message})}),!le&&e.jsx(lr,{source:t.blockStudioDraft,diagnostics:((Yn=t.blockStudioValidation)==null?void 0:Yn.diagnostics)??[],parameterCount:((Zn=(Xn=t.blockStudioValidation)==null?void 0:Xn.parameters)==null?void 0:Zn.length)??0,t:i})]})]}):e.jsx(ur,{dbtStatus:t.blockStudioDbtStatus,semanticStats:Cn,semanticObjectCount:Bn,databaseStats:Ft,onCreateSql:()=>Dn("custom"),onCreateSemantic:()=>Dn("semantic"),onImport:()=>Le("import"),onBuildDql:()=>at({kind:"build",initialInput:"Draft a reusable DQL block that "}),t:i})})]}),e.jsx("div",{onMouseDown:it?co:void 0,style:{gridColumn:mo,gridRow:go,display:it?"block":"none",cursor:"row-resize",background:i.headerBorder}}),e.jsxs("div",{style:{gridColumn:xo,gridRow:yo,borderTop:it?`1px solid ${i.headerBorder}`:"none",display:it?"flex":"none",flexDirection:"column",overflow:"hidden",background:i.cellBg},children:[e.jsxs("div",{style:{display:"flex",gap:14,alignItems:"center",padding:"0 16px",borderBottom:`1px solid ${i.headerBorder}`,flexWrap:"wrap"},children:[e.jsx(kt,{active:f==="results",onClick:()=>h("results"),label:"Results",t:i}),e.jsx(kt,{active:f==="parameters",onClick:()=>h("parameters"),label:`Run inputs${(((ei=(Jn=t.blockStudioValidation)==null?void 0:Jn.parameters)==null?void 0:ei.length)??0)>0?` · ${t.blockStudioValidation.parameters.length}`:""}`,t:i}),e.jsx(kt,{active:f==="lineage",onClick:()=>h("lineage"),label:"Lineage",t:i}),e.jsx(kt,{active:f==="history",onClick:()=>{h("history"),!tt&&t.activeBlockPath&&W.getBlockHistory(t.activeBlockPath).then(o=>{et(o.entries),g(!0)})},label:"History",t:i}),e.jsx(kt,{active:f==="save",onClick:()=>h("save"),label:"Metadata",t:i}),e.jsx("div",{style:{flex:1}}),t.blockStudioPreview?e.jsxs("span",{style:{fontSize:11,color:i.textMuted,fontFamily:i.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:()=>Et(!0),style:{background:"transparent",border:"none",color:i.textMuted,cursor:"pointer",fontSize:11,fontFamily:i.font,padding:"4px 6px"},title:"Hide pane",children:"▾ Hide"})]}),e.jsxs("div",{style:{flex:1,overflow:"auto"},children:[f==="results"&&(K?e.jsx(Er,{elapsedMs:me}):t.blockStudioPreview?e.jsxs("div",{style:{display:"grid",gap:12,padding:12},children:[(ni=(ti=t.blockStudioPreview.invocation)==null?void 0:ti.resolvedParameters)!=null&&ni.length?e.jsx(Lr,{values:t.blockStudioPreview.invocation.resolvedParameters,t:i}):null,e.jsx("div",{style:{fontSize:11,color:i.textMuted,fontFamily:i.fontMono},children:t.blockStudioPreview.sql}),lo==="table"?e.jsx(Ti,{result:t.blockStudioPreview.result,themeMode:t.themeMode}):e.jsx(Oo,{result:t.blockStudioPreview.result,chartConfig:t.blockStudioPreview.chartConfig,themeMode:t.themeMode})]}):D?e.jsx($r,{message:D}):e.jsx(pt,{message:"Run the block to preview results."})),f==="lineage"&&e.jsx(zr,{blockName:pe,loading:T,detail:C,graph:re,paths:B,onSelectNode:o=>{n({type:"SET_LINEAGE_FOCUS",nodeId:o}),n({type:"OPEN_LINEAGE_DRAWER",nodeId:o})},onOpenInspector:()=>{if(pe){const o=`block:${pe}`;n({type:"SET_LINEAGE_FOCUS",nodeId:o}),n({type:"OPEN_LINEAGE_DRAWER",nodeId:o})}},t:i}),f==="parameters"&&e.jsx(Rr,{parameters:((ii=t.blockStudioValidation)==null?void 0:ii.parameters)??[],values:N,onChange:(o,u)=>de(v=>({...v,[o]:u})),onReset:o=>de(u=>{const v={...u};return delete v[o],v}),onRun:()=>void qt(),running:K,t:i}),f==="history"&&e.jsx(Nr,{entries:lt,t:i}),f==="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(Wr,{currentStatus:t.blockStudioMetadata.reviewStatus??"draft",blockPath:t.activeBlockPath,onStatusChanged:o=>{t.blockStudioMetadata&&(n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,reviewStatus:o}}),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:se(t.blockStudioDraft,"status",o)}))},t:i})}),kn&&e.jsx(Fr,{result:kn,t:i}),e.jsx(Pr,{metadata:t.blockStudioMetadata,draftMetadata:nt,onChange:o=>{if(!t.blockStudioMetadata)return;n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...o}});let u=t.blockStudioDraft;typeof o.name=="string"&&(u=Bt(u,o.name)),typeof o.domain=="string"&&(u=se(u,"domain",o.domain)),typeof o.owner=="string"&&(u=se(u,"owner",o.owner)),typeof o.description=="string"&&(u=se(u,"description",o.description)),o.tags&&(u=Tt(u,o.tags)),Me(u)},t:i})]})]})]}),Qe&&mn&&e.jsx("div",{style:{position:"absolute",right:16,bottom:16},children:e.jsx("button",{onClick:()=>Et(!1),style:{background:i.btnBg,border:`1px solid ${i.btnBorder}`,borderRadius:6,color:i.textSecondary,cursor:"pointer",fontSize:12,fontFamily:i.font,padding:"8px 12px"},children:"Open Results"})}),!le&&Ye&&e.jsx("div",{onMouseDown:uo,style:{gridColumn:"4",gridRow:"1 / 4",cursor:"col-resize",background:i.headerBorder}}),Ye&&e.jsx(Vo,{t:i,title:"Block AI",subtitle:pe?`Current block: ${pe}`:"Unsaved governed block draft",expanded:xn,onToggleExpanded:()=>yn(o=>!o),onClose:()=>{Vt(!1),yn(!1)},onNewChat:()=>{x.resetThreadId(),qi(o=>o+1)},running:Wi,compact:le,ariaLabel:"Block Studio AI",style:{gridColumn:le?"1":"5",gridRow:le?Pn:"1 / 4"},children:e.jsx(Uo,{themeMode:t.themeMode,title:"Block AI",scopeHint:pe?`Current block: ${pe}`:"Block Studio project context",workspaceContext:{surface:"block-studio",task:jn==="edit"?"edit_block":"author_block",draftSessionId:d,blockStudioDraft:t.blockStudioDraft,activeBlockPath:t.activeBlockPath,domain:(oi=t.blockStudioMetadata)==null?void 0:oi.domain,importId:Ee==null?void 0:Ee.id,importCandidateId:(ri=Ee==null?void 0:Ee.candidates[0])==null?void 0:ri.id,...jn==="edit"?{mode:"edit",blockPath:t.activeBlockPath}:{}},initialMode:"block",initialInput:Ui,autoRun:Gi,threadId:x.threadId,onThreadIdChange:x.onThreadIdChange,onRunningChange:Fi,onInsertSql:(o,u)=>ro(o,{question:u??pe??"analysis",title:u}),onInsertDql:o=>{so(o)},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}:${Oi}`)}),!Ye&&!le&&e.jsx("button",{type:"button",onClick:()=>Vt(!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 ${i.btnBorder}`,background:i.btnBg,color:i.accent,cursor:"pointer",boxShadow:"0 6px 18px rgba(0, 0, 0, 0.12)"},children:e.jsx(Xo,{size:16,strokeWidth:2})}),rt&&t.blockStudioMetadata&&e.jsx(ar,{metadata:t.blockStudioMetadata,onCancel:()=>{Re.current=null,Ne(!1)},onConfirm:o=>{let u=Bt(t.blockStudioDraft,o.name);u=se(u,"owner",o.owner),n({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...t.blockStudioMetadata,...o}}),n({type:"SET_BLOCK_STUDIO_DRAFT",draft:u}),Ne(!1)},t:i}),st&&e.jsx(dr,{saving:M,onCancel:()=>He(!1),onDiscard:()=>{He(!1),Ot()},onSave:async()=>{Be.current=!0,He(!1),await en()&&(Be.current=!1,Ot())},t:i}),Z&&ye&&e.jsx(cr,{blockName:ye.name,blockPath:ye.path,deleting:ne,error:Fe,onCancel:()=>{ne||(ue(!1),We(null),Oe(null))},onConfirm:()=>void no(),t:i})]})}function sr({active:t,onClick:n,label:r,busy:s,Icon:i,variant:d="secondary",title:p}){const m=Rt[Pt(l=>l.themeMode)],x=d==="primary",P=d==="danger";return e.jsxs("button",{onClick:n,disabled:s,"aria-busy":s||void 0,title:p??r,style:{background:x?m.accent:P?`${m.error}0d`:t?`${m.accent}18`:m.btnBg,border:`1px solid ${x?m.accent:P?`${m.error}55`:t?m.accent:m.btnBorder}`,borderRadius:6,height:28,color:x?"#ffffff":P?m.error:t?m.accent:m.textSecondary,cursor:s?"wait":"pointer",display:"inline-flex",alignItems:"center",gap:6,fontSize:11,fontWeight:x?800:600,fontFamily:m.font,padding:"0 10px",whiteSpace:"nowrap",opacity:s?.7:1},children:[s?e.jsx(ot,{size:13,strokeWidth:2,"aria-hidden":"true"}):i?e.jsx(i,{size:13,strokeWidth:2,"aria-hidden":"true"}):null,s?`${r}...`:r]})}function Ze(t){return e.jsx(sr,{active:!1,...t})}function lr({source:t,diagnostics:n,parameterCount:r,t:s}){const i=t.split(`
15
+ `),d={block:"var(--text-tertiary)",parameters:"var(--accent)",query:"var(--status-success)",tests:"var(--status-warning)",visualization:"var(--cat-audit)"},p=[];i.forEach((l,f)=>{const h=l.match(/^\s*(block|parameters|query|tests|visualization)\b/);if(h&&!p.some(I=>I.label.toLowerCase().startsWith(h[1]))){const I=h[1],L=I==="block"?"Metadata":I==="parameters"?`Parameters${r?` · ${r}`:""}`:I.charAt(0).toUpperCase()+I.slice(1);p.push({label:L,line:f+1,color:d[I]??"var(--text-tertiary)"})}});const m=(t.match(/^\s*assert\b/gm)??[]).length,x=new Set((t.match(/\b(?:from|join)\s+([a-z_][\w.]*)/gi)??[]).map(l=>l.replace(/^(from|join)\s+/i,""))).size,P=n.filter(l=>l.severity==="error");return e.jsxs("div",{style:{width:208,flexShrink:0,background:s.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:s.textMuted,fontFamily:s.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:s.textMuted,padding:"2px 8px",fontFamily:s.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:s.textSecondary,fontFamily:s.font},children:l.label}),e.jsxs("span",{style:{fontSize:10,color:s.textMuted,fontFamily:s.fontMono},children:[":",l.line]})]},l.label))}),e.jsx("div",{style:{padding:"14px 14px 6px",fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:s.textMuted,fontFamily:s.font},children:"Problems"}),P.length===0?e.jsxs("div",{style:{padding:"0 14px",fontSize:11.5,color:"var(--status-success)",display:"flex",alignItems:"center",gap:6,fontFamily:s.font},children:[e.jsx(ut,{size:12})," No problems"]}):e.jsx("div",{style:{padding:"0 14px",display:"flex",flexDirection:"column",gap:5},children:P.slice(0,4).map((l,f)=>e.jsx("span",{style:{fontSize:11,color:"var(--status-error)",lineHeight:1.4,fontFamily:s.font},children:l.message},f))}),e.jsx("div",{style:{padding:"14px 14px 6px",fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:s.textMuted,fontFamily:s.font},children:"Context"}),e.jsxs("div",{style:{padding:"0 14px 16px",display:"flex",flexDirection:"column",gap:5,fontSize:11,color:s.textSecondary,fontFamily:s.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)"}}),r," parameter",r===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)"}}),x," model",x===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 kt({active:t,onClick:n,label:r,t:s}){return e.jsx("button",{type:"button",onClick:n,style:{padding:"9px 1px",fontSize:11.5,fontWeight:650,cursor:"pointer",border:"none",background:"none",fontFamily:s.font,whiteSpace:"nowrap",color:t?s.textPrimary:s.textMuted,boxShadow:t?`inset 0 -2px 0 0 ${s.accent}`:"none"},children:r})}function pi(t,n){return Io(t,{variant:n?"accent":"ghost",size:"xs",active:n})}function Dt(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 ar({metadata:t,onCancel:n,onConfirm:r,t:s}){const[i,d]=c.useState(t.name),[p,m]=c.useState(t.owner),x=!!(i.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 ${s.headerBorder}`,background:s.cellBg,boxShadow:"0 24px 70px rgba(0,0,0,.35)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:15,fontWeight:850,color:s.textPrimary},children:"Save governed block"}),e.jsx("div",{style:{marginTop:4,fontSize:11,lineHeight:1.45,color:s.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(E,{label:"Block name",t:s,children:e.jsx("input",{autoFocus:!0,value:i,onChange:P=>d(P.target.value),style:we(s)})}),e.jsx(E,{label:"Owner",t:s,children:e.jsx("input",{value:p,onChange:P=>m(P.target.value),placeholder:"analytics@company.com or team name",style:we(s)})}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:n,style:Y(s),children:"Cancel"}),e.jsx("button",{type:"button",disabled:!x,onClick:()=>x&&r({name:i.trim(),owner:p.trim()}),style:{...Ce(s),opacity:x?1:.55},children:"Save block"})]})]})})}function dr({saving:t,onSave:n,onDiscard:r,onCancel:s,t:i}){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 ${i.cellBorder}`,borderRadius:12,background:i.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:i.textPrimary,fontFamily:i.font},children:"Save this block before starting another?"}),e.jsx("div",{style:{marginTop:5,fontSize:12,lineHeight:1.5,color:i.textMuted,fontFamily:i.font},children:"Your current workspace has unsaved changes."})]}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:s,disabled:t,style:Y(i),children:"Cancel"}),e.jsx("button",{type:"button",onClick:r,disabled:t,style:{...Y(i),color:i.error},children:"Discard"}),e.jsx("button",{type:"button",onClick:()=>void n(),disabled:t,style:Ce(i),children:t?"Saving…":"Save block"})]})]})})}function cr({blockName:t,blockPath:n,deleting:r,error:s,onCancel:i,onConfirm:d,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(Kt,{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."]}),s&&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:s}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:i,disabled:r,style:Y(p),children:"Cancel"}),e.jsx("button",{type:"button",onClick:d,disabled:r,style:{...Ce(p),background:p.error,borderColor:p.error,opacity:r?.65:1},children:r?e.jsxs(e.Fragment,{children:[e.jsx(ot,{size:13,className:"dql-spin"})," Deleting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Kt,{size:13})," Delete block"]})})]})]})})}function ur({dbtStatus:t,semanticStats:n,semanticObjectCount:r,databaseStats:s,onCreateSql:i,onCreateSemantic:d,onImport:p,onBuildDql:m,t:x}){var L;const P=[{title:"Blank SQL block",detail:"Start with an empty custom query.",action:i,label:"Create",Icon:qo},{title:"Semantic block",detail:"Build directly from governed metrics.",action:d,label:"Build",Icon:Qt}],l=!!(t!=null&&t.artifacts.manifest.exists),f=(t==null?void 0:t.counts.metrics)??n.metrics,h=t?`${t.counts.models} dbt models · ${f} MetricFlow metrics`:"Waiting for dbt artifacts",I=(t==null?void 0:t.projectName)||((L=t==null?void 0:t.projectPath)==null?void 0:L.split("/").filter(Boolean).pop())||"dbt project";return e.jsxs("div",{style:{height:"100%",overflow:"auto",padding:22,display:"grid",gap:14,alignContent:"start",background:x.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:x.textPrimary,fontFamily:x.font},children:"Create DQL blocks"}),e.jsx("div",{style:{fontSize:12,color:x.textMuted,lineHeight:1.45,marginTop:5,maxWidth:560,fontFamily:x.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":x.headerBorder}`,borderRadius:8,background:l?"#2ea0430d":x.cellBg},children:[e.jsx(ut,{size:15,strokeWidth:2,color:l?"#2ea043":x.textMuted,"aria-hidden":"true"}),e.jsx("span",{style:{fontSize:11,color:l?"#2ea043":x.textMuted,fontWeight:700,fontFamily:x.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(sn,{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:Yo,onClick:m,t:x}),e.jsx(sn,{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:zi,onClick:p,t:x}),e.jsx(sn,{title:"Build manually",detail:"Use the visual semantic builder for multiple metrics, compatible dimensions, time grain, filters, and chart intent.",label:"Open builder",Icon:Qt,onClick:d,t:x})]}),e.jsxs("details",{style:wt(x),children:[e.jsx("summary",{style:Ct(x),children:"Manual options"}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))",gap:10},children:P.map($=>e.jsx(pr,{title:$.title,detail:$.detail,label:$.label,Icon:$.Icon,onClick:$.action,t:x},$.title))})]}),e.jsxs("section",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))",gap:8},children:[e.jsx(ln,{Icon:un,label:`${I} dbt`,value:h,tone:l?"success":"neutral",t:x}),e.jsx(ln,{Icon:un,label:"Database",value:`${s.tables} tables`,tone:s.tables>0?"success":"neutral",t:x}),e.jsx(ln,{Icon:Qt,label:"DQL semantic layer",value:`${r} objects`,tone:r>0?"success":"neutral",t:x})]})]})}function sn({title:t,detail:n,label:r,Icon:s,onClick:i,t:d}){return e.jsxs("button",{onClick:i,style:{border:`1px solid ${d.accent}`,borderRadius:8,background:d.cellBg,color:d.textPrimary,cursor:"pointer",display:"grid",gridTemplateColumns:"42px minmax(0, 1fr) auto",gap:12,alignItems:"center",padding:16,minHeight:104,textAlign:"left",fontFamily:d.font,boxShadow:`inset 0 0 0 1px ${d.accent}22`},children:[e.jsx("span",{style:{width:42,height:42,borderRadius:8,display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${d.accent}18`,color:d.accent},children:e.jsx(s,{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:d.textPrimary},children:t}),e.jsx("span",{style:{fontSize:12,color:d.textMuted,lineHeight:1.4},children:n})]}),e.jsx("span",{style:{color:"#ffffff",background:d.accent,borderRadius:6,padding:"7px 10px",fontSize:11,fontWeight:800,whiteSpace:"nowrap"},children:r})]})}function pr({title:t,detail:n,label:r,Icon:s,onClick:i,t:d}){return e.jsxs("button",{onClick:i,style:{textAlign:"left",background:d.cellBg,border:`1px solid ${d.headerBorder}`,borderRadius:8,padding:12,cursor:"pointer",color:d.textPrimary,display:"grid",gridTemplateColumns:"30px minmax(0, 1fr)",gap:10,minHeight:94,fontFamily:d.font,alignItems:"start"},children:[e.jsx("span",{style:{width:30,height:30,borderRadius:7,display:"inline-flex",alignItems:"center",justifyContent:"center",background:`${d.accent}14`,color:d.accent},children:e.jsx(s,{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:d.textPrimary},children:t}),e.jsx("span",{style:{fontSize:11,color:d.textMuted,lineHeight:1.35},children:n}),e.jsx("span",{style:{color:d.accent,fontSize:11,fontWeight:800},children:r})]})]})}function ln({Icon:t,label:n,value:r,tone:s,t:i}){const d=s==="success"?"#2ea043":i.textMuted;return e.jsxs("div",{style:{border:`1px solid ${i.headerBorder}`,borderRadius:8,background:i.cellBg,padding:"9px 10px",display:"flex",alignItems:"center",gap:8,minWidth:0},children:[e.jsx("span",{style:{color:d,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:i.textMuted,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),e.jsx("span",{style:{fontSize:12,color:i.textPrimary,fontWeight:700,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r})]})]})}function fr({source:t,databaseStats:n,semanticCount:r,onChange:s,onOpenExplorer:i,onOpenAi:d,t:p}){const m=l=>{var f;return((f=t.match(new RegExp(`\\b${l}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:f[1])??""},x=l=>{var f;return(((f=t.match(new RegExp(`\\b${l}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i")))==null?void 0:f[1].match(/"([^"]*)"/g))??[]).map(h=>h.slice(1,-1))},P=[{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:i,style:Y(p),children:[n.tables," database tables"]}),e.jsx("button",{type:"button",onClick:d,style:Y(p),children:"Review with AI"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(230px, 1fr))",gap:10},children:[e.jsx(E,{label:"Business outcome",t:p,children:e.jsx(It,{value:m("businessOutcome"),onChange:l=>s(se(t,"businessOutcome",l)),placeholder:"Decision or outcome this block supports",style:we(p)})}),e.jsx(E,{label:"Agent guidance",t:p,children:e.jsx(It,{value:m("llmContext"),onChange:l=>s(se(t,"llmContext",l)),placeholder:"When to use this block",style:we(p)})}),P.map(l=>e.jsx(hr,{label:l.label,hint:l.hint,values:x(l.key),onChange:f=>s(Do(t,l.key,f)),t:p},l.key)),e.jsx(E,{label:"Rules and caveats",t:p,children:e.jsx(It,{value:m("caveats"),onChange:l=>s(se(t,"caveats",l)),placeholder:"Known limitation or interpretation rule",style:we(p)})})]}),e.jsxs("div",{style:{fontSize:10,color:p.textMuted},children:["Available authoring context: ",r," semantic objects, ",n.schemas," schemas, ",n.columns," columns. SQL completion uses the same loaded catalog."]})]})}function hr({label:t,hint:n,values:r,onChange:s,t:i}){const[d,p]=c.useState(""),m=()=>{const x=d.split(",").map(P=>P.trim()).filter(Boolean);x.length>0&&s([...r,...x]),p("")};return e.jsx(E,{label:t,t:i,children:e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:5,padding:6,minHeight:36,border:`1px solid ${i.cellBorder}`,borderRadius:6,background:i.cellBg},children:[r.map(x=>e.jsxs("button",{type:"button",onClick:()=>s(r.filter(P=>P!==x)),title:"Remove",style:{...Dt(i,!0),border:"none",cursor:"pointer"},children:[x," ×"]},x)),e.jsx("input",{value:d,onChange:x=>p(x.target.value),onKeyDown:x=>{(x.key==="Enter"||x.key===",")&&(x.preventDefault(),m())},onBlur:m,placeholder:r.length?"Add another…":n,style:{minWidth:120,flex:1,border:"none",outline:"none",background:"transparent",color:i.textPrimary,fontSize:11,fontFamily:i.font}})]})})}function Pi({source:t,kind:n,onChange:r,t:s}){const i=c.useMemo(()=>Lo(t),[t]),[d,p]=c.useState(""),[m,x]=c.useState(""),[P,l]=c.useState(!0),[f,h]=c.useState("dynamic"),[I,L]=c.useState("auto"),$=rn(m,d),J=I==="auto"?$:I,_=we(s),k=()=>{d.trim()&&(r(di(t,{name:d,type:J,required:P&&!m.trim(),defaultText:m,policy:f})),p(""),x(""),l(!0),h("dynamic"),L("auto"))};return e.jsx(fe,{title:"Runtime parameters",t:s,children:e.jsxs("div",{style:{display:"grid",gap:10},children:[e.jsxs("div",{style:{fontSize:11,color:s.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."]}),i.length>0&&e.jsx("div",{style:{display:"grid",gap:7},children:i.map(S=>{var he;const te=Eo(S),X=A=>r(di(t,{name:S.name,type:A.type??S.type,required:A.required??S.required,defaultText:A.defaultText??te,policy:A.policy??S.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 ${s.cellBorder}`,borderRadius:7,background:s.cellBg},children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:11,fontWeight:800,color:s.textPrimary},children:S.name}),e.jsxs("div",{style:{fontSize:10,color:s.textMuted},children:[((he=S.binding)==null?void 0:he.kind)??"declared value"," · ",S.required?"required":"has default"]})]}),e.jsx("select",{"aria-label":`${S.name} type`,value:S.type,onChange:A=>X({type:A.target.value}),style:_,children:fi.map(A=>e.jsx("option",{value:A,children:A},A))}),S.type==="boolean"?e.jsxs("select",{"aria-label":`${S.name} default`,value:te,onChange:A=>X({defaultText:A.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":`${S.name} default`,value:te,onChange:A=>{const K=A.target.value,G=S.type===rn(te,S.name);X({defaultText:K,required:K.trim()?!1:S.required,...G?{type:rn(K,S.name)}:{}})},placeholder:S.type.endsWith("[]")?"West, East":S.required?"Required value":"Default value",style:_}),e.jsx("select",{"aria-label":`${S.name} policy`,value:S.policy,onChange:A=>X({policy:A.target.value}),style:_,children:mr.map(A=>e.jsx("option",{value:A,children:A},A))}),e.jsx("button",{type:"button",onClick:()=>r($o(t,S.name)),title:`Remove ${S.name}`,style:{border:"none",background:"transparent",color:s.error,cursor:"pointer",fontSize:16,padding:"3px 5px"},children:"×"})]},S.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 ${s.btnBorder}`,borderRadius:7,background:s.appBg},children:[e.jsx("input",{"aria-label":"New parameter name",value:d,onChange:S=>p(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),k())},placeholder:"region_set",style:_}),e.jsx("input",{"aria-label":"New parameter default",value:m,onChange:S=>{x(S.target.value),S.target.value.trim()&&l(!1)},onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),k())},placeholder:"Central, East or 2026-01-01",style:_}),e.jsxs("select",{"aria-label":"New parameter type",value:I,onChange:S=>L(S.target.value),style:_,children:[e.jsxs("option",{value:"auto",children:["Auto · ",$]}),fi.map(S=>e.jsx("option",{value:S,children:S},S))]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:5,color:s.textSecondary,fontSize:11,whiteSpace:"nowrap"},children:[e.jsx("input",{type:"checkbox",checked:P&&!m.trim(),onChange:S=>l(S.target.checked)})," Required"]}),e.jsx("button",{type:"button",onClick:k,disabled:!d.trim(),style:{...Ce(s),opacity:d.trim()?1:.5},children:"Add"})]}),e.jsxs("div",{style:{fontSize:10,color:s.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 fi=["string","number","boolean","date","string[]","number[]","date[]"],mr=["dynamic","static","business","derived","optional","ambiguous_review_required"];function gr({metadata:t,source:n,parameters:r,preview:s,lineageDetail:i,isSemanticBlock:d,running:p,onOpenBuilder:m,onOpenSource:x,onDelete:P,onRun:l,onOpenHistory:f,t:h}){var V,me,ee,N,de;const I=((t==null?void 0:t.reviewStatus)??"").toLowerCase()==="certified",L=(t==null?void 0:t.name)||"block",$=d?ji(n):null,J=((me=(V=n.match(/query\s*=\s*"""([\s\S]*?)"""/i))==null?void 0:V[1])==null?void 0:me.trim())??"",_=$?Array.from(new Set([...$.dimensions,...$.timeDimension?[$.timeDimension]:[],...$.metrics])):$i(J),k=(n.match(/^\s*assert\b.*$/gm)??[]).map(M=>M.trim()),S=((ee=i==null?void 0:i.incoming)==null?void 0:ee.length)??0,te=((N=i==null?void 0:i.outgoing)==null?void 0:N.length)??0,[X,he]=c.useState(!1),A=((i==null?void 0:i.incoming)??[]).map(M=>{var U;return(U=M.node)==null?void 0:U.name}).filter(Boolean).slice(0,3),K=((i==null?void 0:i.outgoing)??[]).map(M=>{var U;return(U=M.node)==null?void 0:U.name}).filter(Boolean).slice(0,3),G={fontSize:11,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:h.textMuted,marginBottom:8,fontFamily:h.font},D=(M,U=!1)=>e.jsx("span",{style:{padding:"3px 9px",borderRadius:999,border:`1px solid ${U?`${h.accent}59`:h.headerBorder}`,background:U?"var(--accent-dim)":"var(--bg-1)",color:U?h.accent:h.textSecondary,fontFamily:h.fontMono,fontWeight:U?600:400,fontSize:11.5},children:M},M),Q=e.jsx("span",{style:{color:h.textMuted,fontSize:11},children:"→"}),F=[["Last run",s!=null&&s.result.executionTime?`${(s.result.executionTime/1e3).toFixed(1)}s`:"Not run yet"],["Rows",s?String(s.result.rowCount??s.result.rows.length):"—"],["Used in",te>0?`${te} downstream`:"—"],["Tests",k.length>0?`${k.length} declared`:"None yet"]];return e.jsx("div",{style:{height:"100%",overflow:"auto",background:h.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:h.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:I?"var(--status-success-bg)":"var(--accent-dim)",color:I?"var(--status-success)":h.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border-subtle)"},children:e.jsx(Qt,{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:h.textPrimary,fontFamily:h.fontMono,letterSpacing:"-0.01em"},children:L}),t!=null&&t.reviewStatus?e.jsx(Di,{status:t.reviewStatus,t:h}):null]}),e.jsx("div",{style:{fontSize:12,color:h.textMuted,marginTop:4},children:[t==null?void 0:t.domain,t!=null&&t.folderPath?`folder: ${t.folderPath}`:null,t==null?void 0:t.owner,...(de=t==null?void 0:t.tags)!=null&&de.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:m,style:{display:"inline-flex",alignItems:"center",gap:7,height:32,padding:"0 14px",borderRadius:8,border:"none",background:h.accent,color:"#fff",fontSize:12.5,fontWeight:650,cursor:"pointer",fontFamily:h.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)"},children:[e.jsx(No,{size:13,strokeWidth:1.75})," Open in builder"]}),e.jsxs("button",{type:"button",onClick:l,disabled:p,style:{display:"inline-flex",alignItems:"center",gap:6,height:32,padding:"0 13px",borderRadius:8,border:`1px solid ${h.headerBorder}`,background:h.cellBg,color:h.textSecondary,fontSize:12.5,fontWeight:600,cursor:"pointer",fontFamily:h.font,opacity:p?.7:1},children:[p?e.jsx(ot,{size:12,style:{animation:"dql-agent-run-spin 0.8s linear infinite"}}):e.jsx(Mi,{size:11,fill:"currentColor"})," Run"]}),e.jsx("button",{type:"button","aria-label":`Delete ${L}`,title:"Delete block",onClick:P,style:{width:32,height:32,borderRadius:8,border:`1px solid ${h.error}55`,background:`${h.error}0d`,color:h.error,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:e.jsx(Kt,{size:14})}),e.jsx("button",{type:"button",title:"History and metadata",onClick:f,style:{width:32,height:32,borderRadius:8,border:`1px solid ${h.headerBorder}`,background:h.cellBg,color:h.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:e.jsx(Ho,{size:15})})]})]}),t!=null&&t.description?e.jsx("div",{style:{fontSize:13.5,lineHeight:1.6,color:h.textSecondary,maxWidth:640},children:t.description}):null,e.jsx("div",{style:{display:"flex",border:"1px solid var(--border-subtle)",borderRadius:10,background:h.cellBg,overflow:"hidden"},children:F.map(([M,U],ge)=>e.jsxs("div",{style:{flex:1,padding:"12px 16px",borderRight:ge<F.length-1?"1px solid var(--border-subtle)":"none"},children:[e.jsx("div",{style:{fontSize:10,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:h.textMuted},children:M}),e.jsx("div",{style:{fontSize:14,fontWeight:650,color:h.textPrimary,marginTop:3},children:U})]},M))}),e.jsxs("div",{children:[e.jsx("div",{style:G,children:"Outputs"}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:_.length>0?_.map(M=>e.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11.5,padding:"4px 10px",borderRadius:999,background:"var(--accent-dim)",color:h.accent,border:`1px solid ${h.accent}33`,fontFamily:h.fontMono},children:M},M)):e.jsx("span",{style:{fontSize:11.5,color:h.textMuted},children:"Open the builder to define outputs."})})]}),e.jsxs("div",{children:[e.jsx("div",{style:G,children:"Parameters"}),e.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:9,overflow:"hidden",background:h.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:h.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"})]}),r.length===0?e.jsx("div",{style:{padding:"9px 12px",fontSize:12,color:h.textMuted},children:"No parameters — this block always runs the same way."}):r.map((M,U)=>e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1.2fr 0.8fr 1fr 0.9fr",gap:8,padding:"8px 12px",borderBottom:U<r.length-1?"1px solid var(--border-subtle)":"none",fontSize:12,alignItems:"center"},children:[e.jsx("span",{style:{fontFamily:h.fontMono,fontWeight:600,color:h.textPrimary},children:M.name}),e.jsx("span",{style:{color:h.textSecondary},children:M.type}),e.jsx("span",{style:{fontFamily:h.fontMono,color:M.default!==void 0&&M.default!==null&&M.default!==""?"var(--status-warning)":h.textMuted},children:M.default!==void 0&&M.default!==null&&M.default!==""?JSON.stringify(M.default):M.required?"required":"—"}),e.jsx("span",{style:{color:h.textMuted},children:M.policy})]},M.name))]})]}),e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[e.jsx("span",{style:{...G,marginBottom:0},children:"DQL source"}),e.jsxs("button",{type:"button",onClick:x,style:{display:"inline-flex",alignItems:"center",gap:5,border:"none",background:"none",color:h.accent,fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:h.font,padding:0},children:["Open in DQL Source ",e.jsx(cn,{size:11,strokeWidth:2})]})]}),e.jsx("pre",{style:{margin:0,border:"1px solid var(--border-subtle)",background:h.cellBg,borderRadius:9,padding:"13px 15px",fontSize:11.5,lineHeight:1.65,fontFamily:h.fontMono,whiteSpace:"pre",overflowX:"auto",color:h.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:G,children:"Tests"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:k.length>0?k.map(M=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12},children:[e.jsx(ut,{size:13,color:"var(--status-success)",strokeWidth:2,style:{flexShrink:0}}),e.jsx("span",{style:{fontFamily:h.fontMono,color:h.textSecondary},children:M})]},M)):e.jsx("span",{style:{fontSize:11.5,color:h.textMuted},children:"No tests yet — add assertions in the builder before certification."})})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>he(M=>!M),style:{display:"flex",alignItems:"center",gap:6,border:"none",background:"none",cursor:"pointer",padding:0,fontFamily:h.font,marginBottom:8},children:[e.jsx(cn,{size:11,color:h.textMuted,strokeWidth:2,style:{transform:X?"rotate(90deg)":"none",transition:"transform 0.12s"}}),e.jsx("span",{style:{fontSize:11,fontWeight:700,letterSpacing:"0.05em",textTransform:"uppercase",color:h.textMuted},children:"Lineage"}),X?null:e.jsxs("span",{style:{fontSize:10.5,color:h.textMuted},children:[S," upstream · ",te," downstream"]})]}),X?e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap",fontSize:11.5,animation:"dql-agent-fadein 0.18s ease-out"},children:[A.length>0?A.map(M=>D(M)):D("no upstream"),Q,D(L,!0),Q,K.length>0?K.map(M=>D(M)):D("no downstream yet")]}):null]})]})]})})}function xr({source:t,metadata:n,semanticLayer:r,dbtStatus:s,domainOptions:i,chartConfig:d,onChange:p,onMetadataChange:m,onOpenAi:x,onSetupRuntime:P,t:l}){const f=ji(t),h={...f,filters:f.requestedFilters},[I,L]=c.useState([]),[$,J]=c.useState(!1),[_,k]=c.useState(null),[S,te]=c.useState(null),[X,he]=c.useState(0);c.useEffect(()=>{let a=!1;if(h.metrics.length===0){L([]),k(null),te(null),J(!1);return}return L([]),k(null),J(!0),te(null),W.getCompatibility(h.metrics).then(w=>{a||(k(w),L(w.dimensions))}).catch(w=>{a||(L([]),te(w instanceof Error?w.message:String(w)))}).finally(()=>{a||J(!1)}),()=>{a=!0}},[r.dimensions,h.metrics.join("|"),X]);const A=new Set(I.flatMap(a=>[a.reference??a.name,a.name])),K=new Map(I.flatMap(a=>[[a.reference??a.name,a.qualifiedName??void 0],[a.name,a.qualifiedName??void 0]])),G=new Map(((_==null?void 0:_.incompatible)??[]).map(a=>[a.name,or(a.reason)])),D=new Map(I.flatMap(a=>[[a.reference??a.name,a],[a.name,a]])),Q=Array.from(new Map([...r.dimensions,...r.timeDimensions].map(a=>{const w=a.reference??a.name;return[w,{...a,name:w}]})).values()),F=new Map(Q.flatMap(a=>[[a.name,a],[a.reference??a.name,a]])),V=I.map(a=>{const w=a.reference??a.name;return{...F.get(w)??F.get(a.name),...a,name:w}}),me=V.filter(a=>a.isTimeDimension||a.type==="time"),ee=hn(l),[N,de]=c.useState(""),[M,U]=c.useState(""),ge=c.useMemo(()=>new Map(r.metrics.map(a=>[a.name,a])),[r.metrics]),Te=c.useMemo(()=>new Map([...Q,...V].flatMap(a=>[[a.name,a],[a.reference??a.name,a]])),[Q,V]),Se=c.useMemo(()=>hi(r.metrics,N),[r.metrics,N]),ce=c.useMemo(()=>hi(V,M),[V,M]),_e=wi(t,"tests"),ie=Array.from(new Set([...h.dimensions,...h.timeDimension?[h.timeDimension]:[],...h.metrics])),Ie=(a,w)=>{m({[a]:w}),p(a==="name"?Bt(t,w):se(t,a,w))},ze=a=>{const w=h.metrics.includes(a)?h.metrics.filter(Z=>Z!==a):[...h.metrics,a];p(vi(t,w))},xe=a=>p(Si(t,"dimensions",a)),Pe=a=>{const w=h.dimensions.includes(a)?h.dimensions.filter(Z=>Z!==a):[...h.dimensions,a];xe(w)};return c.useEffect(()=>{if(!_||h.metrics.length===0)return;const a=Mo(t,Array.from(A));a!==t&&p(a)},[_,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(Ri,{metadata:n,domains:i,onTextChange:Ie,onFolderChange:a=>m({folderPath:a}),onTagsChange:a=>{m({tags:a}),p(Tt(t,a))},t:l}),e.jsxs(fe,{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 · ",h.metrics.length," selected"]}),$&&e.jsx("span",{style:{fontSize:10,color:l.textMuted},children:"Checking compatibility…"})]}),e.jsx(mi,{kind:"metric",total:r.metrics.length,search:N,onSearchChange:de,matches:Se,pool:r.metrics,selected:h.metrics,resolveLabel:a=>{var w;return((w=ge.get(a))==null?void 0:w.label)||a},onToggle:ze,compatible:a=>{var w,Z,ue,ye;return((Z=(w=ge.get(a))==null?void 0:w.execution)==null?void 0:Z.status)!=="requires_setup"&&((ye=(ue=ge.get(a))==null?void 0:ue.execution)==null?void 0:ye.status)!=="unsupported"},t:l}),r.metrics.some(a=>a.execution&&a.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:P,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 ",ir[_.engine]??_.engine]}),_.degraded&&e.jsx("span",{style:{color:"var(--status-warning)"},children:_.degraded})]}),S&&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(Mt,{size:14,style:{flexShrink:0}}),e.jsxs("span",{style:{flex:1},children:["Could not verify governed dimensions: ",S,". Dimension selection is paused so an unapproved join cannot be saved."]}),e.jsx("button",{type:"button",onClick:()=>he(a=>a+1),style:Y(l),children:"Retry"})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 150px",gap:8},children:[e.jsx(E,{label:"Time dimension",t:l,children:e.jsxs("select",{disabled:h.metrics.length===0||$||!!S,value:h.timeDimension,onChange:a=>p(ai(t,"time_dimension",a.target.value)),style:{...ee,opacity:h.metrics.length===0||$||S?.6:1},children:[e.jsx("option",{value:"",children:"None"}),me.map(a=>e.jsxs("option",{value:a.reference??a.name,children:[a.label||a.name," · ",a.name]},a.reference??a.name))]})}),e.jsx(E,{label:"Grain",t:l,children:e.jsxs("select",{value:h.granularity,onChange:a=>p(ai(t,"granularity",a.target.value)),style:ee,children:[e.jsx("option",{value:"",children:"None"}),rr(h.timeDimension,D,r.timeDimensions).map(a=>e.jsx("option",{value:a,children:a},a))]})})]}),r.metrics.length===0&&(r.loading?e.jsxs("div",{role:"status",style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:l.textMuted,lineHeight:1.45},children:[e.jsx(ot,{size:14,className:"dql-spin"}),"Loading ",((s==null?void 0:s.counts.metrics)??0).toLocaleString()," semantic metrics from parsed dbt artifacts… Large catalogs continue loading in the background."]}):((s==null?void 0:s.counts.metrics)??0)>0||s!=null&&s.artifacts.semanticManifest.exists?e.jsxs("div",{role:"alert",style:{fontSize:12,color:"var(--status-warning)",lineHeight:1.45},children:["dbt artifacts contain ",((s==null?void 0:s.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."})),h.metrics.length>1&&_&&I.length===0&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,color:"#d29922",fontSize:11,lineHeight:1.4},children:[e.jsx(Mt,{size:14})," These metrics do not expose a common dimension or join path.",e.jsx("button",{type:"button",onClick:x,style:Y(l),children:"Resolve with AI"})]})]}),e.jsxs(fe,{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(E,{label:"Type",t:l,children:e.jsxs("select",{value:d.chart??"table",onChange:a=>p(Ae(t,{...d,chart:a.target.value})),style:ee,children:[e.jsx("option",{value:"table",children:"Table"}),Ii.map(a=>e.jsx("option",{value:a.value,children:a.label},a.value))]})}),e.jsx(E,{label:"X axis",t:l,children:e.jsxs("select",{value:d.x??"",onChange:a=>p(Ae(t,{...d,x:a.target.value})),style:ee,children:[e.jsx("option",{value:"",children:"Auto"}),ie.map(a=>e.jsx("option",{value:a,children:Ke(a)},a))]})}),e.jsx(E,{label:"Y axis",t:l,children:e.jsxs("select",{value:d.y??"",onChange:a=>p(Ae(t,{...d,y:a.target.value})),style:ee,children:[e.jsx("option",{value:"",children:"Auto"}),ie.map(a=>e.jsx("option",{value:a,children:Ke(a)},a))]})}),e.jsx(E,{label:"Series / color",t:l,children:e.jsxs("select",{value:d.color??"",onChange:a=>p(Ae(t,{...d,color:a.target.value})),style:ee,children:[e.jsx("option",{value:"",children:"None"}),ie.map(a=>e.jsx("option",{value:a,children:Ke(a)},a))]})})]}),e.jsx(E,{label:"Title",t:l,children:e.jsx("input",{value:d.title??"",onChange:a=>p(Ae(t,{...d,title:a.target.value})),placeholder:"Chart title",style:ee})})]}),e.jsx(fe,{title:"Dimensions",hint:"Governed group-bys checked against the metric's join path.",t:l,children:h.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."}):$?e.jsxs("div",{role:"status",style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:l.textMuted},children:[e.jsx(ot,{size:14,className:"dql-spin"}),"Checking common governed dimensions…"]}):S?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(mi,{kind:"dimension",total:V.length,search:M,onSearchChange:U,matches:ce,pool:V,selected:h.dimensions,resolveLabel:a=>{var w;return((w=Te.get(a))==null?void 0:w.label)||a},resolveMachineName:a=>{var w;return K.get(a)??((w=Te.get(a))==null?void 0:w.name)??a},reasonFor:a=>G.get(a),onToggle:Pe,compatible:a=>A.has(a),disabled:h.metrics.length===0||$||!!S,emptyHint:$?"Checking common governed dimensions…":S?"Retry compatibility before selecting dimensions.":"Choose a metric first; dimensions are checked against its governed join path.",t:l})}),e.jsxs(fe,{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([...h.dimensions,...h.timeDimension?[h.timeDimension]:[]])).map(a=>{var Z;const w=h.filters.includes(a);return e.jsx("button",{type:"button",onClick:()=>p(zo(t,w?h.filters.filter(ue=>ue!==a):[...h.filters,a])),style:Dt(l,w),children:((Z=Te.get(a))==null?void 0:Z.label)||a},a)})}),e.jsx("div",{style:{fontSize:10,color:l.textMuted,marginTop:8},children:h.dimensions.length===0&&!h.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."}),h.filters.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:h.filters.map(a=>e.jsxs("span",{style:Dt(l,!0),children:[Ke(a)," · dynamic"]},a))})]}),e.jsx(Pi,{source:t,kind:"semantic",onChange:p,t:l}),e.jsx(fe,{title:`Output fields${ie.length?` · ${ie.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:ie.length>0?ie.map(a=>e.jsx("span",{style:Dt(l,!0),children:Ke(a)},a)):e.jsx("span",{style:{fontSize:11,color:l.textMuted},children:"Select metrics and dimensions to define outputs."})})}),e.jsx(fe,{title:"Tests",hint:"Assertions checked on every run and required for certification.",t:l,children:e.jsx(It,{multiline:!0,value:_e,onChange:a=>p(Ci(t,"tests",a)),placeholder:`assert row_count >= 1
16
+ assert total_revenue >= 0`,style:{...ee,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 Ri({metadata:t,domains:n,onTextChange:r,onFolderChange:s,onTagsChange:i,t:d}){const p=nr(t==null?void 0:t.domain,n),m=hn(d);return e.jsx(fe,{title:"Details",hint:"Name, ownership, and where this block lives.",t:d,children:e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[e.jsx(E,{label:"Block name",t:d,children:e.jsx("input",{value:(t==null?void 0:t.name)??"",onChange:x=>r("name",x.target.value),style:{...m,fontFamily:d.fontMono}})}),e.jsx(E,{label:"Domain",t:d,children:e.jsxs("select",{"aria-label":"Block domain",value:(t==null?void 0:t.domain)??"",onChange:x=>r("domain",x.target.value),style:m,children:[e.jsx("option",{value:"",children:"Select domain…"}),p.map(x=>e.jsx("option",{value:x.value,disabled:x.disabled,children:x.label},x.value))]})}),e.jsx(E,{label:"Owner",t:d,children:e.jsx("input",{value:(t==null?void 0:t.owner)??"",onChange:x=>r("owner",x.target.value),placeholder:"Required to save",style:m})}),e.jsx(E,{label:"Tags",t:d,children:e.jsx(Bi,{values:(t==null?void 0:t.tags)??[],onChange:i,placeholder:"finance, emea",style:m})}),e.jsxs("div",{style:{gridColumn:"1 / -1"},children:[e.jsx(E,{label:"Folder (optional)",t:d,children:e.jsx("input",{"aria-label":"Block folder",value:(t==null?void 0:t.folderPath)??"",onChange:x=>s(x.target.value),placeholder:"executive/monthly",style:{...m,fontFamily:d.fontMono}})}),e.jsx("div",{style:{marginTop:5,fontSize:10,color:d.textMuted,fontFamily:d.fontMono},children:Ei(t)})]}),e.jsx("div",{style:{gridColumn:"1 / -1"},children:e.jsx(E,{label:"Description",t:d,children:e.jsx("input",{value:(t==null?void 0:t.description)??"",onChange:x=>r("description",x.target.value),placeholder:"What business question does this answer?",style:m})})})]})})}function hi(t,n){const r=n.trim().toLowerCase();return r.length<2?[]:t.filter(s=>[s.name,s.label,s.description,s.domain].filter(Boolean).some(i=>i.toLowerCase().includes(r))).slice(0,30)}function mi({kind:t,total:n,search:r,onSearchChange:s,matches:i,pool:d=[],selected:p,resolveLabel:m,resolveMachineName:x,reasonFor:P,onToggle:l,compatible:f=()=>!0,disabled:h=!1,emptyHint:I,t:L}){const[$,J]=c.useState(!1),_=c.useRef(null),k=c.useRef(null),S=t==="metric"?"measures":"dimensions",te=t==="metric"?"Σ":"ab",X=t==="metric"?"var(--accent)":"var(--status-success)",he=t==="metric"?"var(--accent-dim)":"var(--status-success-bg)",A=r.trim().length>=2,K=A?i:d.filter(D=>!p.includes(D.name)).slice(0,8),G=()=>{J(!1),s("")};return c.useEffect(()=>{if(!$)return;requestAnimationFrame(()=>{var F;return(F=_.current)==null?void 0:F.focus()});const D=F=>{k.current&&!k.current.contains(F.target)&&G()},Q=F=>{F.key==="Escape"&&G()};return document.addEventListener("mousedown",D),document.addEventListener("keydown",Q),()=>{document.removeEventListener("mousedown",D),document.removeEventListener("keydown",Q)}},[$]),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginTop:9},children:[p.map(D=>e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11.5,padding:"4px 9px",borderRadius:999,background:he,color:X,border:`1px solid ${t==="metric"?"rgba(107,93,211,0.2)":"rgba(46,139,87,0.25)"}`,fontFamily:L.fontMono},children:[t==="metric"?`Σ ${m(D)}`:m(D),e.jsx("button",{type:"button",onClick:()=>l(D),title:`Remove ${m(D)}`,style:{border:"none",background:"none",color:X,cursor:"pointer",padding:0,fontSize:12,lineHeight:1,fontFamily:"inherit"},children:"×"})]},D)),e.jsxs("span",{ref:k,style:{position:"relative"},children:[e.jsxs("button",{type:"button",disabled:h,onClick:()=>J(D=>!D),title:h?I:`Add ${t}`,style:{border:"1.5px dashed var(--border-strong)",background:"transparent",borderRadius:999,padding:"4px 10px",fontSize:11,fontFamily:L.font,color:h?L.textMuted:L.textSecondary,cursor:h?"not-allowed":"pointer",opacity:h?.6:1},children:["+ Add ",t]}),$&&!h?e.jsxs("div",{style:{position:"absolute",right:0,top:30,zIndex:40,width:300,background:L.cellBg,border:`1px solid ${L.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(Ro,{size:12,color:L.textMuted,style:{flexShrink:0}}),e.jsx("input",{ref:_,value:r,onChange:D=>s(D.target.value),placeholder:`Search ${n.toLocaleString()} ${S}…`,style:{flex:1,border:"none",background:"none",outline:"none",fontSize:12,fontFamily:L.font,color:L.textPrimary,minWidth:0}}),e.jsx("button",{type:"button",onClick:G,style:{border:"none",background:"none",color:L.textMuted,cursor:"pointer",padding:0,fontSize:13,lineHeight:1},children:"×"})]}),e.jsx("div",{style:{maxHeight:208,overflow:"auto"},children:K.length===0?e.jsx("div",{style:{padding:10,fontSize:11,color:L.textMuted},children:A?`No ${S} match “${r}”.`:`No more ${S} to add.`}):K.map(D=>{const Q=p.includes(D.name),F=f(D.name),V=(x==null?void 0:x(D.name))??D.name,me=V!==(D.label||D.name),ee=F?void 0:(P==null?void 0:P(D.name))??"Not compatible with every selected metric";return e.jsxs("button",{type:"button",disabled:!F,onClick:()=>{l(D.name),Q||G()},title:ee??D.description??V,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 10px",border:"none",background:Q?he:"none",cursor:F?"pointer":"not-allowed",textAlign:"left",fontFamily:L.font,borderBottom:"1px solid var(--border-subtle)",opacity:F?1:.5},children:[e.jsx("span",{style:{flexShrink:0,width:16,height:16,borderRadius:4,background:he,color:X,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:t==="metric"?10:9,fontWeight:700,fontFamily:L.fontMono},children:te}),e.jsxs("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:1,overflow:"hidden"},children:[e.jsx("span",{style:{fontSize:12,fontFamily:L.font,color:L.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:D.label||D.name}),me?e.jsx("span",{style:{fontSize:10,fontFamily:L.fontMono,color:L.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:V}):null]}),e.jsx("span",{style:{flexShrink:0,fontSize:10,color:L.textMuted},children:D.domain||D.type||""})]},D.name)})}),e.jsx("div",{style:{padding:"6px 10px",background:"var(--bg-1)",fontSize:10,color:L.textMuted},children:A?`${K.length} match${K.length===1?"":"es"} · certified shown first`:`Showing top ${K.length} of ${n.toLocaleString()} · type to search all`})]}):null]})]})}function yr({mode:t,onModeChange:n,t:r}){const s=[{key:"semantic",label:"Semantic picker"},{key:"custom",label:"Raw SQL"}];return e.jsx("div",{style:{flexShrink:0,borderBottom:`1px solid ${r.headerBorder}`,background:r.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:r.textMuted},children:"Query"}),e.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:2,padding:2,border:`1px solid ${r.headerBorder}`,borderRadius:8,background:r.cellBg},children:s.map(i=>{const d=i.key===t;return e.jsx("button",{type:"button",onClick:()=>n(i.key),style:{border:"none",borderRadius:6,padding:"5px 12px",fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:r.font,background:d?"var(--accent-dim)":"transparent",color:d?r.accent:r.textMuted},children:i.label},i.key)})}),e.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:t==="semantic"?"Pick governed metrics & dimensions — they compile to DQL.":"Write SQL and convert it into a governed DQL script."})]})})}function br({source:t,metadata:n,domainOptions:r,chartConfig:s,onChange:i,onMetadataChange:d,onConvertToDql:p,t:m}){var J,_;const x=hn(m),P=((_=(J=t.match(/query\s*=\s*"""([\s\S]*?)"""/i))==null?void 0:J[1])==null?void 0:_.trim())??"",[l,f]=c.useState(P),h=$i(l),I=wi(t,"tests"),L=k=>{f(k),i(ki(t,k))},$=(k,S)=>{d({[k]:S}),i(k==="name"?Bt(t,S):se(t,k,S))};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(Ri,{metadata:n,domains:r,onTextChange:$,onFolderChange:k=>d({folderPath:k}),onTagsChange:k=>{d({tags:k}),i(Tt(t,k))},t:m}),e.jsxs(fe,{title:"Query",hint:"Write raw SQL — it compiles into a governed DQL script.",t:m,children:[e.jsx("textarea",{rows:7,value:l,onChange:k=>L(k.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
+ category,
18
+ SUM(revenue) AS revenue
19
+ 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(fe,{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(E,{label:"Type",t:m,children:e.jsxs("select",{value:s.chart??"table",onChange:k=>i(Ae(t,{...s,chart:k.target.value})),style:x,children:[e.jsx("option",{value:"table",children:"Table"}),Ii.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))]})}),e.jsx(E,{label:"X axis",t:m,children:e.jsxs("select",{value:s.x??"",onChange:k=>i(Ae(t,{...s,x:k.target.value})),style:x,children:[e.jsx("option",{value:"",children:"Auto"}),h.map(k=>e.jsx("option",{value:k,children:Ke(k)},k))]})}),e.jsx(E,{label:"Y axis",t:m,children:e.jsxs("select",{value:s.y??"",onChange:k=>i(Ae(t,{...s,y:k.target.value})),style:x,children:[e.jsx("option",{value:"",children:"Auto"}),h.map(k=>e.jsx("option",{value:k,children:Ke(k)},k))]})}),e.jsx(E,{label:"Series / color",t:m,children:e.jsxs("select",{value:s.color??"",onChange:k=>i(Ae(t,{...s,color:k.target.value})),style:x,children:[e.jsx("option",{value:"",children:"None"}),h.map(k=>e.jsx("option",{value:k,children:Ke(k)},k))]})})]}),e.jsx(E,{label:"Title",t:m,children:e.jsx("input",{value:s.title??"",onChange:k=>i(Ae(t,{...s,title:k.target.value})),style:x})})]}),e.jsx(fe,{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:h.length>0?h.map(k=>e.jsx("span",{style:Dt(m,!0),children:Ke(k)},k)):e.jsx("span",{style:{fontSize:11,color:m.textMuted},children:"Add aliases in DQL Source to expose business-friendly output names."})})}),e.jsx(Pi,{source:t,kind:"custom",onChange:i,t:m}),e.jsx(fe,{title:"Tests",hint:"Assertions checked on every run and required for certification.",t:m,children:e.jsx(It,{multiline:!0,value:I,onChange:k=>i(Ci(t,"tests",k)),placeholder:`assert row_count >= 1
21
+ assert revenue >= 0`,style:{...x,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 vr({semanticChoice:t,databaseWarning:n,onDismiss:r,onInsertAdvanced:s,onCreateSemantic:i,t:d}){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 ${d.headerBorder}`,background:`${d.accent}10`,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:12,color:d.textSecondary,lineHeight:1.4,flex:1,minWidth:260},children:p}),t&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:i,style:Y(d),children:"Create Semantic Block"}),e.jsx("button",{onClick:s,style:Ce(d),children:"Insert advanced ref"})]}),e.jsx("button",{onClick:r,style:Y(d),children:"Dismiss"})]})}function pn(t){var r,s,i,d,p;const n=((s=(r=t.preview)==null?void 0:r.result)==null?void 0:s.rowCount)??((p=(d=(i=t.preview)==null?void 0:i.result)==null?void 0:d.rows)==null?void 0:p.length);return typeof n=="number"?n:void 0}function zt(t){return t?t.startsWith("blocks/_drafts/")||/^domains\/[^/]+\/blocks\/_drafts\//.test(t):!1}function Je(t){var n,r,s,i,d;return t.reviewStatus==="saved"?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"saved",rows:pn(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:((r=t.validation.diagnostics.find(p=>p.severity==="error"))==null?void 0:r.message)??"DQL validation needs attention."}:t.preview?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"ready",rows:pn(t),savedPath:t.savedPath,message:zt(t.savedPath)?"Preview ran successfully. Draft is saved for review.":"Preview ran successfully. Nothing is written until you save."}:((s=t.draftSave)==null?void 0:s.status)==="saved"||zt(t.savedPath)?{id:t.id,name:t.name,sourcePath:t.sourcePath,status:"ready",savedPath:((i=t.draftSave)==null?void 0:i.path)??t.savedPath,message:"Draft saved. Run preview, then certify when ready."}:((d=t.draftSave)==null?void 0:d.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 Sr(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 jr(t,n){for(let r=0;r<240;r+=1){const s=await W.getDqlGenerationSession(t);if(n(s),s.candidates.every(i=>i.analysisStatus==="ready"||i.analysisStatus==="needs_attention"))return s;await new Promise(i=>window.setTimeout(i,500))}throw new Error("Import analysis is still running. You can leave this workspace and resume the session later.")}async function kr(t,n,r){let s=0;const i=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;s<t.length;){const d=s;s+=1,await r(t[d])}});await Promise.all(i)}function Ut(t){return!!(t.generationMode||t.draftSave||zt(t.savedPath))}function wr(t){return t==="creating"?"Reading SQL":t==="running"?"Running previews":t==="saving"?"Saving blocks":t==="complete"?"Import complete":"Ready"}function Cr(t){return t==="needs_attention"?"needs attention":t.replace("_"," ")}function Br(t){return t==="saved"||t==="ready"?"ok":t==="needs_attention"?"warn":"info"}function Tr({session:t,sessions:n,sessionsLoading:r,onClose:s,onSessionChange:i,onRefreshSessions:d,onSelectCandidate:p,onSavedCandidate:m,defaultDomain:x,defaultOwner:P,themeMode:l,t:f,inline:h=!1}){const[I,L]=c.useState("paste"),[$,J]=c.useState(""),[_,k]=c.useState(""),[S,te]=c.useState([]),[X,he]=c.useState(x),[A,K]=c.useState(P),[G,D]=c.useState(null),[Q,F]=c.useState(!1),[V,me]=c.useState(!1),[ee,N]=c.useState(null),[de,M]=c.useState(null),[U,ge]=c.useState(!1),[Te,Se]=c.useState(!0),[ce,_e]=c.useState(""),[ie,Ie]=c.useState(!1),[ze,xe]=c.useState({}),[Pe,a]=c.useState("idle"),[w,Z]=c.useState({}),ue=c.useMemo(()=>t?t.candidates.find(g=>g.id===G)??t.candidates[0]??null:null,[t,G]);c.useEffect(()=>{if(!(t!=null&&t.candidates.length)){D(null);return}(!G||!t.candidates.some(g=>g.id===G))&&D(t.candidates[0].id)},[t,G]),c.useEffect(()=>{xe({})},[t==null?void 0:t.id]),c.useEffect(()=>{Se(!(t!=null&&t.candidates.length))},[t==null?void 0:t.id,t==null?void 0:t.candidates.length]),c.useEffect(()=>{if(!t){Z({}),a("idle");return}Z(Object.fromEntries(t.candidates.map(g=>[g.id,Je(g)]))),a(g=>g==="idle"?"complete":g)},[t==null?void 0:t.id]);const ye=c.useMemo(()=>{const g=ce.trim().toLowerCase(),T=(t==null?void 0:t.candidates)??[];return g?T.filter(z=>[z.name,z.domain,z.sourcePath,z.description,...z.lineage.sourceTables].some(C=>C.toLowerCase().includes(g))):T},[ce,t]),We=ie||ce.trim()?ye:ye.slice(0,10),oe=((t==null?void 0:t.candidates.map(g=>w[g.id]??Je(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}),Fe=t?oe.saved>0?3:2:1,Oe=(t==null?void 0:t.candidates.filter(g=>{var T;return((T=g.validation)==null?void 0:T.valid)!==!1}).length)??0,Ge=!!(I==="paste"?_.trim():I==="upload"?S.length>0:$.trim()),qe=()=>I==="paste"?{inputMode:"paste",sourceKind:"raw-sql",domain:X,owner:A,sources:[{path:"pasted.sql",content:_}],async:!0,persistence:"session-only"}:I==="upload"?{inputMode:"upload",sourceKind:"raw-sql",domain:X,owner:A,sources:S,async:!0,persistence:"session-only"}:{path:$,inputMode:"path",sourceKind:"raw-sql",domain:X,owner:A,async:!0,persistence:"session-only"},rt=async()=>{var g,T,z;F(!0),me(!0),N(null),xe({}),Z({}),a("creating");try{const C=await W.createDqlGenerationSession(qe());let q=C,re=Object.fromEntries(C.candidates.map(R=>[R.id,{...Je(R),status:"queued",message:"Queued for governed retrieval."}]));const y=(R,O)=>{re={...re,[R]:O(re[R])},Z(re)},B=R=>{q={...q,candidates:q.candidates.map(O=>O.id===R.id?R:O)},i(q)};i(q),D(((g=q.candidates[0])==null?void 0:g.id)??null),Z(re),await d(),a("running"),q=await jr(C.id,R=>{q=R,i(R);for(const O of R.candidates)y(O.id,De=>({...De,name:O.name,sourcePath:O.sourcePath,status:O.analysisStatus==="needs_attention"?"needs_attention":O.analysisStatus==="ready"?"queued":"running",message:Sr(O.analysisStatus)}))}),await kr(q.candidates,2,async R=>{if(R.analysisStatus!=="needs_attention"){y(R.id,O=>({...O,status:"running",message:"Running preview."}));try{const O=await W.previewDqlGenerationCandidate(q.id,R.id);B(O),y(R.id,De=>{var je;return{...De,name:O.name,sourcePath:O.sourcePath,status:"ready",rows:pn(O),savedPath:((je=O.draftSave)==null?void 0:je.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 De=(O==null?void 0:O.message)??"Preview failed.";xe(je=>({...je,[R.id]:De})),y(R.id,je=>({...je,status:"needs_attention",message:De}))}}}),i(q),D(((T=q.candidates.find(R=>R.reviewStatus!=="rejected"))==null?void 0:T.id)??((z=q.candidates[0])==null?void 0:z.id)??null),await d(),a("complete")}catch(C){N((C==null?void 0:C.message)??"Import failed."),a("idle")}finally{F(!1),me(!1)}},Ne=async g=>{var T,z;F(!0),N(null);try{const C=await W.getDqlGenerationSession(g).catch(()=>W.getBlockStudioImport(g));i(C),D(((T=C.candidates.find(q=>q.reviewStatus!=="saved"&&q.reviewStatus!=="rejected"))==null?void 0:T.id)??((z=C.candidates[0])==null?void 0:z.id)??null),xe({}),a("complete")}catch(C){N((C==null?void 0:C.message)??"Failed to resume import session.")}finally{F(!1)}},st=async g=>{M({kind:"one",id:g})},He=async()=>{n.length!==0&&M({kind:"all"})},Re=async()=>{if(!de)return;const g=de;F(!0),N(null);try{g.kind==="one"?await W.deleteBlockStudioImport(g.id):await W.clearBlockStudioImports(),(g.kind==="all"||(t==null?void 0:t.id)===g.id)&&(i(null),D(null)),M(null),await d()}catch(T){N((T==null?void 0:T.message)??"Failed to update import history.")}finally{F(!1)}},Be=g=>{t&&(i({...t,candidates:t.candidates.map(T=>T.id===g.id?g:T)}),Z(T=>({...T,[g.id]:Je(g)})))},ft=async g=>{if(t){F(!0),N(null),xe(T=>{if(!T[g.id])return T;const z={...T};return delete z[g.id],z});try{const T=Ut(g)?await W.previewDqlGenerationCandidate(t.id,g.id):await W.runBlockStudioImportCandidate(t.id,g.id);Be(T),D(T.id),xe(z=>{if(!z[g.id])return z;const C={...z};return delete C[g.id],C})}catch(T){const z=(T==null?void 0:T.message)??"Candidate run failed.";N(z),D(g.id),xe(C=>({...C,[g.id]:z}))}finally{F(!1)}}},Ve=async g=>{if(!t)return;const T=g.owner.trim()||A.trim();if(!T){N("Owner is required before a block can be saved or certified.");return}F(!0),N(null);try{if(Ut(g)){const z=await W.saveSelectedDqlGenerationCandidates(t.id,{candidateIds:[g.id],owner:T});i(z.session);const C=z.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&&Be(C.candidate),C.candidate&&C.block&&m(C.candidate,C.block),C.status==="draft"&&C.blockers.length>0&&N(`Saved as draft: ${C.blockers.join(" ")}`)}else{const z=await W.saveBlockStudioImportCandidate(t.id,g.id);Be(z.candidate),m(z.candidate,z.block)}await d()}catch(z){const C=(z==null?void 0:z.message)??"Candidate save failed.";N(C.includes("409")||C.includes("already exists")?"A block with this name already exists. Rename this candidate, then save again.":C)}finally{F(!1)}},lt=async()=>{if(!t)return;const g=A.trim()||t.defaults.owner.trim();if(!g){N("Owner is required before blocks can be saved or certified.");return}me(!0),N(null);try{const T=t.candidates.filter(B=>B.reviewStatus!=="rejected"&&B.analysisStatus!=="needs_attention").map(B=>B.id),z=await W.saveSelectedDqlGenerationCandidates(t.id,{candidateIds:T,owner:g});i(z.session);const C=new Map(z.results.filter(B=>B.status==="error").map(B=>[B.candidateId,B.error??B.blockers.join(" ")])),q=new Map(z.results.filter(B=>B.path).map(B=>[B.candidateId,B.path]));Z(Object.fromEntries(z.session.candidates.map(B=>{const R=C.get(B.id),O=q.get(B.id)??B.savedPath;return R?[B.id,{...Je(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,{...Je(B),status:"saved",savedPath:O,message:"Block saved."}]:[B.id,Je(B)]}))),await d();const re=z.results.filter(B=>B.status==="error").length,y=z.results.filter(B=>B.status==="draft").length;(re>0||y>0)&&N(`${z.results.length-re} saved. ${y} stayed draft; ${re} need attention.`)}catch(T){N((T==null?void 0:T.message)??"Save all failed.")}finally{me(!1)}},et=async g=>{if(!t)return;const T=await W.updateBlockStudioImportCandidate(t.id,g.id,{reviewStatus:"rejected"});Be(T),d()},tt=async g=>{const z=Array.from(g??[]).filter(q=>q.name.toLowerCase().endsWith(".sql")),C=await Promise.all(z.map(async q=>({path:q.name,content:await q.text()})));te(C),C.length>0&&J("")};return e.jsxs("div",{style:{position:"relative",height:"100%",display:"grid",gridTemplateRows:"80px minmax(0, 1fr)",minHeight:0,background:f.appBg,borderRadius:h?0:8},children:[e.jsxs("header",{style:{borderBottom:`1px solid ${f.headerBorder}`,background:f.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:f.accent,background:`${f.accent}16`,flexShrink:0},children:e.jsx(Ht,{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:f.textPrimary,fontFamily:f.font},children:"Import SQL to DQL"}),e.jsx("span",{style:{fontSize:11,color:f.textMuted,fontFamily:f.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(an,{index:1,active:Fe===1,complete:!!t,title:"Source",detail:I==="paste"?"Paste SQL":I==="upload"?"Upload files":"Local path",t:f}),e.jsx(an,{index:2,active:Fe===2,complete:oe.ready>0||oe.saved>0,title:"Draft",detail:t?`${t.candidates.length} blocks · ${Oe} ready`:"Generate DQL",t:f}),e.jsx(an,{index:3,active:Fe===3,complete:oe.saved>0,title:"Review",detail:oe.saved>0?`${oe.saved} certified`:"Preview and certify",t:f})]}),e.jsx("div",{style:{flex:1}}),e.jsx("button",{onClick:s,title:"Close import","aria-label":"Close import",style:{...Y(f),width:32,height:32,padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e.jsx(Zo,{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 ${f.headerBorder}`,display:"grid",gridTemplateRows:"auto minmax(0, 1fr) auto",minHeight:0,background:f.cellBg},children:[e.jsxs("section",{style:{borderBottom:`1px solid ${f.headerBorder}`,padding:12,display:"grid",gap:10},children:[e.jsxs("button",{onClick:()=>Se(g=>!g),style:{background:"transparent",border:"none",color:f.textPrimary,cursor:"pointer",display:"flex",alignItems:"center",gap:8,padding:0,fontFamily:f.font,textAlign:"left"},children:[e.jsx(zi,{size:14,strokeWidth:2,color:f.accent,"aria-hidden":"true"}),e.jsx("span",{style:{fontSize:12,fontWeight:800,flex:1},children:"Source"}),t&&e.jsx("span",{style:{fontSize:10,color:f.textMuted},children:Te?"Hide":"Edit"})]}),Te?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:()=>L(g),style:{...Y(f),padding:"6px 4px",color:I===g?f.accent:f.textSecondary,borderColor:I===g?f.accent:f.btnBorder,background:I===g?`${f.accent}14`:f.btnBg},children:g==="paste"?"Paste SQL":g==="upload"?"Upload files":"Local path"},g))}),I==="path"&&e.jsx(E,{label:"Path",t:f,children:e.jsx("input",{value:$,onChange:g=>{J(g.target.value),g.target.value.trim()&&te([])},placeholder:"./queries or ./legacy.sql",style:we(f)})}),I==="upload"&&e.jsxs(E,{label:"Upload SQL files",t:f,children:[e.jsx("input",{type:"file",multiple:!0,accept:".sql,text/sql,text/plain",onChange:g=>void tt(g.target.files),style:we(f)}),e.jsx("span",{style:{fontSize:11,color:f.textMuted,fontFamily:f.font},children:S.length>0?`${S.length} SQL file(s) ready`:"Choose one or more SQL files."})]}),I==="paste"&&e.jsx(E,{label:"Paste SQL",t:f,children:e.jsx("textarea",{value:_,onChange:g=>k(g.target.value),placeholder:`select ...; go
22
+ select ...`,style:{...we(f),minHeight:t?86:150,resize:"vertical",fontFamily:f.fontMono}})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(E,{label:"Domain",t:f,children:e.jsx("input",{value:X,onChange:g=>he(g.target.value),placeholder:"auto",style:we(f)})}),e.jsx(E,{label:"Owner",t:f,children:e.jsx("input",{value:A,onChange:g=>K(g.target.value),placeholder:"analytics",style:we(f)})})]}),e.jsx("button",{onClick:()=>void rt(),disabled:Q||!Ge,style:{...Ce(f),padding:"8px 12px",opacity:Q||!Ge?.65:1,cursor:Q||!Ge?"not-allowed":"pointer"},children:Q?wr(Pe):"Generate DQL drafts"}),e.jsx("div",{style:{fontSize:11,color:f.textMuted,fontFamily:f.font,lineHeight:1.45},children:"Uses dbt, MetricFlow, warehouse catalog, and existing DQL context when available."})]}):e.jsxs("button",{onClick:()=>Se(!0),style:{...Y(f),display:"grid",gap:4,textAlign:"left",width:"100%",justifyItems:"start"},children:[e.jsx("span",{style:{fontSize:11,color:f.textSecondary},children:I==="paste"?"Pasted SQL":I==="upload"?"Uploaded files":"Local path"}),e.jsx("span",{style:{maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.textMuted,fontFamily:f.fontMono},children:(t==null?void 0:t.inputPath)??(I==="paste"?"pasted.sql":I==="upload"?`${S.length} file(s)`:$||"./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:f.textPrimary,fontFamily:f.font},children:"Drafts"}),e.jsx(ve,{label:`${t.candidates.length}`,tone:"info",t:f}),oe.ready>0&&e.jsx(ve,{label:`${oe.ready} ready`,tone:"ok",t:f}),oe.attention>0&&e.jsx(ve,{label:`${oe.attention} attention`,tone:"warn",t:f})]}),t.candidates.length>6&&e.jsx("input",{value:ce,onChange:g=>_e(g.target.value),placeholder:"Search drafts, tables, files...",style:we(f)})]}),We.map(g=>{var y,B,R,O,De,je,Lt,be;const T=g.id===(ue==null?void 0:ue.id),z=g.warnings??g.lineage.warnings,C=ze[g.id],q=((B=(y=g.preview)==null?void 0:y.result)==null?void 0:B.rowCount)??((De=(O=(R=g.preview)==null?void 0:R.result)==null?void 0:O.rows)==null?void 0:De.length),re=w[g.id]??Je(g);return e.jsxs("button",{onClick:()=>{D(g.id)},style:{border:`1px solid ${T?f.accent:C?"#f8514955":f.headerBorder}`,borderRadius:8,background:T?`${f.accent}10`:f.appBg,color:f.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(ve,{label:Cr(re.status),tone:Br(re.status),t:f})]}),e.jsxs("span",{style:{fontSize:10,color:f.textMuted,fontFamily:f.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(ve,{label:((je=g.draftSave)==null?void 0:je.status)==="saved"||zt(g.savedPath)?"draft saved":g.reviewStatus,tone:g.reviewStatus==="rejected"?"warn":"info",t:f}),e.jsx(ve,{label:((Lt=g.validation)==null?void 0:Lt.valid)===!1?"fix":"valid",tone:((be=g.validation)==null?void 0:be.valid)===!1?"warn":"ok",t:f}),typeof q=="number"&&e.jsx(ve,{label:`${q} rows`,tone:"ok",t:f}),z.length>0&&e.jsx(ve,{label:`${z.length} warning`,tone:"warn",t:f})]}),(C||re.message)&&e.jsx("span",{style:{fontSize:11,color:C?"#f85149":f.textMuted,lineHeight:1.35,overflowWrap:"anywhere"},children:C??re.message})]},g.id)}),!ie&&!ce.trim()&&ye.length>10&&e.jsxs("button",{onClick:()=>Ie(!0),style:Y(f),children:["Show all ",ye.length," drafts"]}),!t.candidates.some(Ut)&&oe.ready>0&&e.jsx("button",{onClick:()=>void lt(),disabled:V,style:Ce(f),children:V?"Saving...":"Save valid blocks"})]}):e.jsx("div",{style:{fontSize:12,color:f.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:U,onToggle:g=>ge(g.currentTarget.open),style:{borderTop:`1px solid ${f.headerBorder}`,padding:12,display:"grid",gap:8},children:[e.jsxs("summary",{style:{cursor:"pointer",color:f.textSecondary,fontSize:11,fontWeight:800,fontFamily:f.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 d(),style:Y(f),children:"Refresh"}),n.length>0&&e.jsx("button",{onClick:()=>void He(),style:Y(f),children:"Clear"})]}),r?e.jsx("div",{style:{fontSize:12,color:f.textMuted},children:"Loading..."}):n.length===0?e.jsx("div",{style:{fontSize:12,color:f.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?f.accent:f.btnBorder}`,borderRadius:8,background:(t==null?void 0:t.id)===g.id?`${f.accent}10`:f.btnBg,display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",overflow:"hidden"},children:[e.jsxs("button",{onClick:()=>void Ne(g.id),style:{background:"transparent",border:"none",color:f.textSecondary,cursor:"pointer",fontFamily:f.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:f.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.inputPath})]}),e.jsx("button",{onClick:()=>void st(g.id),title:"Delete local import session",style:{background:"transparent",border:"none",borderLeft:`1px solid ${f.headerBorder}`,color:f.textMuted,cursor:"pointer",fontFamily:f.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:f.appBg},children:[ee&&e.jsx("div",{role:"alert",style:{padding:"10px 12px",color:"#f85149",background:"#f8514914",border:"1px solid #f8514933",borderRadius:8,marginBottom:12,fontSize:12},children:ee}),!t||!ue?e.jsx(Mr,{t:f}):e.jsx(Dr,{session:t,candidate:ue,loading:Q,onCandidateUpdated:Be,onRun:ft,onSave:Ve,onReject:et,onReviewInEditor:p,runError:ze[ue.id]??null,themeMode:l,t:f})]})]}),de&&e.jsx(Ir,{t:f,busy:Q,title:de.kind==="all"?"Clear import history?":"Delete import preview?",message:de.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:de.kind==="all"?"Clear history":"Delete preview",onCancel:()=>M(null),onConfirm:()=>void Re()})]})}function Ir({title:t,message:n,confirmLabel:r,busy:s,onCancel:i,onConfirm:d,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:i,disabled:s,style:Y(p),children:"Cancel"}),e.jsx("button",{onClick:d,disabled:s,style:{...Ce(p),opacity:s?.65:1},children:s?"Working...":r})]})]})})}function Dr({session:t,candidate:n,loading:r,onCandidateUpdated:s,onRun:i,onSave:d,onReject:p,onReviewInEditor:m,runError:x,themeMode:P,t:l}){var qe,rt,Ne,st,He,Re,Be,ft,Ve,lt,et,tt,g,T,z,C,q,re;const[f,h]=c.useState(n.name),[I,L]=c.useState(n.domain),[$,J]=c.useState(n.owner),[_,k]=c.useState(n.description),[S,te]=c.useState(n.tags.join(", ")),[X,he]=c.useState((n.terms??[]).join(", ")),[A,K]=c.useState(n.pattern??""),[G,D]=c.useState(n.grain??""),[Q,F]=c.useState((n.entities??[]).join(", ")),[V,me]=c.useState((n.outputs??[]).join(", ")),[ee,N]=c.useState((n.dimensions??[]).join(", ")),[de,M]=c.useState((n.allowedFilters??[]).join(", ")),[U,ge]=c.useState((n.sourceSystems??[]).join(", ")),[Te,Se]=c.useState((n.replacementFor??[]).join(", ")),[ce,_e]=c.useState(n.reviewCadence??"monthly"),[ie,Ie]=c.useState(n.sql),[ze,xe]=c.useState(null),[Pe,a]=c.useState(null),[w,Z]=c.useState(!1);c.useEffect(()=>{h(n.name),L(n.domain),J(n.owner),k(n.description),te(n.tags.join(", ")),he((n.terms??[]).join(", ")),K(n.pattern??""),D(n.grain??""),F((n.entities??[]).join(", ")),me((n.outputs??[]).join(", ")),N((n.dimensions??[]).join(", ")),M((n.allowedFilters??[]).join(", ")),ge((n.sourceSystems??[]).join(", ")),Se((n.replacementFor??[]).join(", ")),_e(n.reviewCadence??"monthly"),Ie(n.sql),a(null),Z(!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 ue=async()=>{a(null);try{const y={name:f,domain:I,owner:$,description:_,tags:S.split(",").map(R=>R.trim()).filter(Boolean),terms:X.split(",").map(R=>R.trim()).filter(Boolean),pattern:A,grain:G,entities:Q.split(",").map(R=>R.trim()).filter(Boolean),outputs:V.split(",").map(R=>R.trim()).filter(Boolean),dimensions:ee.split(",").map(R=>R.trim()).filter(Boolean),allowedFilters:de.split(",").map(R=>R.trim()).filter(Boolean),sourceSystems:U.split(",").map(R=>R.trim()).filter(Boolean),replacementFor:Te.split(",").map(R=>R.trim()).filter(Boolean),reviewCadence:ce,sql:ie,llmContext:n.llmContext},B=Ut(n)?await W.updateDqlGenerationCandidate(t.id,n.id,y):await W.updateBlockStudioImportCandidate(t.id,n.id,y);s(B)}catch(y){a((y==null?void 0:y.message)??"Could not update candidate.")}},ye=async y=>{xe(y),a(null);try{const B=await W.assistBlockStudioImportCandidate(t.id,n.id,y);s(B)}catch(B){a((B==null?void 0:B.message)??"AI assist failed.")}finally{xe(null)}},We=n.warnings??n.lineage.warnings,ne=we(l),oe=((rt=(qe=n.preview)==null?void 0:qe.result)==null?void 0:rt.rowCount)??((He=(st=(Ne=n.preview)==null?void 0:Ne.result)==null?void 0:st.rows)==null?void 0:He.length),Fe=((Re=n.draftSave)==null?void 0:Re.path)??(zt(n.savedPath)?n.savedPath:void 0),Oe=n.recommendedAction==="reuse_existing"||((Be=n.draftSave)==null?void 0:Be.status)==="skipped",Ge=n.lineage.sourceTables.length+(((ft=n.evidence)==null?void 0:ft.length)??0)+n.lineage.parameters.length+We.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 i(n),disabled:r,style:Y(l),children:r?"Running...":"Preview"}),e.jsx("button",{onClick:()=>Z(y=>!y),style:w?Ce(l):Y(l),children:w?"Hide context":`Show context${Ge>0?` (${Ge})`:""}`}),e.jsx("button",{onClick:()=>m(n),style:Ce(l),children:"Edit full DQL"}),e.jsx("button",{onClick:()=>void d(n),disabled:r||n.reviewStatus==="saved"||Oe,style:Ce(l),children:Oe?"Reuse existing":n.reviewStatus==="saved"?"Certified":"Save block"})]}),Pe&&e.jsx("div",{role:"alert",style:{fontSize:12,color:"#f85149",background:"#f8514914",borderRadius:8,padding:10},children:Pe}),x&&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: ",x]}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[e.jsx(ve,{label:((Ve=n.draftSave)==null?void 0:Ve.status)==="skipped"?"reuse recommended":((lt=n.draftSave)==null?void 0:lt.status)==="saved"||Fe?"draft saved":n.reviewStatus,tone:n.reviewStatus==="rejected"?"warn":((et=n.draftSave)==null?void 0:et.status)==="skipped"?"ok":"info",t:l}),e.jsx(ve,{label:`${Math.round(n.confidence*100)}% confidence`,tone:"info",t:l}),e.jsx(ve,{label:((tt=n.validation)==null?void 0:tt.valid)===!1?"needs fixes":"valid",tone:((g=n.validation)==null?void 0:g.valid)===!1?"warn":"ok",t:l}),typeof oe=="number"&&e.jsx(ve,{label:`${oe} rows`,tone:"ok",t:l})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:w?"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(fe,{title:"Review details",t:l,children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(E,{label:"Name",t:l,children:e.jsx("input",{value:f,onChange:y=>h(y.target.value),style:ne})}),e.jsx(E,{label:"Domain",t:l,children:e.jsx("input",{value:I,onChange:y=>L(y.target.value),style:ne})}),e.jsx(E,{label:"Owner",t:l,children:e.jsx("input",{value:$,onChange:y=>J(y.target.value),style:ne})}),e.jsx(E,{label:"Tags",t:l,children:e.jsx("textarea",{value:S,onChange:y=>te(y.target.value),style:{...ne,minHeight:58,resize:"vertical"}})})]}),e.jsx(E,{label:"Business description",t:l,children:e.jsx("textarea",{value:_,onChange:y=>k(y.target.value),style:{...ne,minHeight:70,resize:"vertical"}})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:8},children:[e.jsx(E,{label:"Pattern",t:l,children:e.jsx("select",{value:A,onChange:y=>K(y.target.value),style:ne,children:["custom","metric_wrapper","entity_profile","entity_rollup","ranking","trend","bridge","drilldown","replacement"].map(y=>e.jsx("option",{value:y,children:y},y))})}),e.jsx(E,{label:"Grain",t:l,children:e.jsx("input",{value:G,onChange:y=>D(y.target.value),style:ne})}),e.jsx(E,{label:"Review cadence",t:l,children:e.jsx("select",{value:ce,onChange:y=>_e(y.target.value),style:ne,children:["weekly","monthly","quarterly","semiannual","annual"].map(y=>e.jsx("option",{value:y,children:y},y))})})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(E,{label:"Entities",t:l,children:e.jsx("input",{value:Q,onChange:y=>F(y.target.value),style:ne})}),e.jsx(E,{label:"Outputs",t:l,children:e.jsx("input",{value:V,onChange:y=>me(y.target.value),style:ne})}),e.jsx(E,{label:"Dimensions",t:l,children:e.jsx("input",{value:ee,onChange:y=>N(y.target.value),style:ne})}),e.jsx(E,{label:"Allowed filters",t:l,children:e.jsx("input",{value:de,onChange:y=>M(y.target.value),style:ne})}),e.jsx(E,{label:"Source systems",t:l,children:e.jsx("input",{value:U,onChange:y=>ge(y.target.value),style:ne})}),e.jsx(E,{label:"Terms",t:l,children:e.jsx("input",{value:X,onChange:y=>he(y.target.value),style:ne})})]}),e.jsx(E,{label:"Replaces",t:l,children:e.jsx("input",{value:Te,onChange:y=>Se(y.target.value),style:ne})}),e.jsx("button",{onClick:()=>void ue(),style:{...Ce(l),justifySelf:"start"},children:"Apply edits"})]}),n.preview&&e.jsxs(fe,{title:"Preview Results",t:l,children:[e.jsxs("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.45},children:["Query ran successfully",typeof oe=="number"?` and returned ${oe} rows`:"","."]}),e.jsx("div",{style:{maxHeight:320,overflow:"auto",border:`1px solid ${l.headerBorder}`,borderRadius:8},children:e.jsx(Ti,{result:n.preview.result,themeMode:P})})]}),e.jsxs("details",{style:wt(l),children:[e.jsx("summary",{style:Ct(l),children:"Original SQL"}),e.jsx("textarea",{value:ie,onChange:y=>Ie(y.target.value),style:{...ne,minHeight:210,fontFamily:l.fontMono,resize:"vertical",marginTop:10}})]}),e.jsxs("details",{style:wt(l),children:[e.jsx("summary",{style:Ct(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})]})]}),w&&e.jsxs("div",{style:{display:"grid",gap:12},children:[(((T=n.similarityMatches)==null?void 0:T.length)||((z=n.draftSave)==null?void 0:z.status)==="skipped")&&e.jsx(fe,{title:"Reuse recommendation",t:l,children:e.jsxs("div",{style:{display:"grid",gap:8},children:[e.jsx(ct,{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((y,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:y.name}),e.jsxs("div",{style:{fontSize:10,color:l.textMuted,marginTop:3},children:[y.kind," · ",Math.round(y.score*100),"% · ",y.recommendedAction]}),e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:y.reason})]},`${y.objectKey??y.name}-${B}`))]})}),(((q=n.parameterDecisions)==null?void 0:q.length)||((re=n.filterBindings)==null?void 0:re.length))&&e.jsx(fe,{title:"Parameter contract",t:l,children:e.jsxs("div",{style:{display:"grid",gap:8},children:[(n.parameterDecisions??[]).slice(0,8).map(y=>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:y.name}),e.jsx("span",{style:{fontSize:10,color:l.textMuted},children:y.policy})]}),e.jsxs("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:[y.sourceExpression," = ",String(y.value)]}),e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:y.reason})]},y.name)),(n.filterBindings??[]).length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:(n.filterBindings??[]).map(y=>e.jsx(ve,{label:`${y.filter} -> ${y.binding}`,tone:"info",t:l},y.filter))})]})}),e.jsxs(fe,{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(y=>e.jsx(ve,{label:y,tone:"info",t:l},y)):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((y,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:y.name}),e.jsxs("div",{style:{fontSize:10,color:l.textMuted,marginTop:3},children:[y.kind,y.reason?` · ${y.reason}`:""]}),y.description&&e.jsx("div",{style:{fontSize:11,color:l.textMuted,lineHeight:1.35,marginTop:5},children:y.description})]},`${y.objectKey??y.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(y=>e.jsx(ve,{label:y,tone:"warn",t:l},y)):e.jsx("span",{style:{fontSize:12,color:l.textMuted},children:"None detected"})})]}),We.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"}),We.map((y,B)=>e.jsx("div",{style:{fontSize:12,color:"#d29922",lineHeight:1.4},children:y},B))]})]}),e.jsxs("details",{style:wt(l),children:[e.jsx("summary",{style:Ct(l),children:"Generation audit"}),e.jsxs("div",{style:{display:"grid",gap:8,marginTop:10},children:[e.jsx(ct,{label:"Method",value:n.generationMode==="ai"?`AI-assisted local generation (${n.generationProvider??"configured provider"})`:"Deterministic local generation",t:l}),Fe&&e.jsx(ct,{label:"Draft path",value:Fe,t:l}),e.jsx(ct,{label:"Default test",value:"assert row_count > 0",t:l}),e.jsx(ct,{label:"Split strategy",value:n.splitStrategy??"semicolon-go",t:l}),n.llmContext&&e.jsx(ct,{label:"Agent use",value:n.llmContext,t:l}),(n.conversionNotes??[]).map((y,B)=>e.jsx("div",{style:{fontSize:12,color:l.textMuted,lineHeight:1.4},children:y},B))]})]}),e.jsxs("details",{style:wt(l),children:[e.jsx("summary",{style:Ct(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(([y,B])=>e.jsx("button",{onClick:()=>void ye(y),disabled:!!ze,style:Y(l),children:ze===y?"Working...":B},y))}),(n.aiAssistance??[]).length>0&&e.jsx("div",{style:{display:"grid",gap:8},children:(n.aiAssistance??[]).slice().reverse().map((y,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:[y.action," · ",y.status]}),e.jsx("div",{style:{fontSize:12,color:l.textSecondary,lineHeight:1.45,marginTop:5},children:y.summary})]},`${y.createdAt}-${B}`))})]})]}),e.jsx("button",{onClick:()=>void p(n),disabled:n.reviewStatus==="rejected",style:{...Y(l),justifySelf:"start"},children:n.reviewStatus==="rejected"?"Rejected":"Reject draft"})]})]})]})}function an({index:t,active:n,complete:r,title:s,detail:i,t:d}){const p=r?"#2ea043":n?d.accent:d.textMuted;return e.jsxs("div",{style:{border:`1px solid ${n?d.accent:d.headerBorder}`,borderRadius:8,padding:"9px 10px",display:"grid",gridTemplateColumns:"24px minmax(0, 1fr)",gap:8,alignItems:"center",background:n?`${d.accent}10`:d.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:d.font},children:r?"✓":t}),e.jsxs("span",{style:{minWidth:0},children:[e.jsx("span",{style:{display:"block",fontSize:12,fontWeight:700,color:d.textPrimary,fontFamily:d.font},children:s}),e.jsx("span",{style:{display:"block",fontSize:10,color:d.textMuted,fontFamily:d.font,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]})]})}function Mr({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(pt,{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(([r,s,i])=>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:r}),e.jsx("span",{style:{fontSize:12,fontWeight:700,color:t.textPrimary,fontFamily:t.font},children:s}),e.jsx("span",{style:{fontSize:11,color:t.textMuted,fontFamily:t.font,lineHeight:1.4},children:i})]},s))})]})}function E({label:t,children:n,t:r}){return e.jsxs("label",{style:{display:"grid",gap:5},children:[e.jsx("span",{style:{fontSize:10,fontWeight:700,color:r.textMuted,letterSpacing:"0.05em",textTransform:"uppercase",fontFamily:r.font},children:t}),n]})}function fe({title:t,hint:n,children:r,t:s}){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:s.textPrimary,fontFamily:s.font},children:t}),n?e.jsx("div",{style:{fontSize:11,color:s.textMuted,lineHeight:1.45,marginTop:3,fontFamily:s.font},children:n}):null]}),e.jsx("div",{style:{minWidth:0,display:"grid",gap:10,alignContent:"start"},children:r})]})}function ct({label:t,value:n,t:r}){return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"110px minmax(0, 1fr)",gap:8,fontSize:12,fontFamily:r.font},children:[e.jsx("span",{style:{color:r.textMuted},children:t}),e.jsx("span",{title:n,style:{color:r.textSecondary,overflowWrap:"anywhere"},children:n})]})}function ve({label:t,tone:n,t:r}){const s=n==="ok"?"#2ea043":n==="warn"?"#d29922":r.accent;return e.jsx("span",{style:{fontSize:10,fontWeight:700,color:s,background:`${s}18`,borderRadius:999,padding:"3px 7px",fontFamily:r.font,textTransform:"uppercase"},children:t})}function wt(t){return{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:12,color:t.textPrimary,fontFamily:t.font}}function Ct(t){return{cursor:"pointer",color:t.textSecondary,fontSize:11,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em",fontFamily:t.font}}function we(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 hn(t){return{...we(t),boxSizing:"border-box",fontSize:11.5,minHeight:32,padding:"6px 8px"}}function Y(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 Ce(t){return{...Y(t),background:`${t.accent}18`,border:`1px solid ${t.accent}`,color:t.accent,fontWeight:700}}function zr({blockName:t,loading:n,detail:r,graph:s,paths:i,onSelectNode:d,onOpenInspector:p,t:m}){if(!t)return e.jsx(pt,{message:"Lineage will appear once the block has a name."});if(n)return e.jsx(pt,{message:"Loading block lineage…"});if(!(r!=null&&r.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 x=`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:r.node.name}),e.jsx("div",{style:{fontSize:11,color:m.textMuted,fontFamily:m.font},children:r.node.domain?`Domain: ${r.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"})]}),(i==null?void 0:i.layerSummary)&&e.jsx(_o,{layerSummary:i.layerSummary,t:m}),s&&s.nodes.length>0&&e.jsx(Qo,{nodes:s.nodes,edges:s.edges,focalNodeId:x,height:360,onNodeClick:d,layoutMode:"flow"}),i&&(i.upstreamPaths.length>0||i.downstreamPaths.length>0)&&e.jsxs("div",{style:{display:"grid",gap:10},children:[i.upstreamPaths.length>0&&e.jsx(ci,{title:"Source to Block",paths:i.upstreamPaths,onNodeClick:d,focalNodeId:x,t:m}),i.downstreamPaths.length>0&&e.jsx(ci,{title:"Block to Consumption",paths:i.downstreamPaths,onNodeClick:d,focalNodeId:x,t:m})]})]})}function Pr({metadata:t,draftMetadata:n,onChange:r,t:s}){const i={width:"100%",background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:6,color:s.textPrimary,fontSize:12,fontFamily:s.font,padding:"8px 10px",outline:"none"},d={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:d.name,onChange:p=>r({name:p.target.value}),placeholder:"Block name",style:i}),e.jsx("input",{value:d.domain,onChange:p=>r({domain:p.target.value}),placeholder:"Domain",style:i}),e.jsx("input",{value:d.folderPath,onChange:p=>r({folderPath:p.target.value}),placeholder:"Folder (optional), e.g. executive/monthly",style:{...i,fontFamily:s.fontMono}}),e.jsx("input",{value:d.owner,onChange:p=>r({owner:p.target.value}),placeholder:"Owner",style:i}),e.jsx("input",{value:d.description,onChange:p=>r({description:p.target.value}),placeholder:"Description",style:i}),e.jsx(Bi,{values:d.tags,onChange:p=>r({tags:p}),placeholder:"Tags",style:i})]})}function Rr({parameters:t,values:n,onChange:r,onReset:s,onRun:i,running:d,t:p}){return t.length===0?e.jsx(pt,{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:i,disabled:d,style:Ce(p),children:d?"Running…":"Run preview"})]}),e.jsx(Ko,{parameters:t,values:n,onChange:r,onReset:s,t:p,includeNonRuntime:!0,card:!0})]})}function Lr({values:t,t:n}){return e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:t.map(r=>e.jsxs("span",{style:{fontSize:10,color:n.textSecondary,background:n.appBg,border:`1px solid ${n.cellBorder}`,borderRadius:999,padding:"4px 7px"},children:[r.name," = ",Array.isArray(r.value)?r.value.join(", "):String(r.value)," ",e.jsxs("span",{style:{color:n.textMuted},children:["(",r.source,")"]})]},r.name))})}function pt({message:t}){const n=Rt[Pt(r=>r.themeMode)];return e.jsx("div",{style:{padding:16,fontSize:12,color:n.textMuted},children:t})}function Er({elapsedMs:t}){const n=Rt[Pt(r=>r.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(ot,{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:Ar(t)})]}),e.jsx("div",{style:{color:n.textMuted,fontSize:12,lineHeight:1.45},children:"Executing the block query against the active connection."})]})})}function $r({message:t}){const n=Rt[Pt(r=>r.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:n.textPrimary,fontFamily:n.font,padding:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,fontWeight:700,color:"#f85149"},children:[e.jsx(Mt,{size:16,strokeWidth:2,"aria-hidden":"true"}),e.jsx("span",{children:"Preview failed"})]}),e.jsx("div",{style:{color:n.textPrimary,fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t})]})})}function Ar(t){const n=Math.max(0,Math.floor(t/1e3));if(n<60)return`${n}s`;const r=Math.floor(n/60),s=n%60;return`${r}m ${s}s`}const gi={draft:"#8b949e",review:"#d29922",certified:"#3fb950",deprecated:"#f85149"},_r={draft:[],review:["draft"],certified:["deprecated"],deprecated:["draft"]};function Wr({currentStatus:t,blockPath:n,onStatusChanged:r,t:s}){const[i,d]=c.useState(!1),p=_r[t]??[],m=async x=>{if(n){d(!0);try{const P=await W.updateBlockStatus(n,x);P.ok&&P.status&&r(P.status)}finally{d(!1)}}};return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",background:s.pillBg,borderRadius:8},children:[e.jsx("span",{style:{fontSize:11,color:s.textMuted,fontFamily:s.font},children:"Status:"}),e.jsx("span",{style:{fontSize:11,fontWeight:600,color:gi[t]??s.textMuted,background:`${gi[t]??s.textMuted}18`,padding:"2px 8px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em",fontFamily:s.font},children:t}),e.jsx("span",{style:{flex:1}}),p.map(x=>e.jsx("button",{onClick:()=>void m(x),disabled:i,style:{background:x==="certified"?"#3fb950":x==="deprecated"?"#f85149":s.btnBg,border:`1px solid ${x==="certified"?"#3fb950":x==="deprecated"?"#f85149":s.btnBorder}`,borderRadius:4,color:x==="certified"||x==="deprecated"?"#fff":s.textSecondary,cursor:i?"not-allowed":"pointer",fontSize:10,fontWeight:600,fontFamily:s.font,padding:"3px 10px",textTransform:"capitalize",opacity:i?.5:1},children:i?"...":x==="certified"?"Certify":x==="deprecated"?"Deprecate":`Move to ${x}`},x))]})}function Fr({result:t,t:n}){var m,x,P;const r=t.checklist,s=r?[["Metadata",r.metadata],["Validation",r.validation],["Run",r.run],["Tests",r.tests],["Chart",r.chart],["Lineage",r.lineage]]:[],i=Array.from(new Set(((m=t.blockers)!=null&&m.length?t.blockers:(r==null?void 0:r.blockers)??[]).map(Or))),d=qr(i),p=t.pending?n.accent:t.ok?"#3fb950":"#d29922";return e.jsxs("div",{style:{margin:"12px 12px 0",border:`1px solid ${p}55`,borderRadius:8,background:`${p}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:p,fontFamily:n.font},children:t.pending?"Certification running":t.ok?"Block certified":"Unable to certify"}),(r==null?void 0:r.checkedAt)&&e.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.fontMono},children:r.checkedAt})]}),e.jsx("div",{style:{fontSize:12,color:n.textMuted,lineHeight:1.45},children:t.pending?"The exact draft is saved and the certification gates are running in the background. You may switch pages or continue other work.":t.ok?r!=null&&r.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.":d?`Latest edits were saved, but certification cannot finish because ${d}. Fix it, then click Certify again.`:"Latest edits were saved, but certification cannot finish yet. Fix the blockers below, then click Certify again."}),s.length>0&&e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:s.map(([l,f])=>e.jsxs("span",{style:{fontSize:11,fontWeight:700,color:f?"#3fb950":"#d29922",background:f?"#3fb95018":"#d2992218",borderRadius:999,padding:"4px 8px"},children:[f?"✓":"!"," ",l]},l))}),t.error&&e.jsx("div",{style:{fontSize:12,color:"#f85149"},children:t.error}),i.length>0&&e.jsxs("div",{style:{display:"grid",gap:5},children:[e.jsx("div",{style:{fontSize:10,color:"#d29922",textTransform:"uppercase",fontWeight:800},children:"Missing before certification"}),i.map((l,f)=>e.jsx("div",{style:{fontSize:12,color:"#d29922",lineHeight:1.4},children:l},f))]}),(((P=(x=t.certification)==null?void 0:x.warnings)==null?void 0:P.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(l=>e.jsxs("div",{style:{fontSize:12,color:n.textMuted},children:[l.rule,": ",l.message]},`${l.rule}-${l.message}`))]})]})}function Or(t){const n=t.trim(),r=n.toLowerCase();return r==="missing owner"||r==="block has owner: missing owner"?"Owner is required.":r==="missing domain"||r==="block has domain: missing domain"?"Domain is required.":r==="missing description"||r==="block has description: missing description"?"Description is required.":r==="block has not run successfully"?"The query must run successfully.":r==="tests must pass before certification"||r.startsWith("all tests pass:")?"Tests must pass.":r==="at least one test assertion is required before certification"||r.startsWith("block has tests:")?"Add at least one test assertion.":r==="visualization config is missing"?"Choose a visualization.":n}function qr(t){const n=t.filter(r=>r.endsWith(" is required.")).map(r=>r.replace(" is required.","").toLowerCase());return n.length===0?t[0]?t[0].replace(/\.$/,"").toLowerCase():"":n.length===1?`${n[0]} is missing`:n.length===2?`${n[0]} and ${n[1]} are missing`:n.length>2?`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]} are missing`:t.includes("Add at least one test assertion.")?"a test assertion is missing":t.includes("Choose a visualization.")?"a visualization is missing":t.includes("Tests must pass.")?"tests must pass":t.includes("The query must run successfully.")?"the query has not run successfully":t[0]?t[0].replace(/\.$/,"").toLowerCase():""}function Nr({entries:t,t:n}){return t.length===0?e.jsx(pt,{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(r=>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:r.hash.slice(0,7)}),e.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font},children:new Date(r.date).toLocaleDateString()}),e.jsx("span",{style:{fontSize:11,color:n.textMuted,fontFamily:n.font,marginLeft:"auto"},children:r.author})]}),e.jsx("div",{style:{fontSize:12,color:n.textPrimary,fontFamily:n.font},children:r.message})]},r.hash))]})}function Hr(t,n){const r=t.match(/query\s*=\s*"""([\s\S]*?)"""/i);return r?t.replace(r[0],`query = """${r[1].trimEnd()}
23
+ ${n}
24
+ """`):/^\s*block\s+"/i.test(t.trim())?t.replace(/\n\}\s*$/,`
25
+
26
+ query = """
27
+ ${n}
28
+ """
29
+ }
30
+ `):`${t.trimEnd()}
31
+ ${n}
32
+ `}function xi(t,n){const r=n.trim().replace(/;\s*$/,"");if(!r)return t;const s=t.trim();if(!s)return r;const i=t.match(/query\s*=\s*"""[\s\S]*?"""/i);if(i)return t.replace(i[0],`query = """
33
+ ${r}
34
+ """`);if(/^\s*block\s+"/i.test(s)){const d=`
35
+ query = """
36
+ ${r}
37
+ """
38
+ `;return/\}\s*$/.test(t)?t.replace(/\}\s*$/,`${d}}
39
+ `):`${t.trimEnd()}${d}`}return r}function dn(t){return Po({name:t,status:"draft",metrics:[],dimensions:[],visualization:{chart:"table"}})}function Nt(t){return`block "${t}" {
40
+ domain = "uncategorized"
41
+ type = "custom"
42
+ description = ""
43
+ owner = ""
44
+ tags = []
45
+
46
+ query = """
47
+ SELECT 1 AS value
48
+ """
49
+
50
+ visualization {
51
+ chart = "table"
52
+ }
53
+ }
54
+
55
+ `}const Li="dql.block-studio.draft-session";function fn(){const t=`draft-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;try{window.localStorage.setItem(Li,t)}catch{}return t}function Qr(){var t;try{const n=(t=window.localStorage.getItem(Li))==null?void 0:t.trim();if(n)return n}catch{}return fn()}function Ur(){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 Kr(t,n){try{const r=window.localStorage.getItem(t);return r==null?n:r==="1"}catch{return n}}function Gr(t,n,r,s){try{const i=Number(window.localStorage.getItem(t));return Number.isFinite(i)?Math.min(s,Math.max(r,i)):n}catch{return n}}function Vr(t){return!!(t.blockStudioDraft.trim()||t.blockStudioMetadata||t.activeBlockPath)}function Ei(t){var i,d;const n=((i=t==null?void 0:t.domain)==null?void 0:i.trim())||"uncategorized",r=(d=t==null?void 0:t.folderPath)==null?void 0:d.trim().replace(/\\/g,"/").replace(/^\/+|\/+$/g,""),s=((t==null?void 0:t.name)||"new_block").toLowerCase().replace(/[^a-z0-9_]+/g,"-").replace(/^[-_]+|[-_]+$/g,"")||"new-block";return`blocks/${n}/${r?`${r}/`:""}${s}.dql`}function $i(t){var r;const n=((r=t.match(/\bselect\b([\s\S]*?)\bfrom\b/i))==null?void 0:r[1])??"";return n?Array.from(new Set(n.split(",").map(s=>{var p,m;const i=(p=s.match(/\bas\s+([a-zA-Z_][\w$]*)\s*$/i))==null?void 0:p[1];return i||(((m=s.trim().match(/(?:^|\.)([a-zA-Z_][\w$]*)$/))==null?void 0:m[1])??"")}).filter(Boolean))).slice(0,24):[]}function Ke(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,n=>n.toUpperCase())}function Yr(t,n){const r=n.trim().toLowerCase();if(!r)return t;const s=i=>{const d=[i.label,i.path,i.type].filter(m=>!!m).some(m=>m.toLowerCase().includes(r)),p=(i.children??[]).map(m=>s(m)).filter(m=>!!m);return d||p.length>0?{...i,children:p}:null};return t.map(i=>s(i)).filter(i=>!!i)}function Xr(t){let n=0,r=0,s=0;const i=d=>{d.kind==="schema"&&(n+=1),d.kind==="table"&&(r+=1),d.kind==="column"&&(s+=1);for(const p of d.children??[])i(p)};for(const d of t)i(d);return{schemas:n,tables:r,columns:s}}function Zr(t){const n=[],r=s=>{s.kind==="table"&&s.path&&n.push({path:s.path,columns:(s.children??[]).filter(i=>i.kind==="column").map(i=>i.label)});for(const i of s.children??[])r(i)};for(const s of t)r(s);return n}function yi(t){return["businessOutcome","llmContext","primaryTerms","sourceSystems","synonyms","caveats"].filter(r=>new RegExp(`\\b${r}\\s*=`,"i").test(t)).length}function Jr(t){return t.metrics+t.measures+t.dimensions+t.timeDimensions+t.entities+t.hierarchies+t.semanticModels+t.savedQueries}export{js as BlockStudio};
@@ -1 +1 @@
1
- import{u as C,t as k,r as l,a as I,j as t,p as j,q as S,au as L,av as N}from"./index-1mIC_XX4.js";import{M as W}from"./MiniLineageGraph-GkD4y17x.js";import"./react-CRB3T2We.js";import"./dagre.esm-GKp7qoUL.js";function w(n){return n.replace(/\.(dqlnb|dql)$/i,"")}function $(n,o){return`${n}:${w(o)}`}function U(){var y,x;const{state:n,dispatch:o}=C(),e=k[n.themeMode],i=n.activeFile,d=i&&(i.type==="term"||i.type==="business_view")?$(i.type,i.name):null,[a,B]=l.useState({nodes:[],edges:[],focalNode:null}),[M,u]=l.useState(!1);l.useEffect(()=>{if(!d)return;let s=!1;return u(!0),I.queryLineage({focus:d,upstreamDepth:3,downstreamDepth:3}).then(h=>{var f,v;s||(B({nodes:((f=h.graph)==null?void 0:f.nodes)??[],edges:((v=h.graph)==null?void 0:v.edges)??[],focalNode:h.focalNode??null}),u(!1))}).catch(()=>{s||u(!1)}),()=>{s=!0}},[d]);const r=a.focalNode,c=l.useMemo(()=>new Map(a.nodes.map(s=>[s.id,s])),[a.nodes]),g=l.useMemo(()=>r?a.edges.filter(s=>s.target===r.id).map(s=>({edge:s,node:c.get(s.source)})).filter(s=>!!s.node):[],[r,a.edges,c]),m=l.useMemo(()=>r?a.edges.filter(s=>s.source===r.id).map(s=>({edge:s,node:c.get(s.target)})).filter(s=>!!s.node):[],[r,a.edges,c]);if(!i||!d)return t.jsx("div",{style:{flex:1,padding:24,color:e.textMuted},children:"Select a business term or business view from Explorer."});const p=(r==null?void 0:r.type)??i.type,T=j[p]??e.accent,E=S[p]??p.toUpperCase(),z=((y=r==null?void 0:r.metadata)==null?void 0:y.path)??((x=r==null?void 0:r.metadata)==null?void 0:x.filePath)??i.path;return t.jsxs("div",{style:{flex:1,minWidth:0,overflow:"auto",background:"var(--color-bg-primary)"},children:[t.jsx("div",{style:{padding:"22px 28px 18px",borderBottom:`1px solid ${e.headerBorder}`,background:e.appBg},children:t.jsx("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16},children:t.jsxs("div",{style:{minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[t.jsx("span",{style:{color:e.appBg,background:T,borderRadius:5,padding:"3px 7px",fontSize:10,fontWeight:800,letterSpacing:0},title:L[p]??p,children:E}),t.jsxs("span",{style:{color:e.textMuted,fontSize:12},children:["Lineage · ↑ ",g.length," · ↓ ",m.length]})]}),t.jsx("h1",{style:{margin:0,fontSize:26,lineHeight:1.15,color:e.textPrimary},children:(r==null?void 0:r.name)??w(i.name)}),t.jsx("div",{style:{marginTop:7,color:e.textMuted,fontSize:13},children:i.type==="term"?"Business definition used by blocks, views, dashboards, and AI agents.":"Business composition built from trusted terms, DQL blocks, and other business views."})]})})}),t.jsxs("div",{style:{padding:24,display:"grid",gridTemplateColumns:"minmax(300px, 420px) minmax(420px, 1fr)",gap:18},children:[t.jsxs("section",{style:{display:"grid",gap:14,alignContent:"start"},children:[r&&t.jsx(P,{node:r,t:e}),t.jsx(b,{title:"Upstream",connections:g,t:e}),t.jsx(b,{title:"Downstream",connections:m,t:e}),t.jsxs("div",{style:{border:`1px solid ${e.headerBorder}`,borderRadius:8,padding:12,color:e.textMuted,fontSize:12,background:e.sidebarBg},children:[t.jsx("div",{style:{fontWeight:800,color:e.textSecondary,marginBottom:6},children:"Source file"}),t.jsx("div",{style:{overflowWrap:"anywhere"},children:String(z)})]})]}),t.jsxs("section",{style:{minHeight:520,border:`1px solid ${e.headerBorder}`,borderRadius:8,background:e.sidebarBg,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"12px 14px",borderBottom:`1px solid ${e.headerBorder}`},children:[t.jsx("div",{style:{fontWeight:800,color:e.textPrimary,fontSize:14},children:"Focused lineage"}),t.jsxs("div",{style:{color:e.textMuted,fontSize:12,marginTop:3},children:["Technical inputs and business composition for this ",i.type==="term"?"term":"view","."]})]}),t.jsx("div",{style:{height:470,padding:12},children:M?t.jsx("div",{style:{color:e.textMuted,fontSize:12},children:"Loading lineage..."}):a.nodes.length===0?t.jsx("div",{style:{color:e.textMuted,fontSize:12},children:"No lineage available."}):t.jsx(W,{nodes:a.nodes,edges:a.edges,focalNodeId:d,height:"100%",onNodeClick:s=>{o({type:"SET_LINEAGE_FOCUS",nodeId:s})},interactive:!0})})]})]})]})}function P({node:n,t:o}){const e=n.metadata??{},i=[];return n.domain&&i.push({label:"Domain",value:n.domain}),n.owner&&i.push({label:"Owner",value:n.owner}),n.status&&i.push({label:"Status",value:n.status}),n.type==="term"&&typeof e.termType=="string"&&i.push({label:"Term Type",value:e.termType}),Array.isArray(e.identifiers)&&e.identifiers.length>0&&i.push({label:"Identifiers",value:e.identifiers.map(String).join(", ")}),Array.isArray(e.synonyms)&&e.synonyms.length>0&&i.push({label:"Synonyms",value:e.synonyms.map(String).join(", ")}),typeof e.description=="string"&&e.description.trim()&&i.push({label:"Description",value:e.description}),typeof e.businessOutcome=="string"&&e.businessOutcome.trim()&&i.push({label:"Business Outcome",value:e.businessOutcome}),typeof e.decisionUse=="string"&&e.decisionUse.trim()&&i.push({label:"Decision Use",value:e.decisionUse}),typeof e.reviewCadence=="string"&&e.reviewCadence.trim()&&i.push({label:"Review Cadence",value:e.reviewCadence}),t.jsxs("div",{style:{border:`1px solid ${o.headerBorder}`,borderRadius:8,background:o.sidebarBg,padding:12},children:[t.jsx("div",{style:{fontWeight:800,color:o.textPrimary,marginBottom:10},children:"Business metadata"}),t.jsx("div",{style:{display:"grid",gap:8},children:i.map(d=>t.jsxs("div",{style:{display:"grid",gap:3},children:[t.jsx("div",{style:{color:o.textMuted,fontSize:10,fontWeight:800,textTransform:"uppercase"},children:d.label}),t.jsx("div",{style:{color:o.textSecondary,fontSize:12,lineHeight:1.45},children:d.value})]},d.label))})]})}function b({title:n,connections:o,t:e}){return t.jsxs("div",{style:{border:`1px solid ${e.headerBorder}`,borderRadius:8,background:e.sidebarBg,padding:12},children:[t.jsx("div",{style:{fontWeight:800,color:e.textPrimary,marginBottom:10},children:n}),o.length===0?t.jsxs("div",{style:{color:e.textMuted,fontSize:12},children:["No ",n.toLowerCase()," connections in this focused window."]}):t.jsxs("div",{style:{display:"grid",gap:7},children:[o.slice(0,8).map(({edge:i,node:d})=>{const a=j[d.type]??e.textMuted;return t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"92px 1fr",gap:8,minWidth:0,fontSize:12},children:[t.jsx("span",{style:{color:e.textMuted},children:N[i.type]??i.type}),t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,minWidth:0},children:[t.jsx("span",{style:{color:e.appBg,background:a,borderRadius:3,padding:"1px 4px",fontSize:9,fontWeight:800,flexShrink:0},children:S[d.type]??d.type.slice(0,4).toUpperCase()}),t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:d.name,children:d.name})]})]},`${i.source}-${i.target}-${i.type}`)}),o.length>8&&t.jsxs("div",{style:{color:e.textMuted,fontSize:12},children:[o.length-8," more connection",o.length-8===1?"":"s"," in the graph"]})]})]})}export{U as BusinessArtifactView};
1
+ import{u as C,t as k,r as l,a as I,j as t,p as j,q as S,au as L,av as N}from"./index-9w93YPF9.js";import{M as W}from"./MiniLineageGraph-DT_ycl6s.js";import"./react-CRB3T2We.js";import"./dagre.esm-BjYSO53F.js";function w(n){return n.replace(/\.(dqlnb|dql)$/i,"")}function $(n,o){return`${n}:${w(o)}`}function U(){var y,x;const{state:n,dispatch:o}=C(),e=k[n.themeMode],i=n.activeFile,d=i&&(i.type==="term"||i.type==="business_view")?$(i.type,i.name):null,[a,B]=l.useState({nodes:[],edges:[],focalNode:null}),[M,u]=l.useState(!1);l.useEffect(()=>{if(!d)return;let s=!1;return u(!0),I.queryLineage({focus:d,upstreamDepth:3,downstreamDepth:3}).then(h=>{var f,v;s||(B({nodes:((f=h.graph)==null?void 0:f.nodes)??[],edges:((v=h.graph)==null?void 0:v.edges)??[],focalNode:h.focalNode??null}),u(!1))}).catch(()=>{s||u(!1)}),()=>{s=!0}},[d]);const r=a.focalNode,c=l.useMemo(()=>new Map(a.nodes.map(s=>[s.id,s])),[a.nodes]),g=l.useMemo(()=>r?a.edges.filter(s=>s.target===r.id).map(s=>({edge:s,node:c.get(s.source)})).filter(s=>!!s.node):[],[r,a.edges,c]),m=l.useMemo(()=>r?a.edges.filter(s=>s.source===r.id).map(s=>({edge:s,node:c.get(s.target)})).filter(s=>!!s.node):[],[r,a.edges,c]);if(!i||!d)return t.jsx("div",{style:{flex:1,padding:24,color:e.textMuted},children:"Select a business term or business view from Explorer."});const p=(r==null?void 0:r.type)??i.type,T=j[p]??e.accent,E=S[p]??p.toUpperCase(),z=((y=r==null?void 0:r.metadata)==null?void 0:y.path)??((x=r==null?void 0:r.metadata)==null?void 0:x.filePath)??i.path;return t.jsxs("div",{style:{flex:1,minWidth:0,overflow:"auto",background:"var(--color-bg-primary)"},children:[t.jsx("div",{style:{padding:"22px 28px 18px",borderBottom:`1px solid ${e.headerBorder}`,background:e.appBg},children:t.jsx("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16},children:t.jsxs("div",{style:{minWidth:0},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[t.jsx("span",{style:{color:e.appBg,background:T,borderRadius:5,padding:"3px 7px",fontSize:10,fontWeight:800,letterSpacing:0},title:L[p]??p,children:E}),t.jsxs("span",{style:{color:e.textMuted,fontSize:12},children:["Lineage · ↑ ",g.length," · ↓ ",m.length]})]}),t.jsx("h1",{style:{margin:0,fontSize:26,lineHeight:1.15,color:e.textPrimary},children:(r==null?void 0:r.name)??w(i.name)}),t.jsx("div",{style:{marginTop:7,color:e.textMuted,fontSize:13},children:i.type==="term"?"Business definition used by blocks, views, dashboards, and AI agents.":"Business composition built from trusted terms, DQL blocks, and other business views."})]})})}),t.jsxs("div",{style:{padding:24,display:"grid",gridTemplateColumns:"minmax(300px, 420px) minmax(420px, 1fr)",gap:18},children:[t.jsxs("section",{style:{display:"grid",gap:14,alignContent:"start"},children:[r&&t.jsx(P,{node:r,t:e}),t.jsx(b,{title:"Upstream",connections:g,t:e}),t.jsx(b,{title:"Downstream",connections:m,t:e}),t.jsxs("div",{style:{border:`1px solid ${e.headerBorder}`,borderRadius:8,padding:12,color:e.textMuted,fontSize:12,background:e.sidebarBg},children:[t.jsx("div",{style:{fontWeight:800,color:e.textSecondary,marginBottom:6},children:"Source file"}),t.jsx("div",{style:{overflowWrap:"anywhere"},children:String(z)})]})]}),t.jsxs("section",{style:{minHeight:520,border:`1px solid ${e.headerBorder}`,borderRadius:8,background:e.sidebarBg,overflow:"hidden"},children:[t.jsxs("div",{style:{padding:"12px 14px",borderBottom:`1px solid ${e.headerBorder}`},children:[t.jsx("div",{style:{fontWeight:800,color:e.textPrimary,fontSize:14},children:"Focused lineage"}),t.jsxs("div",{style:{color:e.textMuted,fontSize:12,marginTop:3},children:["Technical inputs and business composition for this ",i.type==="term"?"term":"view","."]})]}),t.jsx("div",{style:{height:470,padding:12},children:M?t.jsx("div",{style:{color:e.textMuted,fontSize:12},children:"Loading lineage..."}):a.nodes.length===0?t.jsx("div",{style:{color:e.textMuted,fontSize:12},children:"No lineage available."}):t.jsx(W,{nodes:a.nodes,edges:a.edges,focalNodeId:d,height:"100%",onNodeClick:s=>{o({type:"SET_LINEAGE_FOCUS",nodeId:s})},interactive:!0})})]})]})]})}function P({node:n,t:o}){const e=n.metadata??{},i=[];return n.domain&&i.push({label:"Domain",value:n.domain}),n.owner&&i.push({label:"Owner",value:n.owner}),n.status&&i.push({label:"Status",value:n.status}),n.type==="term"&&typeof e.termType=="string"&&i.push({label:"Term Type",value:e.termType}),Array.isArray(e.identifiers)&&e.identifiers.length>0&&i.push({label:"Identifiers",value:e.identifiers.map(String).join(", ")}),Array.isArray(e.synonyms)&&e.synonyms.length>0&&i.push({label:"Synonyms",value:e.synonyms.map(String).join(", ")}),typeof e.description=="string"&&e.description.trim()&&i.push({label:"Description",value:e.description}),typeof e.businessOutcome=="string"&&e.businessOutcome.trim()&&i.push({label:"Business Outcome",value:e.businessOutcome}),typeof e.decisionUse=="string"&&e.decisionUse.trim()&&i.push({label:"Decision Use",value:e.decisionUse}),typeof e.reviewCadence=="string"&&e.reviewCadence.trim()&&i.push({label:"Review Cadence",value:e.reviewCadence}),t.jsxs("div",{style:{border:`1px solid ${o.headerBorder}`,borderRadius:8,background:o.sidebarBg,padding:12},children:[t.jsx("div",{style:{fontWeight:800,color:o.textPrimary,marginBottom:10},children:"Business metadata"}),t.jsx("div",{style:{display:"grid",gap:8},children:i.map(d=>t.jsxs("div",{style:{display:"grid",gap:3},children:[t.jsx("div",{style:{color:o.textMuted,fontSize:10,fontWeight:800,textTransform:"uppercase"},children:d.label}),t.jsx("div",{style:{color:o.textSecondary,fontSize:12,lineHeight:1.45},children:d.value})]},d.label))})]})}function b({title:n,connections:o,t:e}){return t.jsxs("div",{style:{border:`1px solid ${e.headerBorder}`,borderRadius:8,background:e.sidebarBg,padding:12},children:[t.jsx("div",{style:{fontWeight:800,color:e.textPrimary,marginBottom:10},children:n}),o.length===0?t.jsxs("div",{style:{color:e.textMuted,fontSize:12},children:["No ",n.toLowerCase()," connections in this focused window."]}):t.jsxs("div",{style:{display:"grid",gap:7},children:[o.slice(0,8).map(({edge:i,node:d})=>{const a=j[d.type]??e.textMuted;return t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"92px 1fr",gap:8,minWidth:0,fontSize:12},children:[t.jsx("span",{style:{color:e.textMuted},children:N[i.type]??i.type}),t.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,minWidth:0},children:[t.jsx("span",{style:{color:e.appBg,background:a,borderRadius:3,padding:"1px 4px",fontSize:9,fontWeight:800,flexShrink:0},children:S[d.type]??d.type.slice(0,4).toUpperCase()}),t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:d.name,children:d.name})]})]},`${i.source}-${i.target}-${i.type}`)}),o.length>8&&t.jsxs("div",{style:{color:e.textMuted,fontSize:12},children:[o.length-8," more connection",o.length-8===1?"":"s"," in the graph"]})]})]})}export{U as BusinessArtifactView};