@duckcodeailabs/dql-cli 1.12.3 → 1.12.5

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 (79) hide show
  1. package/dist/assets/dql-notebook/assets/AgentAnswerCard-BJAnjaLA.js +5 -0
  2. package/dist/assets/dql-notebook/assets/{AgentLogPage-CsSC2tOR.js → AgentLogPage-J72WR6hk.js} +1 -1
  3. package/dist/assets/dql-notebook/assets/{AiBuildDialog-CjJ-9bQW.js → AiBuildDialog-CHJZfDmp.js} +1 -1
  4. package/dist/assets/dql-notebook/assets/{AiBuildResult-BvTcW9oE.js → AiBuildResult-Da7_Cn12.js} +1 -1
  5. package/dist/assets/dql-notebook/assets/{AiSidePanel-CxFrOfCE.js → AiSidePanel-BY6W_5aC.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AnalyticsHome-BtXEdJNR.js → AnalyticsHome-u-buXgdv.js} +1 -1
  7. package/dist/assets/dql-notebook/assets/{AppsView-HjQkbbE6.js → AppsView-3k7ftDpd.js} +3 -3
  8. package/dist/assets/dql-notebook/assets/{BlockStudio-oQHTJsXC.js → BlockStudio-CLX4EUyO.js} +14 -14
  9. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-Dpsftjs7.js → BusinessArtifactView-3THMNeyO.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-c6ZteaI6.js → DbtFirstModelingPage-BwBPwtdA.js} +1 -1
  11. package/dist/assets/dql-notebook/assets/{GitPage-Cj6mc-Yv.js → GitPage-CvEki0pe.js} +1 -1
  12. package/dist/assets/dql-notebook/assets/{GlobalAiRail-8G_rEyhK.js → GlobalAiRail-NXdk9kNy.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/{GovernedContextPage-BTtzt0Za.js → GovernedContextPage-DILbw-Vr.js} +1 -1
  14. package/dist/assets/dql-notebook/assets/{HelpDocsPage-e2CesE73.js → HelpDocsPage-DgCu4bvY.js} +1 -1
  15. package/dist/assets/dql-notebook/assets/{HomePage-U3ryMLEF.js → HomePage-CK3fXTQo.js} +1 -1
  16. package/dist/assets/dql-notebook/assets/{LineageDAG-CEmgJzm3.js → LineageDAG-DW_NO3P2.js} +1 -1
  17. package/dist/assets/dql-notebook/assets/{LineageDetailView-CeV5QMXS.js → LineageDetailView-VT7DLJOB.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{LineageDrawer-B1oAn-N_.js → LineageDrawer-DSTm8aXw.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-fP6RTXut.js → LineagePathBreadcrumb-DRlAYasJ.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-CBYSTmRC.js → MiniLineageGraph-CR_nhwhZ.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/{NewBlockModal-ksEwimjl.js → NewBlockModal-CJvjYiBF.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{NewNotebookModal-CUx0WmXb.js → NewNotebookModal-BEpPH93n.js} +1 -1
  23. package/dist/assets/dql-notebook/assets/{NotebookEditor-BdxJL3LX.js → NotebookEditor-C7GDFwhF.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{ReadinessPage-DZ9wDW76.js → ReadinessPage-rZiOp2xr.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{SetupOnboarding-Bt0AAe0h.js → SetupOnboarding-BWjhTjPB.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{TrustBadge-DNVJK_mP.js → TrustBadge-RvZ9s6OQ.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/{UnifiedAgentRunPanel-BNqE169i.js → UnifiedAgentRunPanel-CGPcpY1B.js} +18 -18
  28. package/dist/assets/dql-notebook/assets/{answer-to-notebook-B_gE6rsY.js → answer-to-notebook-Di227Cd4.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{arrow-left-DnKGhzOR.js → arrow-left-BZHDcWHR.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{arrow-right-CQ73DG7_.js → arrow-right-DlM1pC3_.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/{book-open-text-CyBV5Nhw.js → book-open-text-DBcXFQAu.js} +1 -1
  32. package/dist/assets/dql-notebook/assets/{bot-UOPtBzCj.js → bot-BAywbvPm.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{chevron-up-CDHDU3N3.js → chevron-up-B_GfKE_F.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{circle-x-DC5nkL_u.js → circle-x-BcxtZ-ym.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{dagre.esm-C7ujXipB.js → dagre.esm-Bqs0lsEz.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{external-link-BiJ_dtTM.js → external-link-B24Dk9_t.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{grip-vertical-eXvkUerq.js → grip-vertical-D9g31N3j.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/index-DU7j3Sqk.js +644 -0
  39. package/dist/assets/dql-notebook/assets/{link-2-DkHVJTuH.js → link-2-B36oR5Bj.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/{list-tree-8lYW2Itb.js → list-tree-B9ZzGc4U.js} +1 -1
  41. package/dist/assets/dql-notebook/assets/{maximize-2-DjSovOdP.js → maximize-2-BrvQLPoj.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{minimize-2-DGlmQLES.js → minimize-2-BrpFmsxS.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{panel-right-open-DPc4gShM.js → panel-right-open-B1g1qhh5.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{pencil-nwaGtOdL.js → pencil-DwywbTqQ.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{rotate-ccw-ByjLhAu7.js → rotate-ccw-Db_KVs3J.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{semantic-fields-eEhwnQhG.js → semantic-fields-BIVuvP2l.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{triangle-alert-zws0cKhp.js → triangle-alert-Cne6C2aG.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-D6mtrJ-_.js +18 -0
  49. package/dist/assets/dql-notebook/assets/{user-round-CM8xNakq.js → user-round-DkzxN1xD.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{wand-sparkles-CIKc8r-4.js → wand-sparkles-CJUvFtur.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{workflow-6C0ZLbTi.js → workflow-BOvVTg7R.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{wrench-CeU7hF12.js → wrench-YeSpzZRt.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/{x-DLWEzvri.js → x-C6tsHUR7.js} +1 -1
  54. package/dist/assets/dql-notebook/index.html +1 -1
  55. package/dist/block-invocation.js +4 -0
  56. package/dist/block-invocation.js.map +1 -1
  57. package/dist/llm/answer-loop-tools.d.ts +8 -2
  58. package/dist/llm/answer-loop-tools.d.ts.map +1 -1
  59. package/dist/llm/answer-loop-tools.js +29 -2
  60. package/dist/llm/answer-loop-tools.js.map +1 -1
  61. package/dist/llm/providers/dql-agent-provider.d.ts +27 -1
  62. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  63. package/dist/llm/providers/dql-agent-provider.js +79 -15
  64. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  65. package/dist/llm/types.d.ts +8 -1
  66. package/dist/llm/types.d.ts.map +1 -1
  67. package/dist/local-runtime.d.ts +46 -0
  68. package/dist/local-runtime.d.ts.map +1 -1
  69. package/dist/local-runtime.js +647 -66
  70. package/dist/local-runtime.js.map +1 -1
  71. package/dist/package.json +10 -10
  72. package/dist/sql-result-filter.d.ts +39 -0
  73. package/dist/sql-result-filter.d.ts.map +1 -0
  74. package/dist/sql-result-filter.js +256 -0
  75. package/dist/sql-result-filter.js.map +1 -0
  76. package/package.json +10 -10
  77. package/dist/assets/dql-notebook/assets/AgentAnswerCard-BEIwKGm4.js +0 -5
  78. package/dist/assets/dql-notebook/assets/index-BMVfPaXr.js +0 -644
  79. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-hxi1RZDm.js +0 -18
@@ -1,644 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/HomePage-U3ryMLEF.js","assets/TrustBadge-DNVJK_mP.js","assets/arrow-right-CQ73DG7_.js","assets/triangle-alert-zws0cKhp.js","assets/book-open-text-CyBV5Nhw.js","assets/workflow-6C0ZLbTi.js","assets/react-CRB3T2We.js","assets/AnalyticsHome-BtXEdJNR.js","assets/answer-to-notebook-B_gE6rsY.js","assets/UnifiedAgentRunPanel-BNqE169i.js","assets/AgentAnswerCard-BEIwKGm4.js","assets/usePersistedAgentThreadId-hxi1RZDm.js","assets/AiBuildResult-BvTcW9oE.js","assets/user-round-CM8xNakq.js","assets/rotate-ccw-ByjLhAu7.js","assets/x-DLWEzvri.js","assets/pencil-nwaGtOdL.js","assets/list-tree-8lYW2Itb.js","assets/wrench-CeU7hF12.js","assets/chevron-up-CDHDU3N3.js","assets/GlobalAiRail-8G_rEyhK.js","assets/AiSidePanel-CxFrOfCE.js","assets/minimize-2-DGlmQLES.js","assets/maximize-2-DjSovOdP.js","assets/NotebookEditor-BdxJL3LX.js","assets/LineagePathBreadcrumb-fP6RTXut.js","assets/codemirror-1_I9gm6Z.js","assets/semantic-fields-eEhwnQhG.js","assets/MiniLineageGraph-CBYSTmRC.js","assets/dagre.esm-C7ujXipB.js","assets/dagre-BZV40eAE.css","assets/link-2-DkHVJTuH.js","assets/NewNotebookModal-CUx0WmXb.js","assets/NewBlockModal-ksEwimjl.js","assets/SetupOnboarding-Bt0AAe0h.js","assets/arrow-left-DnKGhzOR.js","assets/BlockStudio-oQHTJsXC.js","assets/panel-right-open-DPc4gShM.js","assets/bot-UOPtBzCj.js","assets/BusinessArtifactView-Dpsftjs7.js","assets/LineageDetailView-CeV5QMXS.js","assets/LineageDAG-CEmgJzm3.js","assets/HelpDocsPage-e2CesE73.js","assets/GitPage-Cj6mc-Yv.js","assets/external-link-BiJ_dtTM.js","assets/ReadinessPage-DZ9wDW76.js","assets/ai-build-bus-1BR770pY.js","assets/wand-sparkles-CIKc8r-4.js","assets/AgentLogPage-CsSC2tOR.js","assets/circle-x-DC5nkL_u.js","assets/GovernedContextPage-BTtzt0Za.js","assets/DbtFirstModelingPage-c6ZteaI6.js","assets/AppsView-HjQkbbE6.js","assets/grip-vertical-eXvkUerq.js","assets/LineageDrawer-B1oAn-N_.js","assets/AiBuildDialog-CjJ-9bQW.js"])))=>i.map(i=>d[i]);
2
- var Id=Object.defineProperty;var Ld=(e,t,n)=>t in e?Id(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ce=(e,t,n)=>Ld(e,typeof t!="symbol"?t+"":t,n);import{r as Ta,a as Ra,g as _a}from"./react-CRB3T2We.js";function Nd(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const o in r)if(o!=="default"&&!(o in e)){const i=Object.getOwnPropertyDescriptor(r,o);i&&Object.defineProperty(e,o,i.get?i:{enumerable:!0,get:()=>r[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var ao={exports:{}},jn={};/**
3
- * @license React
4
- * react-jsx-runtime.production.min.js
5
- *
6
- * Copyright (c) Facebook, Inc. and its affiliates.
7
- *
8
- * This source code is licensed under the MIT license found in the
9
- * LICENSE file in the root directory of this source tree.
10
- */var ti;function Bd(){if(ti)return jn;ti=1;var e=Ta(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function l(a,d,c){var f,p={},h=null,g=null;c!==void 0&&(h=""+c),d.key!==void 0&&(h=""+d.key),d.ref!==void 0&&(g=d.ref);for(f in d)r.call(d,f)&&!i.hasOwnProperty(f)&&(p[f]=d[f]);if(a&&a.defaultProps)for(f in d=a.defaultProps,d)p[f]===void 0&&(p[f]=d[f]);return{$$typeof:t,type:a,key:h,ref:g,props:p,_owner:o.current}}return jn.Fragment=n,jn.jsx=l,jn.jsxs=l,jn}var ni;function Fd(){return ni||(ni=1,ao.exports=Bd()),ao.exports}var s=Fd(),lr={},ri;function zd(){if(ri)return lr;ri=1;var e=Ra();return lr.createRoot=e.createRoot,lr.hydrateRoot=e.hydrateRoot,lr}var qd=zd(),u=Ta();const Pe=_a(u),$a=Nd({__proto__:null,default:Pe},[u]),pe={gray0:"#ffffff",gray50:"#f6f8fa",gray100:"#eaeef2",gray200:"#d0d7de",gray300:"#afb8c1",gray400:"#8c959f",gray600:"#57606a",gray900:"#24292f",gray950:"#1c2128",gray975:"#161b22",gray1000:"#0d1117",blue400:"#58a6ff",blue500:"#388bfd",blue600:"#0969da",blue700:"#0550ae",green500:"#56d364",green600:"#1f883d",red500:"#f85149",red600:"#cf222e",yellow500:"#e3b341",yellow600:"#9a6700"},fe={1:"4px",2:"8px",3:"12px",4:"16px"},Dt={sm:"4px",md:"6px",lg:"8px"},Be={xs:"11px",sm:"12px",md:"14px"},Zo={medium:"500",semibold:"600"},zn={overlay:1e3,modal:1100,popover:1200,tooltip:1300},lo={surfaceBase:pe.gray1000,surfaceRaised:pe.gray975,surfaceElevated:pe.gray950,surfaceOverlay:"rgba(0,0,0,0.7)",surfaceHover:pe.gray900,surfaceActive:"#1f2d3d",surfaceSunken:pe.gray1000,borderSubtle:"#21262d",borderDefault:"#30363d",borderStrong:"#484f58",borderFocus:pe.blue500,textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",textDisabled:"#32383f",textInverse:pe.gray1000,accent:pe.blue500,accentHover:pe.blue400,accentMuted:"rgba(56,139,253,0.15)",accentContrast:"#ffffff",success:pe.green500,warning:pe.yellow500,danger:pe.red500,info:pe.blue400,shadowSm:"0 1px 2px rgba(0,0,0,0.4)",shadowMd:"0 4px 10px rgba(0,0,0,0.45)",shadowLg:"0 12px 28px rgba(0,0,0,0.55)"},cr={surfaceBase:pe.gray0,surfaceRaised:pe.gray50,surfaceElevated:pe.gray0,surfaceOverlay:"rgba(0,0,0,0.4)",surfaceHover:pe.gray100,surfaceActive:"#dbeafe",surfaceSunken:pe.gray50,borderSubtle:pe.gray100,borderDefault:pe.gray200,borderStrong:pe.gray300,borderFocus:pe.blue600,textPrimary:"#1f2328",textSecondary:pe.gray600,textMuted:pe.gray400,textDisabled:pe.gray300,textInverse:pe.gray0,accent:pe.blue600,accentHover:pe.blue700,accentMuted:"rgba(9,105,218,0.12)",accentContrast:"#ffffff",success:pe.green600,warning:pe.yellow600,danger:pe.red600,info:pe.blue600,shadowSm:"0 1px 2px rgba(31,35,40,0.08)",shadowMd:"0 4px 10px rgba(31,35,40,0.1)",shadowLg:"0 12px 28px rgba(31,35,40,0.15)"},Ud={obsidian:lo,paper:cr,white:cr,dark:lo,light:cr,midnight:lo,arctic:cr};function Oa(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function oi(e){const t={};for(const[n,r]of Object.entries(e))t[Oa(n)]=r;return t}function le(e){return`var(${Oa(e)})`}const Wd=u.createContext(null);function Kd({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[i,l]=u.useState(t),a=e??i,d=Ud[a],c=u.useCallback(h=>{e===void 0&&l(h),n==null||n(h)},[e,n]);u.useEffect(()=>{if(!r)return;const h=oi(d),g=document.documentElement;for(const[S,x]of Object.entries(h))g.style.setProperty(S,x);return g.setAttribute("data-theme",a),()=>{for(const S of Object.keys(h))g.style.removeProperty(S);g.removeAttribute("data-theme")}},[r,a,d]);const f=u.useMemo(()=>({theme:a,tokens:d,setTheme:c}),[a,d,c]),p=r?void 0:oi(d);return s.jsx(Wd.Provider,{value:f,children:s.jsx("div",{"data-theme":a,style:p,children:o})})}function ie(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function si(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ur(...e){return t=>{let n=!1;const r=e.map(o=>{const i=si(o,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){const i=r[o];typeof i=="function"?i():si(e[o],null)}}}}function we(...e){return u.useCallback(Ur(...e),e)}function Vd(e,t){const n=u.createContext(t),r=i=>{const{children:l,...a}=i,d=u.useMemo(()=>a,Object.values(a));return s.jsx(n.Provider,{value:d,children:l})};r.displayName=e+"Provider";function o(i){const l=u.useContext(n);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[r,o]}function Mt(e,t=[]){let n=[];function r(i,l){const a=u.createContext(l),d=n.length;n=[...n,l];const c=p=>{var k;const{scope:h,children:g,...S}=p,x=((k=h==null?void 0:h[e])==null?void 0:k[d])||a,b=u.useMemo(()=>S,Object.values(S));return s.jsx(x.Provider,{value:b,children:g})};c.displayName=i+"Provider";function f(p,h){var x;const g=((x=h==null?void 0:h[e])==null?void 0:x[d])||a,S=u.useContext(g);if(S)return S;if(l!==void 0)return l;throw new Error(`\`${p}\` must be used within \`${i}\``)}return[c,f]}const o=()=>{const i=n.map(l=>u.createContext(l));return function(a){const d=(a==null?void 0:a[e])||i;return u.useMemo(()=>({[`__scope${e}`]:{...a,[e]:d}}),[a,d])}};return o.scopeName=e,[r,Hd(o,...t)]}function Hd(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const l=r.reduce((a,{useScope:d,scopeName:c})=>{const p=d(i)[`__scope${c}`];return{...a,...p}},{});return u.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}var es=Ra();const Gd=_a(es);function hn(e){const t=Jd(e),n=u.forwardRef((r,o)=>{const{children:i,...l}=r,a=u.Children.toArray(i),d=a.find(Yd);if(d){const c=d.props.children,f=a.map(p=>p===d?u.Children.count(c)>1?u.Children.only(null):u.isValidElement(c)?c.props.children:null:p);return s.jsx(t,{...l,ref:o,children:u.isValidElement(c)?u.cloneElement(c,void 0,f):null})}return s.jsx(t,{...l,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Jd(e){const t=u.forwardRef((n,r)=>{const{children:o,...i}=n;if(u.isValidElement(o)){const l=Zd(o),a=Xd(i,o.props);return o.type!==u.Fragment&&(a.ref=r?Ur(r,l):l),u.cloneElement(o,a)}return u.Children.count(o)>1?u.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Pa=Symbol("radix.slottable");function Qd(e){const t=({children:n})=>s.jsx(s.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Pa,t}function Yd(e){return u.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Pa}function Xd(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{const d=i(...a);return o(...a),d}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Zd(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var eu=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ve=eu.reduce((e,t)=>{const n=hn(`Primitive.${t}`),r=u.forwardRef((o,i)=>{const{asChild:l,...a}=o,d=l?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(d,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Da(e,t){e&&es.flushSync(()=>e.dispatchEvent(t))}function Rt(e){const t=u.useRef(e);return u.useEffect(()=>{t.current=e}),u.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function tu(e,t=globalThis==null?void 0:globalThis.document){const n=Rt(e);u.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var nu="DismissableLayer",Lo="dismissableLayer.update",ru="dismissableLayer.pointerDownOutside",ou="dismissableLayer.focusOutside",ii,Ma=u.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Jn=u.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:l,onDismiss:a,...d}=e,c=u.useContext(Ma),[f,p]=u.useState(null),h=(f==null?void 0:f.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,g]=u.useState({}),S=we(t,R=>p(R)),x=Array.from(c.layers),[b]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),k=x.indexOf(b),C=f?x.indexOf(f):-1,E=c.layersWithOutsidePointerEventsDisabled.size>0,v=C>=k,w=au(R=>{const y=R.target,M=[...c.branches].some($=>$.contains(y));!v||M||(o==null||o(R),l==null||l(R),R.defaultPrevented||a==null||a())},h),A=lu(R=>{const y=R.target;[...c.branches].some($=>$.contains(y))||(i==null||i(R),l==null||l(R),R.defaultPrevented||a==null||a())},h);return tu(R=>{C===c.layers.size-1&&(r==null||r(R),!R.defaultPrevented&&a&&(R.preventDefault(),a()))},h),u.useEffect(()=>{if(f)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(ii=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(f)),c.layers.add(f),ai(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=ii)}},[f,h,n,c]),u.useEffect(()=>()=>{f&&(c.layers.delete(f),c.layersWithOutsidePointerEventsDisabled.delete(f),ai())},[f,c]),u.useEffect(()=>{const R=()=>g({});return document.addEventListener(Lo,R),()=>document.removeEventListener(Lo,R)},[]),s.jsx(ve.div,{...d,ref:S,style:{pointerEvents:E?v?"auto":"none":void 0,...e.style},onFocusCapture:ie(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ie(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ie(e.onPointerDownCapture,w.onPointerDownCapture)})});Jn.displayName=nu;var su="DismissableLayerBranch",iu=u.forwardRef((e,t)=>{const n=u.useContext(Ma),r=u.useRef(null),o=we(t,r);return u.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),s.jsx(ve.div,{...e,ref:o})});iu.displayName=su;function au(e,t=globalThis==null?void 0:globalThis.document){const n=Rt(e),r=u.useRef(!1),o=u.useRef(()=>{});return u.useEffect(()=>{const i=a=>{if(a.target&&!r.current){let d=function(){Ia(ru,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=d,t.addEventListener("click",o.current,{once:!0})):d()}else t.removeEventListener("click",o.current);r.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function lu(e,t=globalThis==null?void 0:globalThis.document){const n=Rt(e),r=u.useRef(!1);return u.useEffect(()=>{const o=i=>{i.target&&!r.current&&Ia(ou,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function ai(){const e=new CustomEvent(Lo);document.dispatchEvent(e)}function Ia(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?Da(o,i):o.dispatchEvent(i)}var _t=globalThis!=null&&globalThis.document?u.useLayoutEffect:()=>{},cu=$a[" useId ".trim().toString()]||(()=>{}),du=0;function Ln(e){const[t,n]=u.useState(cu());return _t(()=>{n(r=>r??String(du++))},[e]),t?`radix-${t}`:""}const uu=["top","right","bottom","left"],$t=Math.min,Ye=Math.max,Rr=Math.round,dr=Math.floor,yt=e=>({x:e,y:e}),pu={left:"right",right:"left",bottom:"top",top:"bottom"};function No(e,t,n){return Ye(e,$t(t,n))}function wt(e,t){return typeof e=="function"?e(t):e}function jt(e){return e.split("-")[0]}function xn(e){return e.split("-")[1]}function ts(e){return e==="x"?"y":"x"}function ns(e){return e==="y"?"height":"width"}function gt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function rs(e){return ts(gt(e))}function fu(e,t,n){n===void 0&&(n=!1);const r=xn(e),o=rs(e),i=ns(o);let l=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=_r(l)),[l,_r(l)]}function hu(e){const t=_r(e);return[Bo(e),t,Bo(t)]}function Bo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const li=["left","right"],ci=["right","left"],mu=["top","bottom"],gu=["bottom","top"];function yu(e,t,n){switch(e){case"top":case"bottom":return n?t?ci:li:t?li:ci;case"left":case"right":return t?mu:gu;default:return[]}}function xu(e,t,n,r){const o=xn(e);let i=yu(jt(e),n==="start",r);return o&&(i=i.map(l=>l+"-"+o),t&&(i=i.concat(i.map(Bo)))),i}function _r(e){const t=jt(e);return pu[t]+e.slice(t.length)}function bu(e){return{top:0,right:0,bottom:0,left:0,...e}}function La(e){return typeof e!="number"?bu(e):{top:e,right:e,bottom:e,left:e}}function $r(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function di(e,t,n){let{reference:r,floating:o}=e;const i=gt(t),l=rs(t),a=ns(l),d=jt(t),c=i==="y",f=r.x+r.width/2-o.width/2,p=r.y+r.height/2-o.height/2,h=r[a]/2-o[a]/2;let g;switch(d){case"top":g={x:f,y:r.y-o.height};break;case"bottom":g={x:f,y:r.y+r.height};break;case"right":g={x:r.x+r.width,y:p};break;case"left":g={x:r.x-o.width,y:p};break;default:g={x:r.x,y:r.y}}switch(xn(t)){case"start":g[l]-=h*(n&&c?-1:1);break;case"end":g[l]+=h*(n&&c?-1:1);break}return g}async function vu(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:i,rects:l,elements:a,strategy:d}=e,{boundary:c="clippingAncestors",rootBoundary:f="viewport",elementContext:p="floating",altBoundary:h=!1,padding:g=0}=wt(t,e),S=La(g),b=a[h?p==="floating"?"reference":"floating":p],k=$r(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(b)))==null||n?b:b.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(a.floating)),boundary:c,rootBoundary:f,strategy:d})),C=p==="floating"?{x:r,y:o,width:l.floating.width,height:l.floating.height}:l.reference,E=await(i.getOffsetParent==null?void 0:i.getOffsetParent(a.floating)),v=await(i.isElement==null?void 0:i.isElement(E))?await(i.getScale==null?void 0:i.getScale(E))||{x:1,y:1}:{x:1,y:1},w=$r(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:C,offsetParent:E,strategy:d}):C);return{top:(k.top-w.top+S.top)/v.y,bottom:(w.bottom-k.bottom+S.bottom)/v.y,left:(k.left-w.left+S.left)/v.x,right:(w.right-k.right+S.right)/v.x}}const Su=50,ku=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:l}=n,a=l.detectOverflow?l:{...l,detectOverflow:vu},d=await(l.isRTL==null?void 0:l.isRTL(t));let c=await l.getElementRects({reference:e,floating:t,strategy:o}),{x:f,y:p}=di(c,r,d),h=r,g=0;const S={};for(let x=0;x<i.length;x++){const b=i[x];if(!b)continue;const{name:k,fn:C}=b,{x:E,y:v,data:w,reset:A}=await C({x:f,y:p,initialPlacement:r,placement:h,strategy:o,middlewareData:S,rects:c,platform:a,elements:{reference:e,floating:t}});f=E??f,p=v??p,S[k]={...S[k],...w},A&&g<Su&&(g++,typeof A=="object"&&(A.placement&&(h=A.placement),A.rects&&(c=A.rects===!0?await l.getElementRects({reference:e,floating:t,strategy:o}):A.rects),{x:f,y:p}=di(c,h,d)),x=-1)}return{x:f,y:p,placement:h,strategy:o,middlewareData:S}},wu=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:l,elements:a,middlewareData:d}=t,{element:c,padding:f=0}=wt(e,t)||{};if(c==null)return{};const p=La(f),h={x:n,y:r},g=rs(o),S=ns(g),x=await l.getDimensions(c),b=g==="y",k=b?"top":"left",C=b?"bottom":"right",E=b?"clientHeight":"clientWidth",v=i.reference[S]+i.reference[g]-h[g]-i.floating[S],w=h[g]-i.reference[g],A=await(l.getOffsetParent==null?void 0:l.getOffsetParent(c));let R=A?A[E]:0;(!R||!await(l.isElement==null?void 0:l.isElement(A)))&&(R=a.floating[E]||i.floating[S]);const y=v/2-w/2,M=R/2-x[S]/2-1,$=$t(p[k],M),T=$t(p[C],M),L=$,I=R-x[S]-T,G=R/2-x[S]/2+y,Y=No(L,G,I),P=!d.arrow&&xn(o)!=null&&G!==Y&&i.reference[S]/2-(G<L?$:T)-x[S]/2<0,q=P?G<L?G-L:G-I:0;return{[g]:h[g]+q,data:{[g]:Y,centerOffset:G-Y-q,...P&&{alignmentOffset:q}},reset:P}}}),ju=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:i,rects:l,initialPlacement:a,platform:d,elements:c}=t,{mainAxis:f=!0,crossAxis:p=!0,fallbackPlacements:h,fallbackStrategy:g="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:x=!0,...b}=wt(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const k=jt(o),C=gt(a),E=jt(a)===a,v=await(d.isRTL==null?void 0:d.isRTL(c.floating)),w=h||(E||!x?[_r(a)]:hu(a)),A=S!=="none";!h&&A&&w.push(...xu(a,x,S,v));const R=[a,...w],y=await d.detectOverflow(t,b),M=[];let $=((r=i.flip)==null?void 0:r.overflows)||[];if(f&&M.push(y[k]),p){const G=fu(o,l,v);M.push(y[G[0]],y[G[1]])}if($=[...$,{placement:o,overflows:M}],!M.every(G=>G<=0)){var T,L;const G=(((T=i.flip)==null?void 0:T.index)||0)+1,Y=R[G];if(Y&&(!(p==="alignment"?C!==gt(Y):!1)||$.every(O=>gt(O.placement)===C?O.overflows[0]>0:!0)))return{data:{index:G,overflows:$},reset:{placement:Y}};let P=(L=$.filter(q=>q.overflows[0]<=0).sort((q,O)=>q.overflows[1]-O.overflows[1])[0])==null?void 0:L.placement;if(!P)switch(g){case"bestFit":{var I;const q=(I=$.filter(O=>{if(A){const W=gt(O.placement);return W===C||W==="y"}return!0}).map(O=>[O.placement,O.overflows.filter(W=>W>0).reduce((W,se)=>W+se,0)]).sort((O,W)=>O[1]-W[1])[0])==null?void 0:I[0];q&&(P=q);break}case"initialPlacement":P=a;break}if(o!==P)return{reset:{placement:P}}}return{}}}};function ui(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function pi(e){return uu.some(t=>e[t]>=0)}const Cu=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:o="referenceHidden",...i}=wt(e,t);switch(o){case"referenceHidden":{const l=await r.detectOverflow(t,{...i,elementContext:"reference"}),a=ui(l,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:pi(a)}}}case"escaped":{const l=await r.detectOverflow(t,{...i,altBoundary:!0}),a=ui(l,n.floating);return{data:{escapedOffsets:a,escaped:pi(a)}}}default:return{}}}}},Na=new Set(["left","top"]);async function Eu(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),l=jt(n),a=xn(n),d=gt(n)==="y",c=Na.has(l)?-1:1,f=i&&d?-1:1,p=wt(t,e);let{mainAxis:h,crossAxis:g,alignmentAxis:S}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return a&&typeof S=="number"&&(g=a==="end"?S*-1:S),d?{x:g*f,y:h*c}:{x:h*c,y:g*f}}const Au=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:i,placement:l,middlewareData:a}=t,d=await Eu(t,e);return l===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+d.x,y:i+d.y,data:{...d,placement:l}}}}},Tu=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o,platform:i}=t,{mainAxis:l=!0,crossAxis:a=!1,limiter:d={fn:k=>{let{x:C,y:E}=k;return{x:C,y:E}}},...c}=wt(e,t),f={x:n,y:r},p=await i.detectOverflow(t,c),h=gt(jt(o)),g=ts(h);let S=f[g],x=f[h];if(l){const k=g==="y"?"top":"left",C=g==="y"?"bottom":"right",E=S+p[k],v=S-p[C];S=No(E,S,v)}if(a){const k=h==="y"?"top":"left",C=h==="y"?"bottom":"right",E=x+p[k],v=x-p[C];x=No(E,x,v)}const b=d.fn({...t,[g]:S,[h]:x});return{...b,data:{x:b.x-n,y:b.y-r,enabled:{[g]:l,[h]:a}}}}}},Ru=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:l}=t,{offset:a=0,mainAxis:d=!0,crossAxis:c=!0}=wt(e,t),f={x:n,y:r},p=gt(o),h=ts(p);let g=f[h],S=f[p];const x=wt(a,t),b=typeof x=="number"?{mainAxis:x,crossAxis:0}:{mainAxis:0,crossAxis:0,...x};if(d){const E=h==="y"?"height":"width",v=i.reference[h]-i.floating[E]+b.mainAxis,w=i.reference[h]+i.reference[E]-b.mainAxis;g<v?g=v:g>w&&(g=w)}if(c){var k,C;const E=h==="y"?"width":"height",v=Na.has(jt(o)),w=i.reference[p]-i.floating[E]+(v&&((k=l.offset)==null?void 0:k[p])||0)+(v?0:b.crossAxis),A=i.reference[p]+i.reference[E]+(v?0:((C=l.offset)==null?void 0:C[p])||0)-(v?b.crossAxis:0);S<w?S=w:S>A&&(S=A)}return{[h]:g,[p]:S}}}},_u=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:i,platform:l,elements:a}=t,{apply:d=()=>{},...c}=wt(e,t),f=await l.detectOverflow(t,c),p=jt(o),h=xn(o),g=gt(o)==="y",{width:S,height:x}=i.floating;let b,k;p==="top"||p==="bottom"?(b=p,k=h===(await(l.isRTL==null?void 0:l.isRTL(a.floating))?"start":"end")?"left":"right"):(k=p,b=h==="end"?"top":"bottom");const C=x-f.top-f.bottom,E=S-f.left-f.right,v=$t(x-f[b],C),w=$t(S-f[k],E),A=!t.middlewareData.shift;let R=v,y=w;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(y=E),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(R=C),A&&!h){const $=Ye(f.left,0),T=Ye(f.right,0),L=Ye(f.top,0),I=Ye(f.bottom,0);g?y=S-2*($!==0||T!==0?$+T:Ye(f.left,f.right)):R=x-2*(L!==0||I!==0?L+I:Ye(f.top,f.bottom))}await d({...t,availableWidth:y,availableHeight:R});const M=await l.getDimensions(a.floating);return S!==M.width||x!==M.height?{reset:{rects:!0}}:{}}}};function Wr(){return typeof window<"u"}function bn(e){return Ba(e)?(e.nodeName||"").toLowerCase():"#document"}function Xe(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function vt(e){var t;return(t=(Ba(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Ba(e){return Wr()?e instanceof Node||e instanceof Xe(e).Node:!1}function dt(e){return Wr()?e instanceof Element||e instanceof Xe(e).Element:!1}function Ct(e){return Wr()?e instanceof HTMLElement||e instanceof Xe(e).HTMLElement:!1}function fi(e){return!Wr()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Xe(e).ShadowRoot}function Qn(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=ut(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&o!=="inline"&&o!=="contents"}function $u(e){return/^(table|td|th)$/.test(bn(e))}function Kr(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const Ou=/transform|translate|scale|rotate|perspective|filter/,Pu=/paint|layout|strict|content/,Wt=e=>!!e&&e!=="none";let co;function os(e){const t=dt(e)?ut(e):e;return Wt(t.transform)||Wt(t.translate)||Wt(t.scale)||Wt(t.rotate)||Wt(t.perspective)||!ss()&&(Wt(t.backdropFilter)||Wt(t.filter))||Ou.test(t.willChange||"")||Pu.test(t.contain||"")}function Du(e){let t=Ot(e);for(;Ct(t)&&!mn(t);){if(os(t))return t;if(Kr(t))return null;t=Ot(t)}return null}function ss(){return co==null&&(co=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),co}function mn(e){return/^(html|body|#document)$/.test(bn(e))}function ut(e){return Xe(e).getComputedStyle(e)}function Vr(e){return dt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ot(e){if(bn(e)==="html")return e;const t=e.assignedSlot||e.parentNode||fi(e)&&e.host||vt(e);return fi(t)?t.host:t}function Fa(e){const t=Ot(e);return mn(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ct(t)&&Qn(t)?t:Fa(t)}function qn(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Fa(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),l=Xe(o);if(i){const a=Fo(l);return t.concat(l,l.visualViewport||[],Qn(o)?o:[],a&&n?qn(a):[])}else return t.concat(o,qn(o,[],n))}function Fo(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function za(e){const t=ut(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ct(e),i=o?e.offsetWidth:n,l=o?e.offsetHeight:r,a=Rr(n)!==i||Rr(r)!==l;return a&&(n=i,r=l),{width:n,height:r,$:a}}function is(e){return dt(e)?e:e.contextElement}function pn(e){const t=is(e);if(!Ct(t))return yt(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=za(t);let l=(i?Rr(n.width):n.width)/r,a=(i?Rr(n.height):n.height)/o;return(!l||!Number.isFinite(l))&&(l=1),(!a||!Number.isFinite(a))&&(a=1),{x:l,y:a}}const Mu=yt(0);function qa(e){const t=Xe(e);return!ss()||!t.visualViewport?Mu:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Iu(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Xe(e)?!1:t}function Gt(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=is(e);let l=yt(1);t&&(r?dt(r)&&(l=pn(r)):l=pn(e));const a=Iu(i,n,r)?qa(i):yt(0);let d=(o.left+a.x)/l.x,c=(o.top+a.y)/l.y,f=o.width/l.x,p=o.height/l.y;if(i){const h=Xe(i),g=r&&dt(r)?Xe(r):r;let S=h,x=Fo(S);for(;x&&r&&g!==S;){const b=pn(x),k=x.getBoundingClientRect(),C=ut(x),E=k.left+(x.clientLeft+parseFloat(C.paddingLeft))*b.x,v=k.top+(x.clientTop+parseFloat(C.paddingTop))*b.y;d*=b.x,c*=b.y,f*=b.x,p*=b.y,d+=E,c+=v,S=Xe(x),x=Fo(S)}}return $r({width:f,height:p,x:d,y:c})}function Hr(e,t){const n=Vr(e).scrollLeft;return t?t.left+n:Gt(vt(e)).left+n}function Ua(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-Hr(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function Lu(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i=o==="fixed",l=vt(r),a=t?Kr(t.floating):!1;if(r===l||a&&i)return n;let d={scrollLeft:0,scrollTop:0},c=yt(1);const f=yt(0),p=Ct(r);if((p||!p&&!i)&&((bn(r)!=="body"||Qn(l))&&(d=Vr(r)),p)){const g=Gt(r);c=pn(r),f.x=g.x+r.clientLeft,f.y=g.y+r.clientTop}const h=l&&!p&&!i?Ua(l,d):yt(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-d.scrollLeft*c.x+f.x+h.x,y:n.y*c.y-d.scrollTop*c.y+f.y+h.y}}function Nu(e){return Array.from(e.getClientRects())}function Bu(e){const t=vt(e),n=Vr(e),r=e.ownerDocument.body,o=Ye(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Ye(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+Hr(e);const a=-n.scrollTop;return ut(r).direction==="rtl"&&(l+=Ye(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:l,y:a}}const hi=25;function Fu(e,t){const n=Xe(e),r=vt(e),o=n.visualViewport;let i=r.clientWidth,l=r.clientHeight,a=0,d=0;if(o){i=o.width,l=o.height;const f=ss();(!f||f&&t==="fixed")&&(a=o.offsetLeft,d=o.offsetTop)}const c=Hr(r);if(c<=0){const f=r.ownerDocument,p=f.body,h=getComputedStyle(p),g=f.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,S=Math.abs(r.clientWidth-p.clientWidth-g);S<=hi&&(i-=S)}else c<=hi&&(i+=c);return{width:i,height:l,x:a,y:d}}function zu(e,t){const n=Gt(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ct(e)?pn(e):yt(1),l=e.clientWidth*i.x,a=e.clientHeight*i.y,d=o*i.x,c=r*i.y;return{width:l,height:a,x:d,y:c}}function mi(e,t,n){let r;if(t==="viewport")r=Fu(e,n);else if(t==="document")r=Bu(vt(e));else if(dt(t))r=zu(t,n);else{const o=qa(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return $r(r)}function Wa(e,t){const n=Ot(e);return n===t||!dt(n)||mn(n)?!1:ut(n).position==="fixed"||Wa(n,t)}function qu(e,t){const n=t.get(e);if(n)return n;let r=qn(e,[],!1).filter(a=>dt(a)&&bn(a)!=="body"),o=null;const i=ut(e).position==="fixed";let l=i?Ot(e):e;for(;dt(l)&&!mn(l);){const a=ut(l),d=os(l);!d&&a.position==="fixed"&&(o=null),(i?!d&&!o:!d&&a.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||Qn(l)&&!d&&Wa(e,l))?r=r.filter(f=>f!==l):o=a,l=Ot(l)}return t.set(e,r),r}function Uu(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const l=[...n==="clippingAncestors"?Kr(t)?[]:qu(t,this._c):[].concat(n),r],a=mi(t,l[0],o);let d=a.top,c=a.right,f=a.bottom,p=a.left;for(let h=1;h<l.length;h++){const g=mi(t,l[h],o);d=Ye(g.top,d),c=$t(g.right,c),f=$t(g.bottom,f),p=Ye(g.left,p)}return{width:c-p,height:f-d,x:p,y:d}}function Wu(e){const{width:t,height:n}=za(e);return{width:t,height:n}}function Ku(e,t,n){const r=Ct(t),o=vt(t),i=n==="fixed",l=Gt(e,!0,i,t);let a={scrollLeft:0,scrollTop:0};const d=yt(0);function c(){d.x=Hr(o)}if(r||!r&&!i)if((bn(t)!=="body"||Qn(o))&&(a=Vr(t)),r){const g=Gt(t,!0,i,t);d.x=g.x+t.clientLeft,d.y=g.y+t.clientTop}else o&&c();i&&!r&&o&&c();const f=o&&!r&&!i?Ua(o,a):yt(0),p=l.left+a.scrollLeft-d.x-f.x,h=l.top+a.scrollTop-d.y-f.y;return{x:p,y:h,width:l.width,height:l.height}}function uo(e){return ut(e).position==="static"}function gi(e,t){if(!Ct(e)||ut(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return vt(e)===n&&(n=n.ownerDocument.body),n}function Ka(e,t){const n=Xe(e);if(Kr(e))return n;if(!Ct(e)){let o=Ot(e);for(;o&&!mn(o);){if(dt(o)&&!uo(o))return o;o=Ot(o)}return n}let r=gi(e,t);for(;r&&$u(r)&&uo(r);)r=gi(r,t);return r&&mn(r)&&uo(r)&&!os(r)?n:r||Du(e)||n}const Vu=async function(e){const t=this.getOffsetParent||Ka,n=this.getDimensions,r=await n(e.floating);return{reference:Ku(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Hu(e){return ut(e).direction==="rtl"}const Gu={convertOffsetParentRelativeRectToViewportRelativeRect:Lu,getDocumentElement:vt,getClippingRect:Uu,getOffsetParent:Ka,getElementRects:Vu,getClientRects:Nu,getDimensions:Wu,getScale:pn,isElement:dt,isRTL:Hu};function Va(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Ju(e,t){let n=null,r;const o=vt(e);function i(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function l(a,d){a===void 0&&(a=!1),d===void 0&&(d=1),i();const c=e.getBoundingClientRect(),{left:f,top:p,width:h,height:g}=c;if(a||t(),!h||!g)return;const S=dr(p),x=dr(o.clientWidth-(f+h)),b=dr(o.clientHeight-(p+g)),k=dr(f),E={rootMargin:-S+"px "+-x+"px "+-b+"px "+-k+"px",threshold:Ye(0,$t(1,d))||1};let v=!0;function w(A){const R=A[0].intersectionRatio;if(R!==d){if(!v)return l();R?l(!1,R):r=setTimeout(()=>{l(!1,1e-7)},1e3)}R===1&&!Va(c,e.getBoundingClientRect())&&l(),v=!1}try{n=new IntersectionObserver(w,{...E,root:o.ownerDocument})}catch{n=new IntersectionObserver(w,E)}n.observe(e)}return l(!0),i}function Qu(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:d=!1}=r,c=is(e),f=o||i?[...c?qn(c):[],...t?qn(t):[]]:[];f.forEach(k=>{o&&k.addEventListener("scroll",n,{passive:!0}),i&&k.addEventListener("resize",n)});const p=c&&a?Ju(c,n):null;let h=-1,g=null;l&&(g=new ResizeObserver(k=>{let[C]=k;C&&C.target===c&&g&&t&&(g.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var E;(E=g)==null||E.observe(t)})),n()}),c&&!d&&g.observe(c),t&&g.observe(t));let S,x=d?Gt(e):null;d&&b();function b(){const k=Gt(e);x&&!Va(x,k)&&n(),x=k,S=requestAnimationFrame(b)}return n(),()=>{var k;f.forEach(C=>{o&&C.removeEventListener("scroll",n),i&&C.removeEventListener("resize",n)}),p==null||p(),(k=g)==null||k.disconnect(),g=null,d&&cancelAnimationFrame(S)}}const Yu=Au,Xu=Tu,Zu=ju,ep=_u,tp=Cu,yi=wu,np=Ru,rp=(e,t,n)=>{const r=new Map,o={platform:Gu,...n},i={...o.platform,_c:r};return ku(e,t,{...o,platform:i})};var op=typeof document<"u",sp=function(){},jr=op?u.useLayoutEffect:sp;function Or(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Or(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Or(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Ha(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function xi(e,t){const n=Ha(e);return Math.round(t*n)/n}function po(e){const t=u.useRef(e);return jr(()=>{t.current=e}),t}function ip(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:l}={},transform:a=!0,whileElementsMounted:d,open:c}=e,[f,p]=u.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[h,g]=u.useState(r);Or(h,r)||g(r);const[S,x]=u.useState(null),[b,k]=u.useState(null),C=u.useCallback(O=>{O!==A.current&&(A.current=O,x(O))},[]),E=u.useCallback(O=>{O!==R.current&&(R.current=O,k(O))},[]),v=i||S,w=l||b,A=u.useRef(null),R=u.useRef(null),y=u.useRef(f),M=d!=null,$=po(d),T=po(o),L=po(c),I=u.useCallback(()=>{if(!A.current||!R.current)return;const O={placement:t,strategy:n,middleware:h};T.current&&(O.platform=T.current),rp(A.current,R.current,O).then(W=>{const se={...W,isPositioned:L.current!==!1};G.current&&!Or(y.current,se)&&(y.current=se,es.flushSync(()=>{p(se)}))})},[h,t,n,T,L]);jr(()=>{c===!1&&y.current.isPositioned&&(y.current.isPositioned=!1,p(O=>({...O,isPositioned:!1})))},[c]);const G=u.useRef(!1);jr(()=>(G.current=!0,()=>{G.current=!1}),[]),jr(()=>{if(v&&(A.current=v),w&&(R.current=w),v&&w){if($.current)return $.current(v,w,I);I()}},[v,w,I,$,M]);const Y=u.useMemo(()=>({reference:A,floating:R,setReference:C,setFloating:E}),[C,E]),P=u.useMemo(()=>({reference:v,floating:w}),[v,w]),q=u.useMemo(()=>{const O={position:n,left:0,top:0};if(!P.floating)return O;const W=xi(P.floating,f.x),se=xi(P.floating,f.y);return a?{...O,transform:"translate("+W+"px, "+se+"px)",...Ha(P.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:W,top:se}},[n,a,P.floating,f.x,f.y]);return u.useMemo(()=>({...f,update:I,refs:Y,elements:P,floatingStyles:q}),[f,I,Y,P,q])}const ap=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?yi({element:r.current,padding:o}).fn(n):{}:r?yi({element:r,padding:o}).fn(n):{}}}},lp=(e,t)=>{const n=Yu(e);return{name:n.name,fn:n.fn,options:[e,t]}},cp=(e,t)=>{const n=Xu(e);return{name:n.name,fn:n.fn,options:[e,t]}},dp=(e,t)=>({fn:np(e).fn,options:[e,t]}),up=(e,t)=>{const n=Zu(e);return{name:n.name,fn:n.fn,options:[e,t]}},pp=(e,t)=>{const n=ep(e);return{name:n.name,fn:n.fn,options:[e,t]}},fp=(e,t)=>{const n=tp(e);return{name:n.name,fn:n.fn,options:[e,t]}},hp=(e,t)=>{const n=ap(e);return{name:n.name,fn:n.fn,options:[e,t]}};var mp="Arrow",Ga=u.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...i}=e;return s.jsx(ve.svg,{...i,ref:t,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:s.jsx("polygon",{points:"0,0 30,0 15,10"})})});Ga.displayName=mp;var gp=Ga;function yp(e){const[t,n]=u.useState(void 0);return _t(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let l,a;if("borderBoxSize"in i){const d=i.borderBoxSize,c=Array.isArray(d)?d[0]:d;l=c.inlineSize,a=c.blockSize}else l=e.offsetWidth,a=e.offsetHeight;n({width:l,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var as="Popper",[Ja,vn]=Mt(as),[xp,Qa]=Ja(as),Ya=e=>{const{__scopePopper:t,children:n}=e,[r,o]=u.useState(null);return s.jsx(xp,{scope:t,anchor:r,onAnchorChange:o,children:n})};Ya.displayName=as;var Xa="PopperAnchor",Za=u.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Qa(Xa,n),l=u.useRef(null),a=we(t,l),d=u.useRef(null);return u.useEffect(()=>{const c=d.current;d.current=(r==null?void 0:r.current)||l.current,c!==d.current&&i.onAnchorChange(d.current)}),r?null:s.jsx(ve.div,{...o,ref:a})});Za.displayName=Xa;var ls="PopperContent",[bp,vp]=Ja(ls),el=u.forwardRef((e,t)=>{var re,ge,ye,Ae,ze,Ie;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:i="center",alignOffset:l=0,arrowPadding:a=0,avoidCollisions:d=!0,collisionBoundary:c=[],collisionPadding:f=0,sticky:p="partial",hideWhenDetached:h=!1,updatePositionStrategy:g="optimized",onPlaced:S,...x}=e,b=Qa(ls,n),[k,C]=u.useState(null),E=we(t,be=>C(be)),[v,w]=u.useState(null),A=yp(v),R=(A==null?void 0:A.width)??0,y=(A==null?void 0:A.height)??0,M=r+(i!=="center"?"-"+i:""),$=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},T=Array.isArray(c)?c:[c],L=T.length>0,I={padding:$,boundary:T.filter(kp),altBoundary:L},{refs:G,floatingStyles:Y,placement:P,isPositioned:q,middlewareData:O}=ip({strategy:"fixed",placement:M,whileElementsMounted:(...be)=>Qu(...be,{animationFrame:g==="always"}),elements:{reference:b.anchor},middleware:[lp({mainAxis:o+y,alignmentAxis:l}),d&&cp({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?dp():void 0,...I}),d&&up({...I}),pp({...I,apply:({elements:be,rects:ue,availableWidth:Le,availableHeight:qe})=>{const{width:$e,height:De}=ue.reference,Ze=be.floating.style;Ze.setProperty("--radix-popper-available-width",`${Le}px`),Ze.setProperty("--radix-popper-available-height",`${qe}px`),Ze.setProperty("--radix-popper-anchor-width",`${$e}px`),Ze.setProperty("--radix-popper-anchor-height",`${De}px`)}}),v&&hp({element:v,padding:a}),wp({arrowWidth:R,arrowHeight:y}),h&&fp({strategy:"referenceHidden",...I})]}),[W,se]=rl(P),H=Rt(S);_t(()=>{q&&(H==null||H())},[q,H]);const te=(re=O.arrow)==null?void 0:re.x,J=(ge=O.arrow)==null?void 0:ge.y,B=((ye=O.arrow)==null?void 0:ye.centerOffset)!==0,[ne,ce]=u.useState();return _t(()=>{k&&ce(window.getComputedStyle(k).zIndex)},[k]),s.jsx("div",{ref:G.setFloating,"data-radix-popper-content-wrapper":"",style:{...Y,transform:q?Y.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ne,"--radix-popper-transform-origin":[(Ae=O.transformOrigin)==null?void 0:Ae.x,(ze=O.transformOrigin)==null?void 0:ze.y].join(" "),...((Ie=O.hide)==null?void 0:Ie.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:s.jsx(bp,{scope:n,placedSide:W,onArrowChange:w,arrowX:te,arrowY:J,shouldHideArrow:B,children:s.jsx(ve.div,{"data-side":W,"data-align":se,...x,ref:E,style:{...x.style,animation:q?void 0:"none"}})})})});el.displayName=ls;var tl="PopperArrow",Sp={top:"bottom",right:"left",bottom:"top",left:"right"},nl=u.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,i=vp(tl,r),l=Sp[i.placedSide];return s.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[l]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:s.jsx(gp,{...o,ref:n,style:{...o.style,display:"block"}})})});nl.displayName=tl;function kp(e){return e!==null}var wp=e=>({name:"transformOrigin",options:e,fn(t){var b,k,C;const{placement:n,rects:r,middlewareData:o}=t,l=((b=o.arrow)==null?void 0:b.centerOffset)!==0,a=l?0:e.arrowWidth,d=l?0:e.arrowHeight,[c,f]=rl(n),p={start:"0%",center:"50%",end:"100%"}[f],h=(((k=o.arrow)==null?void 0:k.x)??0)+a/2,g=(((C=o.arrow)==null?void 0:C.y)??0)+d/2;let S="",x="";return c==="bottom"?(S=l?p:`${h}px`,x=`${-d}px`):c==="top"?(S=l?p:`${h}px`,x=`${r.floating.height+d}px`):c==="right"?(S=`${-d}px`,x=l?p:`${g}px`):c==="left"&&(S=`${r.floating.width+d}px`,x=l?p:`${g}px`),{data:{x:S,y:x}}}});function rl(e){const[t,n="center"]=e.split("-");return[t,n]}var jp=Ya,Gr=Za,cs=el,ds=nl,Cp="Portal",Yn=u.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,i]=u.useState(!1);_t(()=>i(!0),[]);const l=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return l?Gd.createPortal(s.jsx(ve.div,{...r,ref:t}),l):null});Yn.displayName=Cp;function Ep(e,t){return u.useReducer((n,r)=>t[n][r]??n,e)}var rt=e=>{const{present:t,children:n}=e,r=Ap(t),o=typeof n=="function"?n({present:r.isPresent}):u.Children.only(n),i=we(r.ref,Tp(o));return typeof n=="function"||r.isPresent?u.cloneElement(o,{ref:i}):null};rt.displayName="Presence";function Ap(e){const[t,n]=u.useState(),r=u.useRef(null),o=u.useRef(e),i=u.useRef("none"),l=e?"mounted":"unmounted",[a,d]=Ep(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return u.useEffect(()=>{const c=ur(r.current);i.current=a==="mounted"?c:"none"},[a]),_t(()=>{const c=r.current,f=o.current;if(f!==e){const h=i.current,g=ur(c);e?d("MOUNT"):g==="none"||(c==null?void 0:c.display)==="none"?d("UNMOUNT"):d(f&&h!==g?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,d]),_t(()=>{if(t){let c;const f=t.ownerDocument.defaultView??window,p=g=>{const x=ur(r.current).includes(CSS.escape(g.animationName));if(g.target===t&&x&&(d("ANIMATION_END"),!o.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",c=f.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},h=g=>{g.target===t&&(i.current=ur(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{f.clearTimeout(c),t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:u.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function ur(e){return(e==null?void 0:e.animationName)||"none"}function Tp(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var Rp=$a[" useInsertionEffect ".trim().toString()]||_t;function us({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,i,l]=_p({defaultProp:t,onChange:n}),a=e!==void 0,d=a?e:o;{const f=u.useRef(e!==void 0);u.useEffect(()=>{const p=f.current;p!==a&&console.warn(`${r} is changing from ${p?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),f.current=a},[a,r])}const c=u.useCallback(f=>{var p;if(a){const h=$p(f)?f(e):f;h!==e&&((p=l.current)==null||p.call(l,h))}else i(f)},[a,e,i,l]);return[d,c]}function _p({defaultProp:e,onChange:t}){const[n,r]=u.useState(e),o=u.useRef(n),i=u.useRef(t);return Rp(()=>{i.current=t},[t]),u.useEffect(()=>{var l;o.current!==n&&((l=i.current)==null||l.call(i,n),o.current=n)},[n,o]),[n,r,i]}function $p(e){return typeof e=="function"}var Op=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Pp="VisuallyHidden",ol=u.forwardRef((e,t)=>s.jsx(ve.span,{...e,ref:t,style:{...Op,...e.style}}));ol.displayName=Pp;var Dp=ol,[Jr]=Mt("Tooltip",[vn]),Qr=vn(),sl="TooltipProvider",Mp=700,zo="tooltip.open",[Ip,ps]=Jr(sl),il=e=>{const{__scopeTooltip:t,delayDuration:n=Mp,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,l=u.useRef(!0),a=u.useRef(!1),d=u.useRef(0);return u.useEffect(()=>{const c=d.current;return()=>window.clearTimeout(c)},[]),s.jsx(Ip,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:u.useCallback(()=>{window.clearTimeout(d.current),l.current=!1},[]),onClose:u.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:u.useCallback(c=>{a.current=c},[]),disableHoverableContent:o,children:i})};il.displayName=sl;var Un="Tooltip",[Lp,Xn]=Jr(Un),al=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:l,delayDuration:a}=e,d=ps(Un,e.__scopeTooltip),c=Qr(t),[f,p]=u.useState(null),h=Ln(),g=u.useRef(0),S=l??d.disableHoverableContent,x=a??d.delayDuration,b=u.useRef(!1),[k,C]=us({prop:r,defaultProp:o??!1,onChange:R=>{R?(d.onOpen(),document.dispatchEvent(new CustomEvent(zo))):d.onClose(),i==null||i(R)},caller:Un}),E=u.useMemo(()=>k?b.current?"delayed-open":"instant-open":"closed",[k]),v=u.useCallback(()=>{window.clearTimeout(g.current),g.current=0,b.current=!1,C(!0)},[C]),w=u.useCallback(()=>{window.clearTimeout(g.current),g.current=0,C(!1)},[C]),A=u.useCallback(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{b.current=!0,C(!0),g.current=0},x)},[x,C]);return u.useEffect(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),s.jsx(jp,{...c,children:s.jsx(Lp,{scope:t,contentId:h,open:k,stateAttribute:E,trigger:f,onTriggerChange:p,onTriggerEnter:u.useCallback(()=>{d.isOpenDelayedRef.current?A():v()},[d.isOpenDelayedRef,A,v]),onTriggerLeave:u.useCallback(()=>{S?w():(window.clearTimeout(g.current),g.current=0)},[w,S]),onOpen:v,onClose:w,disableHoverableContent:S,children:n})})};al.displayName=Un;var qo="TooltipTrigger",ll=u.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Xn(qo,n),i=ps(qo,n),l=Qr(n),a=u.useRef(null),d=we(t,a,o.onTriggerChange),c=u.useRef(!1),f=u.useRef(!1),p=u.useCallback(()=>c.current=!1,[]);return u.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),s.jsx(Gr,{asChild:!0,...l,children:s.jsx(ve.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:d,onPointerMove:ie(e.onPointerMove,h=>{h.pointerType!=="touch"&&!f.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),f.current=!0)}),onPointerLeave:ie(e.onPointerLeave,()=>{o.onTriggerLeave(),f.current=!1}),onPointerDown:ie(e.onPointerDown,()=>{o.open&&o.onClose(),c.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:ie(e.onFocus,()=>{c.current||o.onOpen()}),onBlur:ie(e.onBlur,o.onClose),onClick:ie(e.onClick,o.onClose)})})});ll.displayName=qo;var fs="TooltipPortal",[Np,Bp]=Jr(fs,{forceMount:void 0}),cl=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,i=Xn(fs,t);return s.jsx(Np,{scope:t,forceMount:n,children:s.jsx(rt,{present:n||i.open,children:s.jsx(Yn,{asChild:!0,container:o,children:r})})})};cl.displayName=fs;var gn="TooltipContent",dl=u.forwardRef((e,t)=>{const n=Bp(gn,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,l=Xn(gn,e.__scopeTooltip);return s.jsx(rt,{present:r||l.open,children:l.disableHoverableContent?s.jsx(ul,{side:o,...i,ref:t}):s.jsx(Fp,{side:o,...i,ref:t})})}),Fp=u.forwardRef((e,t)=>{const n=Xn(gn,e.__scopeTooltip),r=ps(gn,e.__scopeTooltip),o=u.useRef(null),i=we(t,o),[l,a]=u.useState(null),{trigger:d,onClose:c}=n,f=o.current,{onPointerInTransitChange:p}=r,h=u.useCallback(()=>{a(null),p(!1)},[p]),g=u.useCallback((S,x)=>{const b=S.currentTarget,k={x:S.clientX,y:S.clientY},C=Kp(k,b.getBoundingClientRect()),E=Vp(k,C),v=Hp(x.getBoundingClientRect()),w=Jp([...E,...v]);a(w),p(!0)},[p]);return u.useEffect(()=>()=>h(),[h]),u.useEffect(()=>{if(d&&f){const S=b=>g(b,f),x=b=>g(b,d);return d.addEventListener("pointerleave",S),f.addEventListener("pointerleave",x),()=>{d.removeEventListener("pointerleave",S),f.removeEventListener("pointerleave",x)}}},[d,f,g,h]),u.useEffect(()=>{if(l){const S=x=>{const b=x.target,k={x:x.clientX,y:x.clientY},C=(d==null?void 0:d.contains(b))||(f==null?void 0:f.contains(b)),E=!Gp(k,l);C?h():E&&(h(),c())};return document.addEventListener("pointermove",S),()=>document.removeEventListener("pointermove",S)}},[d,f,l,c,h]),s.jsx(ul,{...e,ref:i})}),[zp,qp]=Jr(Un,{isInside:!1}),Up=Qd("TooltipContent"),ul=u.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:l,...a}=e,d=Xn(gn,n),c=Qr(n),{onClose:f}=d;return u.useEffect(()=>(document.addEventListener(zo,f),()=>document.removeEventListener(zo,f)),[f]),u.useEffect(()=>{if(d.trigger){const p=h=>{const g=h.target;g!=null&&g.contains(d.trigger)&&f()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[d.trigger,f]),s.jsx(Jn,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:p=>p.preventDefault(),onDismiss:f,children:s.jsxs(cs,{"data-state":d.stateAttribute,...c,...a,ref:t,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[s.jsx(Up,{children:r}),s.jsx(zp,{scope:n,isInside:!0,children:s.jsx(Dp,{id:d.contentId,role:"tooltip",children:o||r})})]})})});dl.displayName=gn;var pl="TooltipArrow",Wp=u.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Qr(n);return qp(pl,n).isInside?null:s.jsx(ds,{...o,...r,ref:t})});Wp.displayName=pl;function Kp(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Vp(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function Hp(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function Gp(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,l=t.length-1;i<t.length;l=i++){const a=t[i],d=t[l],c=a.x,f=a.y,p=d.x,h=d.y;f>r!=h>r&&n<(p-c)*(r-f)/(h-f)+c&&(o=!o)}return o}function Jp(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Qp(t)}function Qp(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const o=e[r];for(;t.length>=2;){const i=t[t.length-1],l=t[t.length-2];if((i.x-l.x)*(o.y-l.y)>=(i.y-l.y)*(o.x-l.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const i=n[n.length-1],l=n[n.length-2];if((i.x-l.x)*(o.y-l.y)>=(i.y-l.y)*(o.x-l.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Yp=il,Xp=al,Zp=ll,ef=cl,tf=dl;function fl({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:i=200,container:l}){return s.jsxs(Xp,{delayDuration:i,children:[s.jsx(Zp,{asChild:!0,children:t}),s.jsx(ef,{container:l,children:s.jsx(tf,{side:n,align:r,sideOffset:o,style:{background:le("surfaceElevated"),color:le("textPrimary"),border:`1px solid ${le("borderDefault")}`,borderRadius:Dt.sm,padding:`${fe[1]} ${fe[2]}`,fontSize:Be.sm,boxShadow:le("shadowMd"),zIndex:zn.tooltip,userSelect:"none"},children:e})})]})}const nf=Yp;var fo="focusScope.autoFocusOnMount",ho="focusScope.autoFocusOnUnmount",bi={bubbles:!1,cancelable:!0},rf="FocusScope",Yr=u.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...l}=e,[a,d]=u.useState(null),c=Rt(o),f=Rt(i),p=u.useRef(null),h=we(t,x=>d(x)),g=u.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;u.useEffect(()=>{if(r){let x=function(E){if(g.paused||!a)return;const v=E.target;a.contains(v)?p.current=v:Tt(p.current,{select:!0})},b=function(E){if(g.paused||!a)return;const v=E.relatedTarget;v!==null&&(a.contains(v)||Tt(p.current,{select:!0}))},k=function(E){if(document.activeElement===document.body)for(const w of E)w.removedNodes.length>0&&Tt(a)};document.addEventListener("focusin",x),document.addEventListener("focusout",b);const C=new MutationObserver(k);return a&&C.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",b),C.disconnect()}}},[r,a,g.paused]),u.useEffect(()=>{if(a){Si.add(g);const x=document.activeElement;if(!a.contains(x)){const k=new CustomEvent(fo,bi);a.addEventListener(fo,c),a.dispatchEvent(k),k.defaultPrevented||(of(df(hl(a)),{select:!0}),document.activeElement===x&&Tt(a))}return()=>{a.removeEventListener(fo,c),setTimeout(()=>{const k=new CustomEvent(ho,bi);a.addEventListener(ho,f),a.dispatchEvent(k),k.defaultPrevented||Tt(x??document.body,{select:!0}),a.removeEventListener(ho,f),Si.remove(g)},0)}}},[a,c,f,g]);const S=u.useCallback(x=>{if(!n&&!r||g.paused)return;const b=x.key==="Tab"&&!x.altKey&&!x.ctrlKey&&!x.metaKey,k=document.activeElement;if(b&&k){const C=x.currentTarget,[E,v]=sf(C);E&&v?!x.shiftKey&&k===v?(x.preventDefault(),n&&Tt(E,{select:!0})):x.shiftKey&&k===E&&(x.preventDefault(),n&&Tt(v,{select:!0})):k===C&&x.preventDefault()}},[n,r,g.paused]);return s.jsx(ve.div,{tabIndex:-1,...l,ref:h,onKeyDown:S})});Yr.displayName=rf;function of(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Tt(r,{select:t}),document.activeElement!==n)return}function sf(e){const t=hl(e),n=vi(t,e),r=vi(t.reverse(),e);return[n,r]}function hl(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function vi(e,t){for(const n of e)if(!af(n,{upTo:t}))return n}function af(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function lf(e){return e instanceof HTMLInputElement&&"select"in e}function Tt(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&lf(e)&&t&&e.select()}}var Si=cf();function cf(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ki(e,t),e.unshift(t)},remove(t){var n;e=ki(e,t),(n=e[0])==null||n.resume()}}}function ki(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function df(e){return e.filter(t=>t.tagName!=="A")}var mo=0;function hs(){u.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??wi()),document.body.insertAdjacentElement("beforeend",e[1]??wi()),mo++,()=>{mo===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),mo--}},[])}function wi(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var mt=function(){return mt=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t},mt.apply(this,arguments)};function ml(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function uf(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))}var Cr="right-scroll-bar-position",Er="width-before-scroll-bar",pf="with-scroll-bars-hidden",ff="--removed-body-scroll-bar-size";function go(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function hf(e,t){var n=u.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var mf=typeof window<"u"?u.useLayoutEffect:u.useEffect,ji=new WeakMap;function gf(e,t){var n=hf(null,function(r){return e.forEach(function(o){return go(o,r)})});return mf(function(){var r=ji.get(n);if(r){var o=new Set(r),i=new Set(e),l=n.current;o.forEach(function(a){i.has(a)||go(a,null)}),i.forEach(function(a){o.has(a)||go(a,l)})}ji.set(n,e)},[e]),n}function yf(e){return e}function xf(e,t){t===void 0&&(t=yf);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(i){var l=t(i,r);return n.push(l),function(){n=n.filter(function(a){return a!==l})}},assignSyncMedium:function(i){for(r=!0;n.length;){var l=n;n=[],l.forEach(i)}n={push:function(a){return i(a)},filter:function(){return n}}},assignMedium:function(i){r=!0;var l=[];if(n.length){var a=n;n=[],a.forEach(i),l=n}var d=function(){var f=l;l=[],f.forEach(i)},c=function(){return Promise.resolve().then(d)};c(),n={push:function(f){l.push(f),c()},filter:function(f){return l=l.filter(f),n}}}};return o}function bf(e){e===void 0&&(e={});var t=xf(null);return t.options=mt({async:!0,ssr:!1},e),t}var gl=function(e){var t=e.sideCar,n=ml(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return u.createElement(r,mt({},n))};gl.isSideCarExport=!0;function vf(e,t){return e.useMedium(t),gl}var yl=bf(),yo=function(){},Xr=u.forwardRef(function(e,t){var n=u.useRef(null),r=u.useState({onScrollCapture:yo,onWheelCapture:yo,onTouchMoveCapture:yo}),o=r[0],i=r[1],l=e.forwardProps,a=e.children,d=e.className,c=e.removeScrollBar,f=e.enabled,p=e.shards,h=e.sideCar,g=e.noRelative,S=e.noIsolation,x=e.inert,b=e.allowPinchZoom,k=e.as,C=k===void 0?"div":k,E=e.gapMode,v=ml(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),w=h,A=gf([n,t]),R=mt(mt({},v),o);return u.createElement(u.Fragment,null,f&&u.createElement(w,{sideCar:yl,removeScrollBar:c,shards:p,noRelative:g,noIsolation:S,inert:x,setCallbacks:i,allowPinchZoom:!!b,lockRef:n,gapMode:E}),l?u.cloneElement(u.Children.only(a),mt(mt({},R),{ref:A})):u.createElement(C,mt({},R,{className:d,ref:A}),a))});Xr.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Xr.classNames={fullWidth:Er,zeroRight:Cr};var Sf=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function kf(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Sf();return t&&e.setAttribute("nonce",t),e}function wf(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function jf(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Cf=function(){var e=0,t=null;return{add:function(n){e==0&&(t=kf())&&(wf(t,n),jf(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Ef=function(){var e=Cf();return function(t,n){u.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},xl=function(){var e=Ef(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Af={left:0,top:0,right:0,gap:0},xo=function(e){return parseInt(e||"",10)||0},Tf=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[xo(n),xo(r),xo(o)]},Rf=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Af;var t=Tf(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},_f=xl(),fn="data-scroll-locked",$f=function(e,t,n,r){var o=e.left,i=e.top,l=e.right,a=e.gap;return n===void 0&&(n="margin"),`
11
- .`.concat(pf,` {
12
- overflow: hidden `).concat(r,`;
13
- padding-right: `).concat(a,"px ").concat(r,`;
14
- }
15
- body[`).concat(fn,`] {
16
- overflow: hidden `).concat(r,`;
17
- overscroll-behavior: contain;
18
- `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
19
- padding-left: `.concat(o,`px;
20
- padding-top: `).concat(i,`px;
21
- padding-right: `).concat(l,`px;
22
- margin-left:0;
23
- margin-top:0;
24
- margin-right: `).concat(a,"px ").concat(r,`;
25
- `),n==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),`
26
- }
27
-
28
- .`).concat(Cr,` {
29
- right: `).concat(a,"px ").concat(r,`;
30
- }
31
-
32
- .`).concat(Er,` {
33
- margin-right: `).concat(a,"px ").concat(r,`;
34
- }
35
-
36
- .`).concat(Cr," .").concat(Cr,` {
37
- right: 0 `).concat(r,`;
38
- }
39
-
40
- .`).concat(Er," .").concat(Er,` {
41
- margin-right: 0 `).concat(r,`;
42
- }
43
-
44
- body[`).concat(fn,`] {
45
- `).concat(ff,": ").concat(a,`px;
46
- }
47
- `)},Ci=function(){var e=parseInt(document.body.getAttribute(fn)||"0",10);return isFinite(e)?e:0},Of=function(){u.useEffect(function(){return document.body.setAttribute(fn,(Ci()+1).toString()),function(){var e=Ci()-1;e<=0?document.body.removeAttribute(fn):document.body.setAttribute(fn,e.toString())}},[])},Pf=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;Of();var i=u.useMemo(function(){return Rf(o)},[o]);return u.createElement(_f,{styles:$f(i,!t,o,n?"":"!important")})},Uo=!1;if(typeof window<"u")try{var pr=Object.defineProperty({},"passive",{get:function(){return Uo=!0,!0}});window.addEventListener("test",pr,pr),window.removeEventListener("test",pr,pr)}catch{Uo=!1}var nn=Uo?{passive:!1}:!1,Df=function(e){return e.tagName==="TEXTAREA"},bl=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Df(e)&&n[t]==="visible")},Mf=function(e){return bl(e,"overflowY")},If=function(e){return bl(e,"overflowX")},Ei=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=vl(e,r);if(o){var i=Sl(e,r),l=i[1],a=i[2];if(l>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Lf=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Nf=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},vl=function(e,t){return e==="v"?Mf(t):If(t)},Sl=function(e,t){return e==="v"?Lf(t):Nf(t)},Bf=function(e,t){return e==="h"&&t==="rtl"?-1:1},Ff=function(e,t,n,r,o){var i=Bf(e,window.getComputedStyle(t).direction),l=i*r,a=n.target,d=t.contains(a),c=!1,f=l>0,p=0,h=0;do{if(!a)break;var g=Sl(e,a),S=g[0],x=g[1],b=g[2],k=x-b-i*S;(S||k)&&vl(e,a)&&(p+=k,h+=S);var C=a.parentNode;a=C&&C.nodeType===Node.DOCUMENT_FRAGMENT_NODE?C.host:C}while(!d&&a!==document.body||d&&(t.contains(a)||t===a));return(f&&Math.abs(p)<1||!f&&Math.abs(h)<1)&&(c=!0),c},fr=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Ai=function(e){return[e.deltaX,e.deltaY]},Ti=function(e){return e&&"current"in e?e.current:e},zf=function(e,t){return e[0]===t[0]&&e[1]===t[1]},qf=function(e){return`
48
- .block-interactivity-`.concat(e,` {pointer-events: none;}
49
- .allow-interactivity-`).concat(e,` {pointer-events: all;}
50
- `)},Uf=0,rn=[];function Wf(e){var t=u.useRef([]),n=u.useRef([0,0]),r=u.useRef(),o=u.useState(Uf++)[0],i=u.useState(xl)[0],l=u.useRef(e);u.useEffect(function(){l.current=e},[e]),u.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var x=uf([e.lockRef.current],(e.shards||[]).map(Ti),!0).filter(Boolean);return x.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),x.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var a=u.useCallback(function(x,b){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!l.current.allowPinchZoom;var k=fr(x),C=n.current,E="deltaX"in x?x.deltaX:C[0]-k[0],v="deltaY"in x?x.deltaY:C[1]-k[1],w,A=x.target,R=Math.abs(E)>Math.abs(v)?"h":"v";if("touches"in x&&R==="h"&&A.type==="range")return!1;var y=window.getSelection(),M=y&&y.anchorNode,$=M?M===A||M.contains(A):!1;if($)return!1;var T=Ei(R,A);if(!T)return!0;if(T?w=R:(w=R==="v"?"h":"v",T=Ei(R,A)),!T)return!1;if(!r.current&&"changedTouches"in x&&(E||v)&&(r.current=w),!w)return!0;var L=r.current||w;return Ff(L,b,x,L==="h"?E:v)},[]),d=u.useCallback(function(x){var b=x;if(!(!rn.length||rn[rn.length-1]!==i)){var k="deltaY"in b?Ai(b):fr(b),C=t.current.filter(function(w){return w.name===b.type&&(w.target===b.target||b.target===w.shadowParent)&&zf(w.delta,k)})[0];if(C&&C.should){b.cancelable&&b.preventDefault();return}if(!C){var E=(l.current.shards||[]).map(Ti).filter(Boolean).filter(function(w){return w.contains(b.target)}),v=E.length>0?a(b,E[0]):!l.current.noIsolation;v&&b.cancelable&&b.preventDefault()}}},[]),c=u.useCallback(function(x,b,k,C){var E={name:x,delta:b,target:k,should:C,shadowParent:Kf(k)};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(v){return v!==E})},1)},[]),f=u.useCallback(function(x){n.current=fr(x),r.current=void 0},[]),p=u.useCallback(function(x){c(x.type,Ai(x),x.target,a(x,e.lockRef.current))},[]),h=u.useCallback(function(x){c(x.type,fr(x),x.target,a(x,e.lockRef.current))},[]);u.useEffect(function(){return rn.push(i),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:h}),document.addEventListener("wheel",d,nn),document.addEventListener("touchmove",d,nn),document.addEventListener("touchstart",f,nn),function(){rn=rn.filter(function(x){return x!==i}),document.removeEventListener("wheel",d,nn),document.removeEventListener("touchmove",d,nn),document.removeEventListener("touchstart",f,nn)}},[]);var g=e.removeScrollBar,S=e.inert;return u.createElement(u.Fragment,null,S?u.createElement(i,{styles:qf(o)}):null,g?u.createElement(Pf,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Kf(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Vf=vf(yl,Wf);var Zr=u.forwardRef(function(e,t){return u.createElement(Xr,mt({},e,{ref:t,sideCar:Vf}))});Zr.classNames=Xr.classNames;var Hf=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},on=new WeakMap,hr=new WeakMap,mr={},bo=0,kl=function(e){return e&&(e.host||kl(e.parentNode))},Gf=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=kl(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},Jf=function(e,t,n,r){var o=Gf(t,Array.isArray(e)?e:[e]);mr[n]||(mr[n]=new WeakMap);var i=mr[n],l=[],a=new Set,d=new Set(o),c=function(p){!p||a.has(p)||(a.add(p),c(p.parentNode))};o.forEach(c);var f=function(p){!p||d.has(p)||Array.prototype.forEach.call(p.children,function(h){if(a.has(h))f(h);else try{var g=h.getAttribute(r),S=g!==null&&g!=="false",x=(on.get(h)||0)+1,b=(i.get(h)||0)+1;on.set(h,x),i.set(h,b),l.push(h),x===1&&S&&hr.set(h,!0),b===1&&h.setAttribute(n,"true"),S||h.setAttribute(r,"true")}catch(k){console.error("aria-hidden: cannot operate on ",h,k)}})};return f(t),a.clear(),bo++,function(){l.forEach(function(p){var h=on.get(p)-1,g=i.get(p)-1;on.set(p,h),i.set(p,g),h||(hr.has(p)||p.removeAttribute(r),hr.delete(p)),g||p.removeAttribute(n)}),bo--,bo||(on=new WeakMap,on=new WeakMap,hr=new WeakMap,mr={})}},ms=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Hf(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Jf(r,o,n,"aria-hidden")):function(){return null}},eo="Dialog",[wl]=Mt(eo),[Qf,pt]=wl(eo),jl=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:l=!0}=e,a=u.useRef(null),d=u.useRef(null),[c,f]=us({prop:r,defaultProp:o??!1,onChange:i,caller:eo});return s.jsx(Qf,{scope:t,triggerRef:a,contentRef:d,contentId:Ln(),titleId:Ln(),descriptionId:Ln(),open:c,onOpenChange:f,onOpenToggle:u.useCallback(()=>f(p=>!p),[f]),modal:l,children:n})};jl.displayName=eo;var Cl="DialogTrigger",Yf=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=pt(Cl,n),i=we(t,o.triggerRef);return s.jsx(ve.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":xs(o.open),...r,ref:i,onClick:ie(e.onClick,o.onOpenToggle)})});Yf.displayName=Cl;var gs="DialogPortal",[Xf,El]=wl(gs,{forceMount:void 0}),Al=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=pt(gs,t);return s.jsx(Xf,{scope:t,forceMount:n,children:u.Children.map(r,l=>s.jsx(rt,{present:n||i.open,children:s.jsx(Yn,{asChild:!0,container:o,children:l})}))})};Al.displayName=gs;var Pr="DialogOverlay",Tl=u.forwardRef((e,t)=>{const n=El(Pr,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=pt(Pr,e.__scopeDialog);return i.modal?s.jsx(rt,{present:r||i.open,children:s.jsx(eh,{...o,ref:t})}):null});Tl.displayName=Pr;var Zf=hn("DialogOverlay.RemoveScroll"),eh=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=pt(Pr,n);return s.jsx(Zr,{as:Zf,allowPinchZoom:!0,shards:[o.contentRef],children:s.jsx(ve.div,{"data-state":xs(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Jt="DialogContent",Rl=u.forwardRef((e,t)=>{const n=El(Jt,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=pt(Jt,e.__scopeDialog);return s.jsx(rt,{present:r||i.open,children:i.modal?s.jsx(th,{...o,ref:t}):s.jsx(nh,{...o,ref:t})})});Rl.displayName=Jt;var th=u.forwardRef((e,t)=>{const n=pt(Jt,e.__scopeDialog),r=u.useRef(null),o=we(t,n.contentRef,r);return u.useEffect(()=>{const i=r.current;if(i)return ms(i)},[]),s.jsx(_l,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ie(e.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:ie(e.onPointerDownOutside,i=>{const l=i.detail.originalEvent,a=l.button===0&&l.ctrlKey===!0;(l.button===2||a)&&i.preventDefault()}),onFocusOutside:ie(e.onFocusOutside,i=>i.preventDefault())})}),nh=u.forwardRef((e,t)=>{const n=pt(Jt,e.__scopeDialog),r=u.useRef(!1),o=u.useRef(!1);return s.jsx(_l,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,a;(l=e.onCloseAutoFocus)==null||l.call(e,i),i.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var d,c;(d=e.onInteractOutside)==null||d.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const l=i.target;((c=n.triggerRef.current)==null?void 0:c.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),_l=u.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...l}=e,a=pt(Jt,n),d=u.useRef(null),c=we(t,d);return hs(),s.jsxs(s.Fragment,{children:[s.jsx(Yr,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(Jn,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":xs(a.open),...l,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx(sh,{titleId:a.titleId}),s.jsx(ah,{contentRef:d,descriptionId:a.descriptionId})]})]})}),ys="DialogTitle",$l=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=pt(ys,n);return s.jsx(ve.h2,{id:o.titleId,...r,ref:t})});$l.displayName=ys;var Ol="DialogDescription",rh=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=pt(Ol,n);return s.jsx(ve.p,{id:o.descriptionId,...r,ref:t})});rh.displayName=Ol;var Pl="DialogClose",oh=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=pt(Pl,n);return s.jsx(ve.button,{type:"button",...r,ref:t,onClick:ie(e.onClick,()=>o.onOpenChange(!1))})});oh.displayName=Pl;function xs(e){return e?"open":"closed"}var Dl="DialogTitleWarning",[C1,Ml]=Vd(Dl,{contentName:Jt,titleName:ys,docsSlug:"dialog"}),sh=({titleId:e})=>{const t=Ml(Dl),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
51
-
52
- If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
53
-
54
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return u.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},ih="DialogDescriptionWarning",ah=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Ml(ih).contentName}}.`;return u.useEffect(()=>{var i;const o=(i=e.current)==null?void 0:i.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},lh=jl,ch=Al,dh=Tl,uh=Rl,ph=$l;function Il(e){const t=e+"CollectionProvider",[n,r]=Mt(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=x=>{const{scope:b,children:k}=x,C=Pe.useRef(null),E=Pe.useRef(new Map).current;return s.jsx(o,{scope:b,itemMap:E,collectionRef:C,children:k})};l.displayName=t;const a=e+"CollectionSlot",d=hn(a),c=Pe.forwardRef((x,b)=>{const{scope:k,children:C}=x,E=i(a,k),v=we(b,E.collectionRef);return s.jsx(d,{ref:v,children:C})});c.displayName=a;const f=e+"CollectionItemSlot",p="data-radix-collection-item",h=hn(f),g=Pe.forwardRef((x,b)=>{const{scope:k,children:C,...E}=x,v=Pe.useRef(null),w=we(b,v),A=i(f,k);return Pe.useEffect(()=>(A.itemMap.set(v,{ref:v,...E}),()=>void A.itemMap.delete(v))),s.jsx(h,{[p]:"",ref:w,children:C})});g.displayName=f;function S(x){const b=i(e+"CollectionConsumer",x);return Pe.useCallback(()=>{const C=b.collectionRef.current;if(!C)return[];const E=Array.from(C.querySelectorAll(`[${p}]`));return Array.from(b.itemMap.values()).sort((A,R)=>E.indexOf(A.ref.current)-E.indexOf(R.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:l,Slot:c,ItemSlot:g},S,r]}var fh=u.createContext(void 0);function hh(e){const t=u.useContext(fh);return e||t||"ltr"}var vo="rovingFocusGroup.onEntryFocus",mh={bubbles:!1,cancelable:!0},Zn="RovingFocusGroup",[Wo,Ll,gh]=Il(Zn),[yh,Nl]=Mt(Zn,[gh]),[xh,bh]=yh(Zn),Bl=u.forwardRef((e,t)=>s.jsx(Wo.Provider,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Wo.Slot,{scope:e.__scopeRovingFocusGroup,children:s.jsx(vh,{...e,ref:t})})}));Bl.displayName=Zn;var vh=u.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:d,onEntryFocus:c,preventScrollOnEntryFocus:f=!1,...p}=e,h=u.useRef(null),g=we(t,h),S=hh(i),[x,b]=us({prop:l,defaultProp:a??null,onChange:d,caller:Zn}),[k,C]=u.useState(!1),E=Rt(c),v=Ll(n),w=u.useRef(!1),[A,R]=u.useState(0);return u.useEffect(()=>{const y=h.current;if(y)return y.addEventListener(vo,E),()=>y.removeEventListener(vo,E)},[E]),s.jsx(xh,{scope:n,orientation:r,dir:S,loop:o,currentTabStopId:x,onItemFocus:u.useCallback(y=>b(y),[b]),onItemShiftTab:u.useCallback(()=>C(!0),[]),onFocusableItemAdd:u.useCallback(()=>R(y=>y+1),[]),onFocusableItemRemove:u.useCallback(()=>R(y=>y-1),[]),children:s.jsx(ve.div,{tabIndex:k||A===0?-1:0,"data-orientation":r,...p,ref:g,style:{outline:"none",...e.style},onMouseDown:ie(e.onMouseDown,()=>{w.current=!0}),onFocus:ie(e.onFocus,y=>{const M=!w.current;if(y.target===y.currentTarget&&M&&!k){const $=new CustomEvent(vo,mh);if(y.currentTarget.dispatchEvent($),!$.defaultPrevented){const T=v().filter(P=>P.focusable),L=T.find(P=>P.active),I=T.find(P=>P.id===x),Y=[L,I,...T].filter(Boolean).map(P=>P.ref.current);ql(Y,f)}}w.current=!1}),onBlur:ie(e.onBlur,()=>C(!1))})})}),Fl="RovingFocusGroupItem",zl=u.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,children:l,...a}=e,d=Ln(),c=i||d,f=bh(Fl,n),p=f.currentTabStopId===c,h=Ll(n),{onFocusableItemAdd:g,onFocusableItemRemove:S,currentTabStopId:x}=f;return u.useEffect(()=>{if(r)return g(),()=>S()},[r,g,S]),s.jsx(Wo.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:s.jsx(ve.span,{tabIndex:p?0:-1,"data-orientation":f.orientation,...a,ref:t,onMouseDown:ie(e.onMouseDown,b=>{r?f.onItemFocus(c):b.preventDefault()}),onFocus:ie(e.onFocus,()=>f.onItemFocus(c)),onKeyDown:ie(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){f.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const k=wh(b,f.orientation,f.dir);if(k!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let E=h().filter(v=>v.focusable).map(v=>v.ref.current);if(k==="last")E.reverse();else if(k==="prev"||k==="next"){k==="prev"&&E.reverse();const v=E.indexOf(b.currentTarget);E=f.loop?jh(E,v+1):E.slice(v+1)}setTimeout(()=>ql(E))}}),children:typeof l=="function"?l({isCurrentTabStop:p,hasTabStop:x!=null}):l})})});zl.displayName=Fl;var Sh={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function kh(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function wh(e,t,n){const r=kh(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Sh[r]}function ql(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function jh(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Ch=Bl,Eh=zl,Ko=["Enter"," "],Ah=["ArrowDown","PageUp","Home"],Ul=["ArrowUp","PageDown","End"],Th=[...Ah,...Ul],Rh={ltr:[...Ko,"ArrowRight"],rtl:[...Ko,"ArrowLeft"]},_h={ltr:["ArrowLeft"],rtl:["ArrowRight"]},to="Menu",[Wn,$h,Oh]=Il(to),[Xt,Wl]=Mt(to,[Oh,vn,Nl]),bs=vn(),Kl=Nl(),[E1,Zt]=Xt(to),[A1,er]=Xt(to),Ph="MenuAnchor",vs=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=bs(n);return s.jsx(Gr,{...o,...r,ref:t})});vs.displayName=Ph;var Ss="MenuPortal",[Dh,Vl]=Xt(Ss,{forceMount:void 0}),Hl=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Zt(Ss,t);return s.jsx(Dh,{scope:t,forceMount:n,children:s.jsx(rt,{present:n||i.open,children:s.jsx(Yn,{asChild:!0,container:o,children:r})})})};Hl.displayName=Ss;var nt="MenuContent",[Mh,ks]=Xt(nt),Gl=u.forwardRef((e,t)=>{const n=Vl(nt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Zt(nt,e.__scopeMenu),l=er(nt,e.__scopeMenu);return s.jsx(Wn.Provider,{scope:e.__scopeMenu,children:s.jsx(rt,{present:r||i.open,children:s.jsx(Wn.Slot,{scope:e.__scopeMenu,children:l.modal?s.jsx(Ih,{...o,ref:t}):s.jsx(Lh,{...o,ref:t})})})})}),Ih=u.forwardRef((e,t)=>{const n=Zt(nt,e.__scopeMenu),r=u.useRef(null),o=we(t,r);return u.useEffect(()=>{const i=r.current;if(i)return ms(i)},[]),s.jsx(ws,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ie(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Lh=u.forwardRef((e,t)=>{const n=Zt(nt,e.__scopeMenu);return s.jsx(ws,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Nh=hn("MenuContent.ScrollLock"),ws=u.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:a,onEntryFocus:d,onEscapeKeyDown:c,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:h,onDismiss:g,disableOutsideScroll:S,...x}=e,b=Zt(nt,n),k=er(nt,n),C=bs(n),E=Kl(n),v=$h(n),[w,A]=u.useState(null),R=u.useRef(null),y=we(t,R,b.onContentChange),M=u.useRef(0),$=u.useRef(""),T=u.useRef(0),L=u.useRef(null),I=u.useRef("right"),G=u.useRef(0),Y=S?Zr:u.Fragment,P=S?{as:Nh,allowPinchZoom:!0}:void 0,q=W=>{var re,ge;const se=$.current+W,H=v().filter(ye=>!ye.disabled),te=document.activeElement,J=(re=H.find(ye=>ye.ref.current===te))==null?void 0:re.textValue,B=H.map(ye=>ye.textValue),ne=Qh(B,se,J),ce=(ge=H.find(ye=>ye.textValue===ne))==null?void 0:ge.ref.current;(function ye(Ae){$.current=Ae,window.clearTimeout(M.current),Ae!==""&&(M.current=window.setTimeout(()=>ye(""),1e3))})(se),ce&&setTimeout(()=>ce.focus())};u.useEffect(()=>()=>window.clearTimeout(M.current),[]),hs();const O=u.useCallback(W=>{var H,te;return I.current===((H=L.current)==null?void 0:H.side)&&Xh(W,(te=L.current)==null?void 0:te.area)},[]);return s.jsx(Mh,{scope:n,searchRef:$,onItemEnter:u.useCallback(W=>{O(W)&&W.preventDefault()},[O]),onItemLeave:u.useCallback(W=>{var se;O(W)||((se=R.current)==null||se.focus(),A(null))},[O]),onTriggerLeave:u.useCallback(W=>{O(W)&&W.preventDefault()},[O]),pointerGraceTimerRef:T,onPointerGraceIntentChange:u.useCallback(W=>{L.current=W},[]),children:s.jsx(Y,{...P,children:s.jsx(Yr,{asChild:!0,trapped:o,onMountAutoFocus:ie(i,W=>{var se;W.preventDefault(),(se=R.current)==null||se.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:s.jsx(Jn,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:h,onDismiss:g,children:s.jsx(Ch,{asChild:!0,...E,dir:k.dir,orientation:"vertical",loop:r,currentTabStopId:w,onCurrentTabStopIdChange:A,onEntryFocus:ie(d,W=>{k.isUsingKeyboardRef.current||W.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(cs,{role:"menu","aria-orientation":"vertical","data-state":dc(b.open),"data-radix-menu-content":"",dir:k.dir,...C,...x,ref:y,style:{outline:"none",...x.style},onKeyDown:ie(x.onKeyDown,W=>{const H=W.target.closest("[data-radix-menu-content]")===W.currentTarget,te=W.ctrlKey||W.altKey||W.metaKey,J=W.key.length===1;H&&(W.key==="Tab"&&W.preventDefault(),!te&&J&&q(W.key));const B=R.current;if(W.target!==B||!Th.includes(W.key))return;W.preventDefault();const ce=v().filter(re=>!re.disabled).map(re=>re.ref.current);Ul.includes(W.key)&&ce.reverse(),Gh(ce)}),onBlur:ie(e.onBlur,W=>{W.currentTarget.contains(W.target)||(window.clearTimeout(M.current),$.current="")}),onPointerMove:ie(e.onPointerMove,Kn(W=>{const se=W.target,H=G.current!==W.clientX;if(W.currentTarget.contains(se)&&H){const te=W.clientX>G.current?"right":"left";I.current=te,G.current=W.clientX}}))})})})})})})});Gl.displayName=nt;var Bh="MenuGroup",js=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(ve.div,{role:"group",...r,ref:t})});js.displayName=Bh;var Fh="MenuLabel",Jl=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(ve.div,{...r,ref:t})});Jl.displayName=Fh;var Dr="MenuItem",Ri="menu.itemSelect",no=u.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=u.useRef(null),l=er(Dr,e.__scopeMenu),a=ks(Dr,e.__scopeMenu),d=we(t,i),c=u.useRef(!1),f=()=>{const p=i.current;if(!n&&p){const h=new CustomEvent(Ri,{bubbles:!0,cancelable:!0});p.addEventListener(Ri,g=>r==null?void 0:r(g),{once:!0}),Da(p,h),h.defaultPrevented?c.current=!1:l.onClose()}};return s.jsx(Ql,{...o,ref:d,disabled:n,onClick:ie(e.onClick,f),onPointerDown:p=>{var h;(h=e.onPointerDown)==null||h.call(e,p),c.current=!0},onPointerUp:ie(e.onPointerUp,p=>{var h;c.current||(h=p.currentTarget)==null||h.click()}),onKeyDown:ie(e.onKeyDown,p=>{const h=a.searchRef.current!=="";n||h&&p.key===" "||Ko.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});no.displayName=Dr;var Ql=u.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,l=ks(Dr,n),a=Kl(n),d=u.useRef(null),c=we(t,d),[f,p]=u.useState(!1),[h,g]=u.useState("");return u.useEffect(()=>{const S=d.current;S&&g((S.textContent??"").trim())},[i.children]),s.jsx(Wn.ItemSlot,{scope:n,disabled:r,textValue:o??h,children:s.jsx(Eh,{asChild:!0,...a,focusable:!r,children:s.jsx(ve.div,{role:"menuitem","data-highlighted":f?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:c,onPointerMove:ie(e.onPointerMove,Kn(S=>{r?l.onItemLeave(S):(l.onItemEnter(S),S.defaultPrevented||S.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ie(e.onPointerLeave,Kn(S=>l.onItemLeave(S))),onFocus:ie(e.onFocus,()=>p(!0)),onBlur:ie(e.onBlur,()=>p(!1))})})})}),zh="MenuCheckboxItem",Yl=u.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return s.jsx(nc,{scope:e.__scopeMenu,checked:n,children:s.jsx(no,{role:"menuitemcheckbox","aria-checked":Mr(n)?"mixed":n,...o,ref:t,"data-state":Es(n),onSelect:ie(o.onSelect,()=>r==null?void 0:r(Mr(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Yl.displayName=zh;var Xl="MenuRadioGroup",[qh,Uh]=Xt(Xl,{value:void 0,onValueChange:()=>{}}),Zl=u.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,i=Rt(r);return s.jsx(qh,{scope:e.__scopeMenu,value:n,onValueChange:i,children:s.jsx(js,{...o,ref:t})})});Zl.displayName=Xl;var ec="MenuRadioItem",tc=u.forwardRef((e,t)=>{const{value:n,...r}=e,o=Uh(ec,e.__scopeMenu),i=n===o.value;return s.jsx(nc,{scope:e.__scopeMenu,checked:i,children:s.jsx(no,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":Es(i),onSelect:ie(r.onSelect,()=>{var l;return(l=o.onValueChange)==null?void 0:l.call(o,n)},{checkForDefaultPrevented:!1})})})});tc.displayName=ec;var Cs="MenuItemIndicator",[nc,Wh]=Xt(Cs,{checked:!1}),rc=u.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=Wh(Cs,n);return s.jsx(rt,{present:r||Mr(i.checked)||i.checked===!0,children:s.jsx(ve.span,{...o,ref:t,"data-state":Es(i.checked)})})});rc.displayName=Cs;var Kh="MenuSeparator",oc=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(ve.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});oc.displayName=Kh;var Vh="MenuArrow",sc=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=bs(n);return s.jsx(ds,{...o,...r,ref:t})});sc.displayName=Vh;var Hh="MenuSub",[T1,ic]=Xt(Hh),_n="MenuSubTrigger",ac=u.forwardRef((e,t)=>{const n=Zt(_n,e.__scopeMenu),r=er(_n,e.__scopeMenu),o=ic(_n,e.__scopeMenu),i=ks(_n,e.__scopeMenu),l=u.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:d}=i,c={__scopeMenu:e.__scopeMenu},f=u.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return u.useEffect(()=>f,[f]),u.useEffect(()=>{const p=a.current;return()=>{window.clearTimeout(p),d(null)}},[a,d]),s.jsx(vs,{asChild:!0,...c,children:s.jsx(Ql,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":dc(n.open),...e,ref:Ur(t,o.onTriggerChange),onClick:p=>{var h;(h=e.onClick)==null||h.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ie(e.onPointerMove,Kn(p=>{i.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!l.current&&(i.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{n.onOpenChange(!0),f()},100))})),onPointerLeave:ie(e.onPointerLeave,Kn(p=>{var g,S;f();const h=(g=n.content)==null?void 0:g.getBoundingClientRect();if(h){const x=(S=n.content)==null?void 0:S.dataset.side,b=x==="right",k=b?-5:5,C=h[b?"left":"right"],E=h[b?"right":"left"];i.onPointerGraceIntentChange({area:[{x:p.clientX+k,y:p.clientY},{x:C,y:h.top},{x:E,y:h.top},{x:E,y:h.bottom},{x:C,y:h.bottom}],side:x}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(p),p.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ie(e.onKeyDown,p=>{var g;const h=i.searchRef.current!=="";e.disabled||h&&p.key===" "||Rh[r.dir].includes(p.key)&&(n.onOpenChange(!0),(g=n.content)==null||g.focus(),p.preventDefault())})})})});ac.displayName=_n;var lc="MenuSubContent",cc=u.forwardRef((e,t)=>{const n=Vl(nt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Zt(nt,e.__scopeMenu),l=er(nt,e.__scopeMenu),a=ic(lc,e.__scopeMenu),d=u.useRef(null),c=we(t,d);return s.jsx(Wn.Provider,{scope:e.__scopeMenu,children:s.jsx(rt,{present:r||i.open,children:s.jsx(Wn.Slot,{scope:e.__scopeMenu,children:s.jsx(ws,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:c,align:"start",side:l.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:f=>{var p;l.isUsingKeyboardRef.current&&((p=d.current)==null||p.focus()),f.preventDefault()},onCloseAutoFocus:f=>f.preventDefault(),onFocusOutside:ie(e.onFocusOutside,f=>{f.target!==a.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ie(e.onEscapeKeyDown,f=>{l.onClose(),f.preventDefault()}),onKeyDown:ie(e.onKeyDown,f=>{var g;const p=f.currentTarget.contains(f.target),h=_h[l.dir].includes(f.key);p&&h&&(i.onOpenChange(!1),(g=a.trigger)==null||g.focus(),f.preventDefault())})})})})})});cc.displayName=lc;function dc(e){return e?"open":"closed"}function Mr(e){return e==="indeterminate"}function Es(e){return Mr(e)?"indeterminate":e?"checked":"unchecked"}function Gh(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Jh(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Qh(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let l=Jh(e,Math.max(i,0));o.length===1&&(l=l.filter(c=>c!==n));const d=l.find(c=>c.toLowerCase().startsWith(o.toLowerCase()));return d!==n?d:void 0}function Yh(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,l=t.length-1;i<t.length;l=i++){const a=t[i],d=t[l],c=a.x,f=a.y,p=d.x,h=d.y;f>r!=h>r&&n<(p-c)*(r-f)/(h-f)+c&&(o=!o)}return o}function Xh(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Yh(n,t)}function Kn(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Zh=vs,em=Hl,tm=Gl,nm=js,rm=Jl,om=no,sm=Yl,im=Zl,am=tc,lm=rc,cm=oc,dm=sc,um=ac,pm=cc,uc="DropdownMenu",[fm]=Mt(uc,[Wl]),Je=Wl(),[R1,pc]=fm(uc),fc="DropdownMenuTrigger",hm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=pc(fc,n),l=Je(n);return s.jsx(Zh,{asChild:!0,...l,children:s.jsx(ve.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:Ur(t,i.triggerRef),onPointerDown:ie(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(i.onOpenToggle(),i.open||a.preventDefault())}),onKeyDown:ie(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&i.onOpenToggle(),a.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});hm.displayName=fc;var mm="DropdownMenuPortal",hc=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Je(t);return s.jsx(em,{...r,...n})};hc.displayName=mm;var mc="DropdownMenuContent",gc=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=pc(mc,n),i=Je(n),l=u.useRef(!1);return s.jsx(tm,{id:o.contentId,"aria-labelledby":o.triggerId,...i,...r,ref:t,onCloseAutoFocus:ie(e.onCloseAutoFocus,a=>{var d;l.current||(d=o.triggerRef.current)==null||d.focus(),l.current=!1,a.preventDefault()}),onInteractOutside:ie(e.onInteractOutside,a=>{const d=a.detail.originalEvent,c=d.button===0&&d.ctrlKey===!0,f=d.button===2||c;(!o.modal||f)&&(l.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});gc.displayName=mc;var gm="DropdownMenuGroup",ym=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(nm,{...o,...r,ref:t})});ym.displayName=gm;var xm="DropdownMenuLabel",yc=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(rm,{...o,...r,ref:t})});yc.displayName=xm;var bm="DropdownMenuItem",xc=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(om,{...o,...r,ref:t})});xc.displayName=bm;var vm="DropdownMenuCheckboxItem",Sm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(sm,{...o,...r,ref:t})});Sm.displayName=vm;var km="DropdownMenuRadioGroup",wm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(im,{...o,...r,ref:t})});wm.displayName=km;var jm="DropdownMenuRadioItem",Cm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(am,{...o,...r,ref:t})});Cm.displayName=jm;var Em="DropdownMenuItemIndicator",Am=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(lm,{...o,...r,ref:t})});Am.displayName=Em;var Tm="DropdownMenuSeparator",bc=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(cm,{...o,...r,ref:t})});bc.displayName=Tm;var Rm="DropdownMenuArrow",_m=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(dm,{...o,...r,ref:t})});_m.displayName=Rm;var $m="DropdownMenuSubTrigger",Om=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(um,{...o,...r,ref:t})});Om.displayName=$m;var Pm="DropdownMenuSubContent",Dm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Je(n);return s.jsx(pm,{...o,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Dm.displayName=Pm;var Mm=hc,Im=gc,Lm=yc,Nm=xc,Bm=bc;const Fm=u.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>s.jsx(Mm,{container:e,children:s.jsx(Im,{ref:o,sideOffset:n,style:{minWidth:180,background:le("surfaceElevated"),color:le("textPrimary"),border:`1px solid ${le("borderDefault")}`,borderRadius:Dt.md,boxShadow:le("shadowMd"),padding:fe[1],zIndex:zn.popover,...t},...r})}));Fm.displayName="DropdownMenuContent";const zm=u.forwardRef(({style:e,...t},n)=>s.jsx(Nm,{ref:n,style:{display:"flex",alignItems:"center",gap:fe[2],padding:`${fe[1]} ${fe[2]}`,fontSize:Be.sm,borderRadius:Dt.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));zm.displayName="DropdownMenuItem";const qm=u.forwardRef(({style:e,...t},n)=>s.jsx(Bm,{ref:n,style:{height:1,background:le("borderSubtle"),margin:`${fe[1]} 0`,...e},...t}));qm.displayName="DropdownMenuSeparator";const Um=u.forwardRef(({style:e,...t},n)=>s.jsx(Lm,{ref:n,style:{padding:`${fe[1]} ${fe[2]}`,fontSize:Be.xs,color:le("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));Um.displayName="DropdownMenuLabel";var vc="Popover",[Sc]=Mt(vc,[vn]),ro=vn(),[_1,It]=Sc(vc),kc="PopoverAnchor",Wm=u.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=It(kc,n),i=ro(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:a}=o;return u.useEffect(()=>(l(),()=>a()),[l,a]),s.jsx(Gr,{...i,...r,ref:t})});Wm.displayName=kc;var wc="PopoverTrigger",Km=u.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=It(wc,n),i=ro(n),l=we(t,o.triggerRef),a=s.jsx(ve.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Tc(o.open),...r,ref:l,onClick:ie(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?a:s.jsx(Gr,{asChild:!0,...i,children:a})});Km.displayName=wc;var As="PopoverPortal",[Vm,Hm]=Sc(As,{forceMount:void 0}),jc=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=It(As,t);return s.jsx(Vm,{scope:t,forceMount:n,children:s.jsx(rt,{present:n||i.open,children:s.jsx(Yn,{asChild:!0,container:o,children:r})})})};jc.displayName=As;var yn="PopoverContent",Cc=u.forwardRef((e,t)=>{const n=Hm(yn,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=It(yn,e.__scopePopover);return s.jsx(rt,{present:r||i.open,children:i.modal?s.jsx(Jm,{...o,ref:t}):s.jsx(Qm,{...o,ref:t})})});Cc.displayName=yn;var Gm=hn("PopoverContent.RemoveScroll"),Jm=u.forwardRef((e,t)=>{const n=It(yn,e.__scopePopover),r=u.useRef(null),o=we(t,r),i=u.useRef(!1);return u.useEffect(()=>{const l=r.current;if(l)return ms(l)},[]),s.jsx(Zr,{as:Gm,allowPinchZoom:!0,children:s.jsx(Ec,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ie(e.onCloseAutoFocus,l=>{var a;l.preventDefault(),i.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:ie(e.onPointerDownOutside,l=>{const a=l.detail.originalEvent,d=a.button===0&&a.ctrlKey===!0,c=a.button===2||d;i.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:ie(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),Qm=u.forwardRef((e,t)=>{const n=It(yn,e.__scopePopover),r=u.useRef(!1),o=u.useRef(!1);return s.jsx(Ec,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,a;(l=e.onCloseAutoFocus)==null||l.call(e,i),i.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var d,c;(d=e.onInteractOutside)==null||d.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const l=i.target;((c=n.triggerRef.current)==null?void 0:c.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),Ec=u.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:a,onPointerDownOutside:d,onFocusOutside:c,onInteractOutside:f,...p}=e,h=It(yn,n),g=ro(n);return hs(),s.jsx(Yr,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(Jn,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:f,onEscapeKeyDown:a,onPointerDownOutside:d,onFocusOutside:c,onDismiss:()=>h.onOpenChange(!1),children:s.jsx(cs,{"data-state":Tc(h.open),role:"dialog",id:h.contentId,...g,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Ac="PopoverClose",Ym=u.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=It(Ac,n);return s.jsx(ve.button,{type:"button",...r,ref:t,onClick:ie(e.onClick,()=>o.onOpenChange(!1))})});Ym.displayName=Ac;var Xm="PopoverArrow",Zm=u.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=ro(n);return s.jsx(ds,{...o,...r,ref:t})});Zm.displayName=Xm;function Tc(e){return e?"open":"closed"}var eg=jc,tg=Cc;const ng=u.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>s.jsx(eg,{container:e,children:s.jsx(tg,{ref:o,sideOffset:n,style:{background:le("surfaceElevated"),color:le("textPrimary"),border:`1px solid ${le("borderDefault")}`,borderRadius:Dt.md,boxShadow:le("shadowMd"),padding:fe[3],zIndex:zn.popover,minWidth:220,...t},...r})}));ng.displayName="PopoverContent";function Ts({icon:e,eyebrow:t,title:n,subtitle:r,status:o,actions:i,toolbar:l,bodyPadding:a=14,children:d}){return s.jsxs("div",{className:"panel-frame",children:[s.jsxs("div",{className:"panel-frame-header",children:[s.jsxs("div",{className:"panel-frame-heading",children:[e&&s.jsx("span",{className:"panel-frame-icon",children:e}),s.jsxs("div",{className:"panel-frame-title-col",children:[t&&s.jsx("div",{className:"panel-frame-eyebrow",children:t}),s.jsxs("div",{className:"panel-frame-title-row",children:[n&&s.jsx("h2",{className:"panel-frame-title",children:n}),o&&s.jsx("span",{className:"panel-frame-status",children:o})]}),r&&s.jsx("div",{className:"panel-frame-subtitle",children:r})]})]}),i&&s.jsx("div",{className:"panel-frame-actions",children:i})]}),l&&s.jsx("div",{className:"panel-frame-toolbar",children:l}),s.jsx("div",{className:"panel-frame-body",style:{padding:a},children:d})]})}function Rc({tone:e="neutral",icon:t,children:n,className:r="",...o}){return s.jsxs("span",{className:`status-pill tone-${e} ${r}`,...o,children:[t&&s.jsx("span",{className:"status-pill-icon",children:t}),n]})}function Nn({icon:e,title:t,description:n,action:r}){return s.jsxs("div",{className:"panel-empty",children:[e&&s.jsx("span",{className:"panel-empty-icon",children:e}),t&&s.jsx("p",{className:"panel-empty-title",children:t}),n&&s.jsx("p",{className:"panel-empty-desc",children:n}),r]})}function _c({left:e,right:t,children:n,className:r=""}){return s.jsxs("div",{className:`panel-toolbar ${r}`,children:[e&&s.jsx("div",{className:"panel-toolbar-left",children:e}),n&&s.jsx("div",{className:"panel-toolbar-center",children:n}),t&&s.jsx("div",{className:"panel-toolbar-right",children:t})]})}function rg({shortcut:e,children:t,style:n,...r}){return s.jsx("kbd",{...r,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:18,height:18,padding:`0 ${fe[1]}px`,borderRadius:Dt.sm,border:`1px solid ${le("borderSubtle")}`,background:le("surfaceRaised"),color:le("textSecondary"),fontFamily:"var(--dql-font-mono, monospace)",fontSize:Be.xs,fontWeight:Zo.medium,lineHeight:1,whiteSpace:"nowrap",...n},children:e??t})}const _i=e=>{let t;const n=new Set,r=(c,f)=>{const p=typeof c=="function"?c(t):c;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(g=>g(t,h))}},o=()=>t,a={setState:r,getState:o,getInitialState:()=>d,subscribe:c=>(n.add(c),()=>n.delete(c))},d=t=e(r,o,a);return a},og=(e=>e?_i(e):_i),sg=e=>e;function ig(e,t=sg){const n=Pe.useSyncExternalStore(e.subscribe,Pe.useCallback(()=>t(e.getState()),[e,t]),Pe.useCallback(()=>t(e.getInitialState()),[e,t]));return Pe.useDebugValue(n),n}const $i=e=>{const t=og(e),n=r=>ig(t,r);return Object.assign(n,t),n},ag=(e=>e?$i(e):$i),Oi=e=>Symbol.iterator in e,Pi=e=>"entries"in e,Di=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[o,i]of n)if(!r.has(o)||!Object.is(i,r.get(o)))return!1;return!0},lg=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=n.next(),i=r.next();for(;!o.done&&!i.done;){if(!Object.is(o.value,i.value))return!1;o=n.next(),i=r.next()}return!!o.done&&!!i.done};function cg(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Oi(e)&&Oi(t)?Pi(e)&&Pi(t)?Di(e,t):lg(e,t):Di({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function dg(e){const t=Pe.useRef(void 0);return n=>{const r=e(n);return cg(t.current,r)?t.current:t.current=r}}const ug=/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g;function Rs(e,t){const n=new Map;for(const o of t)n.set(o.id,o.id),o.name&&n.set(o.name,o.id);const r=new Map;for(const o of e.dependencies??[])r.set(o.cellId,o);for(const o of e.content.matchAll(ug)){const i=o[1],l=n.get(i);l&&l!==e.id&&r.set(l,{cellId:l,output:i})}if(e.upstream){const o=n.get(e.upstream);o&&o!==e.id&&r.set(o,{cellId:o,output:e.upstream})}return[...r.values()]}function pg(e){const t=e.filter(c=>!["markdown","param","chat"].includes(c.type)),n=new Set(t.map(c=>c.id)),r=new Set(e.map(c=>c.id)),o=new Map(t.map(c=>[c.id,0])),i=new Map(t.map(c=>[c.id,[]])),l=[];for(const c of t)for(const f of Rs(c,e)){if(!r.has(f.cellId)){l.push({cellId:c.id,dependency:f.cellId});continue}n.has(f.cellId)&&(i.get(f.cellId).push(c.id),o.set(c.id,(o.get(c.id)??0)+1))}const a=t.filter(c=>o.get(c.id)===0),d=[];for(;a.length>0;){const c=a.shift();d.push(c);for(const f of i.get(c.id)??[]){const p=(o.get(f)??0)-1;if(o.set(f,p),p===0){const h=t.find(g=>g.id===f);h&&a.push(h)}}}return{ordered:d,cycleCellIds:t.filter(c=>!d.some(f=>f.id===c.id)).map(c=>c.id),missing:l}}function fg(e,t){const n=new Set,r=[e];for(;r.length>0;){const o=r.shift();for(const i of t)n.has(i.id)||i.id===e||Rs(i,t).some(l=>l.cellId===o)&&(n.add(i.id),r.push(i.id))}return n}function hg(){var e;if(typeof window<"u")try{(e=window.localStorage)==null||e.removeItem("dql-app-mode")}catch{}return"studio"}function mg(){var t;if(typeof window>"u")return"paper";const e=(t=window.localStorage)==null?void 0:t.getItem("dql-theme");return e==="obsidian"||e==="paper"||e==="white"?e:e==="midnight"||e==="dark"?"obsidian":e==="arctic"?"white":"paper"}function gg(){if(typeof window>"u")return"apps";const e=new URLSearchParams(window.location.search);return e.has("domain")||e.has("domainSection")||e.has("modelArea")?"domains":"apps"}const yg={mainView:gg(),agentLogRun:void 0,settingsTab:"overview",themeMode:mg(),appMode:hg(),sidebarPanel:null,sidebarOpen:!1,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,schemaTables:[],schemaLoading:!1,semanticLayer:{available:!1,provider:null,metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[],domains:[],tags:[],favorites:[],recentlyUsed:[],loading:!1,lastSyncTime:null},devPanelOpen:!1,devPanelTab:"logs",queryLog:[],newNotebookModalOpen:!1,newBlockModalOpen:!1,newBlockModalDefaultType:"custom",autoSave:!0,executionCounter:0,savingFile:!1,lineageFullscreen:!1,lineageFocusNodeId:null,lineageReturnTarget:null,lineageDrawerOpen:!1,lineageDrawerNodeId:null,dashboardMode:!1,activeBlockPath:null,blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:null,blockStudioMetadata:null,blockStudioCatalog:null,blockStudioCatalogLoading:!1,blockStudioImportOpen:!1,blockStudioDbtStatus:null,setupOpen:!1,inspectorOpen:!1,inspectorContext:null,apps:[],appsLoading:!1,activeAppId:null,activeDashboardId:null,activeAppExperience:"view",activeAppSection:"dashboards",activePersona:null,globalAi:{open:!1,audience:"stakeholder",context:{}}};function Vo(e){const t=new Set;return e.map(n=>{var o;let r=(o=n.id)==null?void 0:o.trim();if(!r||t.has(r))do r=tt();while(t.has(r));return t.add(r),r===n.id?n:{...n,id:r}})}function xg(e,t){var n,r,o,i,l,a,d;switch(t.type){case"SET_MAIN_VIEW":return t.view==="imports"?{...e,mainView:"block_studio",sidebarPanel:"block_library",sidebarOpen:!0,blockStudioImportOpen:!0,lineageFullscreen:!1,lineageFocusNodeId:null,lineageReturnTarget:null}:t.view==="home"?{...e,mainView:"home",sidebarPanel:null,sidebarOpen:!1,lineageFullscreen:!1,lineageFocusNodeId:null,lineageReturnTarget:null,lineageDrawerOpen:!1,lineageDrawerNodeId:null,dashboardMode:!1}:{...e,mainView:t.view,lineageFullscreen:!1,lineageFocusNodeId:null,lineageReturnTarget:null};case"OPEN_AGENT_LOG":return{...e,agentLogRun:t.run,mainView:"agent_log"};case"SET_SETTINGS_TAB":return{...e,settingsTab:t.tab};case"SET_THEME":{if(typeof document<"u"){const c=t.mode==="dark"||t.mode==="midnight"?"obsidian":t.mode==="light"?"paper":t.mode==="arctic"?"white":t.mode;document.documentElement.setAttribute("data-theme",c);try{(n=window.localStorage)==null||n.setItem("dql-theme",t.mode)}catch{}}return{...e,themeMode:t.mode}}case"SET_APP_MODE":{if(typeof window<"u")try{(r=window.localStorage)==null||r.removeItem("dql-app-mode")}catch{}return{...e,appMode:"studio"}}case"SET_SIDEBAR_PANEL":{if(t.panel==="lineage")return{...e,sidebarPanel:"lineage",sidebarOpen:!1,lineageFullscreen:!1,lineageFocusNodeId:e.mainView==="lineage_detail"?e.lineageFocusNodeId:null,lineageReturnTarget:null,mainView:"lineage"};const c=["connection","git","apps","readiness","skills","domains","settings"],f=t.panel!==null&&c.includes(t.panel);return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null&&!f,lineageFullscreen:!1,lineageFocusNodeId:null,lineageReturnTarget:null,mainView:t.panel==="connection"?"connection":t.panel==="git"?"git":t.panel==="apps"?"apps":t.panel==="readiness"?"readiness":t.panel==="skills"?"skills":t.panel==="domains"?"domains":t.panel==="settings"?"connection":t.panel==="files"?"notebook":t.panel==="block_library"||((o=e.activeFile)==null?void 0:o.type)==="block"?"block_studio":"notebook"}}case"TOGGLE_SIDEBAR":return{...e,sidebarOpen:!e.sidebarOpen};case"SET_FILES":return{...e,files:t.files};case"SET_FILES_LOADING":return{...e,filesLoading:t.loading};case"OPEN_BUSINESS_ARTIFACT":return{...e,activeFile:t.file,cells:[],notebookTitle:t.file.name.replace(/\.(dqlnb|dql)$/i,""),notebookDirty:!1,mainView:"business_artifact",activeBlockPath:null,blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:null,blockStudioMetadata:null,dashboardMode:!1,lineageFullscreen:!1,lineageDrawerOpen:!1,lineageDrawerNodeId:null,lineageFocusNodeId:`${t.file.type}:${t.file.name.replace(/\.(dqlnb|dql)$/i,"")}`};case"OPEN_FILE":return{...e,activeFile:t.file,cells:Vo(t.cells),notebookTitle:t.title,notebookMetadata:t.metadata??{},notebookDirty:!1,mainView:t.file.type==="block"?"block_studio":"notebook",activeBlockPath:t.file.type==="block"?t.file.path:null,blockStudioDraft:t.file.type==="block"?e.blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:t.file.type==="block"?e.blockStudioPreview:null,blockStudioValidation:t.file.type==="block"?e.blockStudioValidation:null,blockStudioMetadata:t.file.type==="block"?e.blockStudioMetadata:null,lineageFullscreen:!1,lineageFocusNodeId:null};case"OPEN_BLOCK_STUDIO":return{...e,activeFile:t.file,cells:[],notebookTitle:t.payload.metadata.name,notebookDirty:!1,mainView:"block_studio",dashboardMode:!1,activeBlockPath:t.payload.path,blockStudioDraft:t.payload.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,blockStudioImportOpen:!1,lineageFullscreen:!1,lineageFocusNodeId:(i=t.payload.metadata)!=null&&i.name?`block:${t.payload.metadata.name}`:null};case"SET_CELLS":return{...e,cells:Vo(t.cells),notebookDirty:!0};case"UPDATE_NOTEBOOK_METADATA":{const c=e.notebookMetadata;let f=!1;for(const p of Object.keys(t.updates))if(c[p]!==t.updates[p]){f=!0;break}return f?{...e,notebookMetadata:{...c,...t.updates},notebookDirty:!0}:e}case"ADD_CELL":{const c=e.cells.some(h=>h.id===t.cell.id)?{...t.cell,id:tt()}:t.cell;if(!t.afterId)return{...e,cells:[...e.cells,c],notebookDirty:!0};const f=e.cells.findIndex(h=>h.id===t.afterId);if(f===-1)return{...e,cells:[...e.cells,c],notebookDirty:!0};const p=[...e.cells];return p.splice(f+1,0,c),{...e,cells:p,notebookDirty:!0}}case"UPDATE_CELL":{const c=t.updates.content!==void 0||t.updates.name!==void 0||t.updates.executionTarget!==void 0||t.updates.datasetRefs!==void 0||t.updates.dependencies!==void 0||t.updates.dqlParameterValues!==void 0||t.updates.blockBinding!==void 0,f=c?fg(t.id,e.cells):new Set,p=e.cells.map(g=>{if(g.id===t.id){const S={...g,...t.updates};return c&&g.result&&t.updates.stale===void 0?{...S,stale:!0}:S}return f.has(g.id)&&g.result?{...g,stale:!0}:g}),h=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:p,notebookDirty:!0,executionCounter:h}}case"DELETE_CELL":return{...e,cells:e.cells.filter(c=>c.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const c=e.cells.findIndex(p=>p.id===t.id);if(c===-1)return e;const f=[...e.cells];return t.direction==="up"&&c>0?[f[c-1],f[c]]=[f[c],f[c-1]]:t.direction==="down"&&c<f.length-1&&([f[c],f[c+1]]=[f[c+1],f[c]]),{...e,cells:f,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:c,toIndex:f}=t;if(c===f||c<0||f<0||c>=e.cells.length||f>=e.cells.length)return e;const p=[...e.cells],[h]=p.splice(c,1);return p.splice(f,0,h),{...e,cells:p,notebookDirty:!0}}case"SET_SCHEMA":return{...e,schemaTables:t.tables};case"SET_SCHEMA_LOADING":return{...e,schemaLoading:t.loading};case"TOGGLE_SCHEMA_TABLE":return{...e,schemaTables:e.schemaTables.map(c=>c.name===t.tableName?{...c,expanded:!c.expanded}:c)};case"TOGGLE_DEV_PANEL":return{...e,devPanelOpen:!e.devPanelOpen};case"SET_DEV_PANEL_TAB":return{...e,devPanelTab:t.tab};case"APPEND_QUERY_LOG":return{...e,queryLog:[...e.queryLog,t.entry]};case"OPEN_NEW_NOTEBOOK_MODAL":return{...e,newNotebookModalOpen:!0};case"CLOSE_NEW_NOTEBOOK_MODAL":return{...e,newNotebookModalOpen:!1};case"OPEN_NEW_BLOCK_MODAL":return{...e,newBlockModalOpen:!0,newBlockModalDefaultType:t.blockType??"custom"};case"START_NEW_BLOCK_WORKSPACE":return{...e,mainView:"block_studio",sidebarPanel:"block_library",sidebarOpen:!0,activeFile:null,activeBlockPath:null,blockStudioDraft:"",blockStudioDirty:!1,blockStudioPreview:null,blockStudioValidation:null,blockStudioMetadata:null,blockStudioImportOpen:!1,newBlockModalOpen:!1,newBlockModalDefaultType:t.blockType??"custom",notebookTitle:"Blocks"};case"CLOSE_NEW_BLOCK_MODAL":return{...e,newBlockModalOpen:!1};case"SET_AUTO_SAVE":return{...e,autoSave:t.enabled};case"SET_NOTEBOOK_DIRTY":return{...e,notebookDirty:t.dirty};case"SET_SAVING":return{...e,savingFile:t.saving};case"FILE_ADDED":return e.files.some(c=>c.path===t.file.path)?e:{...e,files:[...e.files,t.file]};case"FILE_REMOVED":{const c=e.files.filter(f=>f.path!==t.path);return((l=e.activeFile)==null?void 0:l.path)!==t.path?{...e,files:c}:{...e,files:c,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1}}case"SET_TABLE_COLUMNS":return{...e,schemaTables:e.schemaTables.map(c=>c.name===t.tableName?{...c,columns:t.columns}:c)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(c=>c.id===t.id?{...c,paramValue:t.value}:c),notebookDirty:!0};case"SET_SEMANTIC_LAYER":return{...e,semanticLayer:{...t.layer,loading:!1}};case"SET_SEMANTIC_LOADING":return{...e,semanticLayer:{...e.semanticLayer,loading:t.loading}};case"SET_SEMANTIC_FAVORITES":return{...e,semanticLayer:{...e.semanticLayer,favorites:t.favorites}};case"ADD_SEMANTIC_RECENT":{const c=[t.name,...e.semanticLayer.recentlyUsed.filter(f=>f!==t.name)].slice(0,12);return{...e,semanticLayer:{...e.semanticLayer,recentlyUsed:c}}}case"SET_SEMANTIC_DOMAINS":return{...e,semanticLayer:{...e.semanticLayer,domains:t.domains,tags:t.tags,lastSyncTime:t.lastSyncTime??e.semanticLayer.lastSyncTime}};case"TOGGLE_LINEAGE_FULLSCREEN":return{...e,lineageFullscreen:!e.lineageFullscreen};case"SET_LINEAGE_FOCUS":return{...e,lineageFocusNodeId:t.nodeId};case"OPEN_LINEAGE_DETAIL":{const c=t.returnTo!==void 0?t.returnTo:e.mainView==="lineage_detail"?e.lineageReturnTarget:null;return{...e,mainView:"lineage_detail",lineageFullscreen:!1,lineageFocusNodeId:t.nodeId,lineageReturnTarget:c,lineageDrawerOpen:!1,lineageDrawerNodeId:null,dashboardMode:!1}}case"OPEN_LINEAGE_DRAWER":return{...e,lineageDrawerOpen:!0,lineageDrawerNodeId:t.nodeId};case"CLOSE_LINEAGE_DRAWER":return{...e,lineageDrawerOpen:!1,lineageDrawerNodeId:null};case"TOGGLE_DASHBOARD_MODE":return{...e,dashboardMode:!e.dashboardMode};case"SET_BLOCK_STUDIO_DRAFT":return{...e,blockStudioDraft:t.draft,blockStudioDirty:!0};case"SET_BLOCK_STUDIO_DIRTY":return{...e,blockStudioDirty:t.dirty};case"SET_BLOCK_STUDIO_PREVIEW":return{...e,blockStudioPreview:t.preview};case"SET_BLOCK_STUDIO_VALIDATION":return{...e,blockStudioValidation:t.validation};case"SET_BLOCK_STUDIO_METADATA":return{...e,blockStudioMetadata:t.metadata,notebookTitle:t.metadata.name,blockStudioDirty:!0};case"SET_BLOCK_STUDIO_CATALOG":return{...e,blockStudioCatalog:t.catalog};case"SET_BLOCK_STUDIO_CATALOG_LOADING":return{...e,blockStudioCatalogLoading:t.loading};case"OPEN_BLOCK_IMPORT":return{...e,mainView:"block_studio",sidebarPanel:"block_library",sidebarOpen:!0,blockStudioImportOpen:!0,lineageFullscreen:!1,lineageFocusNodeId:null};case"CLOSE_BLOCK_IMPORT":return{...e,blockStudioImportOpen:!1};case"SET_BLOCK_STUDIO_DBT_STATUS":return{...e,blockStudioDbtStatus:t.status};case"OPEN_SETUP":return{...e,setupOpen:!0};case"CLOSE_SETUP":return{...e,setupOpen:!1};case"OPEN_GLOBAL_AI":return{...e,globalAi:{open:!0,audience:t.audience??e.globalAi.audience,context:t.context??e.globalAi.context,autoRun:t.autoRun?{...t.autoRun,nonce:Date.now()}:e.globalAi.autoRun}};case"CLOSE_GLOBAL_AI":return{...e,globalAi:{...e.globalAi,open:!1}};case"TOGGLE_GLOBAL_AI":return{...e,globalAi:{...e.globalAi,open:!e.globalAi.open,audience:t.audience??e.globalAi.audience,context:t.context??e.globalAi.context}};case"SET_GLOBAL_AI_CONTEXT":return{...e,globalAi:{...e.globalAi,context:t.context,audience:t.audience??e.globalAi.audience}};case"TOGGLE_INSPECTOR":return{...e,inspectorOpen:!e.inspectorOpen};case"SET_INSPECTOR":return{...e,inspectorOpen:t.open,inspectorContext:t.context===void 0?e.inspectorContext:t.context};case"SET_INSPECTOR_CONTEXT":return{...e,inspectorContext:t.context,inspectorOpen:t.context!==null?!0:e.inspectorOpen};case"SET_APPS":return{...e,apps:t.apps};case"SET_APPS_LOADING":return{...e,appsLoading:t.loading};case"OPEN_APP":{const c=e.apps.find(h=>h.id===t.appId)??null,f=t.dashboardId!==void 0?t.dashboardId:((a=c==null?void 0:c.homepage)==null?void 0:a.type)==="dashboard"?c.homepage.id:((d=c==null?void 0:c.dashboards[0])==null?void 0:d.id)??null,p=e.activeAppId===t.appId;return{...e,mainView:"apps",activeAppId:t.appId,activeDashboardId:f,activeAppExperience:t.experience??(p?e.activeAppExperience:"view"),activeAppSection:t.section??(p?e.activeAppSection:"dashboards"),lineageReturnTarget:null}}case"OPEN_DASHBOARD":return{...e,activeDashboardId:t.dashboardId};case"SET_APP_WORKSPACE_STATE":return{...e,activeAppExperience:t.experience??e.activeAppExperience,activeAppSection:t.section??e.activeAppSection};case"SET_ACTIVE_PERSONA":return{...e,activePersona:t.persona};default:return e}}const Ho=ag((e,t)=>({...yg,dispatch:n=>{const r=xg(t(),n);e(r)}})),bg=u.createContext(null);function vg({children:e}){return Pe.useEffect(()=>{const t=n=>{if(n.key!=="dql-theme"||!n.newValue)return;const r=n.newValue;(r==="obsidian"||r==="paper"||r==="white"||r==="midnight"||r==="arctic"||r==="dark"||r==="light")&&Ho.getState().dispatch({type:"SET_THEME",mode:r})};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]),s.jsx(s.Fragment,{children:e})}function xe(){const e=Ho(dg(r=>{const{dispatch:o,...i}=r;return i})),t=Ho(r=>r.dispatch);return u.useContext(bg)??{state:e,dispatch:t}}function tt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function _s(e,t=""){const n={id:tt(),type:e,content:t,status:"idle"};return e==="param"&&(n.content="",n.paramConfig={paramType:"text",label:"Parameter",defaultValue:"",options:[]}),e==="chart"&&(n.chartConfig={chart:"bar"}),e==="filter"&&(n.filterConfig={mode:"keep",groups:[{id:`g_${Math.random().toString(36).slice(2,8)}`,combinator:"and",rules:[]}]}),e==="pivot"&&(n.pivotConfig={rows:[],columns:[],values:[]}),e==="single_value"&&(n.singleValueConfig={aggregation:"count",format:"number"}),e==="table"&&(n.tableConfig={}),e==="chat"&&(n.chatConfig={history:[]}),n}const Sg="modulepreload",kg=function(e){return"/"+e},Mi={},je=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){let l=function(c){return Promise.all(c.map(f=>Promise.resolve(f).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),d=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));o=l(n.map(c=>{if(c=kg(c),c in Mi)return;Mi[c]=!0;const f=c.endsWith(".css"),p=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${p}`))return;const h=document.createElement("link");if(h.rel=f?"stylesheet":Sg,f||(h.as="script"),h.crossOrigin="",h.href=c,d&&h.setAttribute("nonce",d),document.head.appendChild(h),f)return new Promise((g,S)=>{h.addEventListener("load",g),h.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=l,window.dispatchEvent(a),!a.defaultPrevented)throw l}return o.then(l=>{for(const a of l||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})};/**
55
- * @license lucide-react v0.563.0 - ISC
56
- *
57
- * This source code is licensed under the ISC license.
58
- * See the LICENSE file in the root directory of this source tree.
59
- */const $c=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/**
60
- * @license lucide-react v0.563.0 - ISC
61
- *
62
- * This source code is licensed under the ISC license.
63
- * See the LICENSE file in the root directory of this source tree.
64
- */const wg=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
65
- * @license lucide-react v0.563.0 - ISC
66
- *
67
- * This source code is licensed under the ISC license.
68
- * See the LICENSE file in the root directory of this source tree.
69
- */const jg=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());/**
70
- * @license lucide-react v0.563.0 - ISC
71
- *
72
- * This source code is licensed under the ISC license.
73
- * See the LICENSE file in the root directory of this source tree.
74
- */const Ii=e=>{const t=jg(e);return t.charAt(0).toUpperCase()+t.slice(1)};/**
75
- * @license lucide-react v0.563.0 - ISC
76
- *
77
- * This source code is licensed under the ISC license.
78
- * See the LICENSE file in the root directory of this source tree.
79
- */var Cg={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
80
- * @license lucide-react v0.563.0 - ISC
81
- *
82
- * This source code is licensed under the ISC license.
83
- * See the LICENSE file in the root directory of this source tree.
84
- */const Eg=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};/**
85
- * @license lucide-react v0.563.0 - ISC
86
- *
87
- * This source code is licensed under the ISC license.
88
- * See the LICENSE file in the root directory of this source tree.
89
- */const Ag=u.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:l,...a},d)=>u.createElement("svg",{ref:d,...Cg,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:$c("lucide",o),...!i&&!Eg(a)&&{"aria-hidden":"true"},...a},[...l.map(([c,f])=>u.createElement(c,f)),...Array.isArray(i)?i:[i]]));/**
90
- * @license lucide-react v0.563.0 - ISC
91
- *
92
- * This source code is licensed under the ISC license.
93
- * See the LICENSE file in the root directory of this source tree.
94
- */const X=(e,t)=>{const n=u.forwardRef(({className:r,...o},i)=>u.createElement(Ag,{ref:i,iconNode:t,className:$c(`lucide-${wg(Ii(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Ii(e),n};/**
95
- * @license lucide-react v0.563.0 - ISC
96
- *
97
- * This source code is licensed under the ISC license.
98
- * See the LICENSE file in the root directory of this source tree.
99
- */const Tg=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Rg=X("arrow-down",Tg);/**
100
- * @license lucide-react v0.563.0 - ISC
101
- *
102
- * This source code is licensed under the ISC license.
103
- * See the LICENSE file in the root directory of this source tree.
104
- */const _g=[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]],$g=X("arrow-right-left",_g);/**
105
- * @license lucide-react v0.563.0 - ISC
106
- *
107
- * This source code is licensed under the ISC license.
108
- * See the LICENSE file in the root directory of this source tree.
109
- */const Og=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Pg=X("arrow-up",Og);/**
110
- * @license lucide-react v0.563.0 - ISC
111
- *
112
- * This source code is licensed under the ISC license.
113
- * See the LICENSE file in the root directory of this source tree.
114
- */const Dg=[["path",{d:"M10 22V7a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5a1 1 0 0 0-1-1H2",key:"1ah6g2"}],["rect",{x:"14",y:"2",width:"8",height:"8",rx:"1",key:"88lufb"}]],$s=X("blocks",Dg);/**
115
- * @license lucide-react v0.563.0 - ISC
116
- *
117
- * This source code is licensed under the ISC license.
118
- * See the LICENSE file in the root directory of this source tree.
119
- */const Mg=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z",key:"oz39mx"}]],Ig=X("bookmark",Mg);/**
120
- * @license lucide-react v0.563.0 - ISC
121
- *
122
- * This source code is licensed under the ISC license.
123
- * See the LICENSE file in the root directory of this source tree.
124
- */const Lg=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],Ng=X("box",Lg);/**
125
- * @license lucide-react v0.563.0 - ISC
126
- *
127
- * This source code is licensed under the ISC license.
128
- * See the LICENSE file in the root directory of this source tree.
129
- */const Bg=[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]],Go=X("boxes",Bg);/**
130
- * @license lucide-react v0.563.0 - ISC
131
- *
132
- * This source code is licensed under the ISC license.
133
- * See the LICENSE file in the root directory of this source tree.
134
- */const Fg=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],zg=X("briefcase",Fg);/**
135
- * @license lucide-react v0.563.0 - ISC
136
- *
137
- * This source code is licensed under the ISC license.
138
- * See the LICENSE file in the root directory of this source tree.
139
- */const qg=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ug=X("check",qg);/**
140
- * @license lucide-react v0.563.0 - ISC
141
- *
142
- * This source code is licensed under the ISC license.
143
- * See the LICENSE file in the root directory of this source tree.
144
- */const Wg=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Os=X("chevron-down",Wg);/**
145
- * @license lucide-react v0.563.0 - ISC
146
- *
147
- * This source code is licensed under the ISC license.
148
- * See the LICENSE file in the root directory of this source tree.
149
- */const Kg=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],oo=X("chevron-right",Kg);/**
150
- * @license lucide-react v0.563.0 - ISC
151
- *
152
- * This source code is licensed under the ISC license.
153
- * See the LICENSE file in the root directory of this source tree.
154
- */const Vg=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],Hg=X("chevrons-left",Vg);/**
155
- * @license lucide-react v0.563.0 - ISC
156
- *
157
- * This source code is licensed under the ISC license.
158
- * See the LICENSE file in the root directory of this source tree.
159
- */const Gg=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],Jg=X("chevrons-right",Gg);/**
160
- * @license lucide-react v0.563.0 - ISC
161
- *
162
- * This source code is licensed under the ISC license.
163
- * See the LICENSE file in the root directory of this source tree.
164
- */const Qg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],Yg=X("circle-alert",Qg);/**
165
- * @license lucide-react v0.563.0 - ISC
166
- *
167
- * This source code is licensed under the ISC license.
168
- * See the LICENSE file in the root directory of this source tree.
169
- */const Xg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Oc=X("circle-check",Xg);/**
170
- * @license lucide-react v0.563.0 - ISC
171
- *
172
- * This source code is licensed under the ISC license.
173
- * See the LICENSE file in the root directory of this source tree.
174
- */const Zg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],ey=X("circle-question-mark",Zg);/**
175
- * @license lucide-react v0.563.0 - ISC
176
- *
177
- * This source code is licensed under the ISC license.
178
- * See the LICENSE file in the root directory of this source tree.
179
- */const ty=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],ny=X("clock",ty);/**
180
- * @license lucide-react v0.563.0 - ISC
181
- *
182
- * This source code is licensed under the ISC license.
183
- * See the LICENSE file in the root directory of this source tree.
184
- */const ry=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],oy=X("command",ry);/**
185
- * @license lucide-react v0.563.0 - ISC
186
- *
187
- * This source code is licensed under the ISC license.
188
- * See the LICENSE file in the root directory of this source tree.
189
- */const sy=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],tr=X("database",sy);/**
190
- * @license lucide-react v0.563.0 - ISC
191
- *
192
- * This source code is licensed under the ISC license.
193
- * See the LICENSE file in the root directory of this source tree.
194
- */const iy=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Pc=X("download",iy);/**
195
- * @license lucide-react v0.563.0 - ISC
196
- *
197
- * This source code is licensed under the ISC license.
198
- * See the LICENSE file in the root directory of this source tree.
199
- */const ay=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],ly=X("eye-off",ay);/**
200
- * @license lucide-react v0.563.0 - ISC
201
- *
202
- * This source code is licensed under the ISC license.
203
- * See the LICENSE file in the root directory of this source tree.
204
- */const cy=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Dc=X("eye",cy);/**
205
- * @license lucide-react v0.563.0 - ISC
206
- *
207
- * This source code is licensed under the ISC license.
208
- * See the LICENSE file in the root directory of this source tree.
209
- */const dy=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"1oajmo"}],["path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"mpwhp6"}]],uy=X("file-braces",dy);/**
210
- * @license lucide-react v0.563.0 - ISC
211
- *
212
- * This source code is licensed under the ISC license.
213
- * See the LICENSE file in the root directory of this source tree.
214
- */const py=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]],fy=X("file-check",py);/**
215
- * @license lucide-react v0.563.0 - ISC
216
- *
217
- * This source code is licensed under the ISC license.
218
- * See the LICENSE file in the root directory of this source tree.
219
- */const hy=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],my=X("file-pen",hy);/**
220
- * @license lucide-react v0.563.0 - ISC
221
- *
222
- * This source code is licensed under the ISC license.
223
- * See the LICENSE file in the root directory of this source tree.
224
- */const gy=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],Mc=X("file-plus",gy);/**
225
- * @license lucide-react v0.563.0 - ISC
226
- *
227
- * This source code is licensed under the ISC license.
228
- * See the LICENSE file in the root directory of this source tree.
229
- */const yy=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],xy=X("file-question-mark",yy);/**
230
- * @license lucide-react v0.563.0 - ISC
231
- *
232
- * This source code is licensed under the ISC license.
233
- * See the LICENSE file in the root directory of this source tree.
234
- */const by=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],vy=X("file-spreadsheet",by);/**
235
- * @license lucide-react v0.563.0 - ISC
236
- *
237
- * This source code is licensed under the ISC license.
238
- * See the LICENSE file in the root directory of this source tree.
239
- */const Sy=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Ps=X("file-text",Sy);/**
240
- * @license lucide-react v0.563.0 - ISC
241
- *
242
- * This source code is licensed under the ISC license.
243
- * See the LICENSE file in the root directory of this source tree.
244
- */const ky=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m14.5 12.5-5 5",key:"b62r18"}],["path",{d:"m9.5 12.5 5 5",key:"1rk7el"}]],wy=X("file-x",ky);/**
245
- * @license lucide-react v0.563.0 - ISC
246
- *
247
- * This source code is licensed under the ISC license.
248
- * See the LICENSE file in the root directory of this source tree.
249
- */const jy=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8",key:"14sh0y"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z",key:"1970lx"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1",key:"l4dndm"}]],Cy=X("files",jy);/**
250
- * @license lucide-react v0.563.0 - ISC
251
- *
252
- * This source code is licensed under the ISC license.
253
- * See the LICENSE file in the root directory of this source tree.
254
- */const Ey=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],Ic=X("folder-open",Ey);/**
255
- * @license lucide-react v0.563.0 - ISC
256
- *
257
- * This source code is licensed under the ISC license.
258
- * See the LICENSE file in the root directory of this source tree.
259
- */const Ay=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],Bn=X("folder",Ay);/**
260
- * @license lucide-react v0.563.0 - ISC
261
- *
262
- * This source code is licensed under the ISC license.
263
- * See the LICENSE file in the root directory of this source tree.
264
- */const Ty=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],Ry=X("funnel",Ty);/**
265
- * @license lucide-react v0.563.0 - ISC
266
- *
267
- * This source code is licensed under the ISC license.
268
- * See the LICENSE file in the root directory of this source tree.
269
- */const _y=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],$y=X("gauge",_y);/**
270
- * @license lucide-react v0.563.0 - ISC
271
- *
272
- * This source code is licensed under the ISC license.
273
- * See the LICENSE file in the root directory of this source tree.
274
- */const Oy=[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]],Sn=X("git-branch",Oy);/**
275
- * @license lucide-react v0.563.0 - ISC
276
- *
277
- * This source code is licensed under the ISC license.
278
- * See the LICENSE file in the root directory of this source tree.
279
- */const Py=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],Dy=X("git-commit-horizontal",Py);/**
280
- * @license lucide-react v0.563.0 - ISC
281
- *
282
- * This source code is licensed under the ISC license.
283
- * See the LICENSE file in the root directory of this source tree.
284
- */const My=[["circle",{cx:"12",cy:"18",r:"3",key:"1mpf1b"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["path",{d:"M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9",key:"1uq4wg"}],["path",{d:"M12 12v3",key:"158kv8"}]],Iy=X("git-fork",My);/**
285
- * @license lucide-react v0.563.0 - ISC
286
- *
287
- * This source code is licensed under the ISC license.
288
- * See the LICENSE file in the root directory of this source tree.
289
- */const Ly=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Ds=X("layers",Ly);/**
290
- * @license lucide-react v0.563.0 - ISC
291
- *
292
- * This source code is licensed under the ISC license.
293
- * See the LICENSE file in the root directory of this source tree.
294
- */const Ny=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],By=X("layout-dashboard",Ny);/**
295
- * @license lucide-react v0.563.0 - ISC
296
- *
297
- * This source code is licensed under the ISC license.
298
- * See the LICENSE file in the root directory of this source tree.
299
- */const Fy=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Fn=X("loader-circle",Fy);/**
300
- * @license lucide-react v0.563.0 - ISC
301
- *
302
- * This source code is licensed under the ISC license.
303
- * See the LICENSE file in the root directory of this source tree.
304
- */const zy=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],qy=X("message-circle",zy);/**
305
- * @license lucide-react v0.563.0 - ISC
306
- *
307
- * This source code is licensed under the ISC license.
308
- * See the LICENSE file in the root directory of this source tree.
309
- */const Uy=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],Wy=X("monitor",Uy);/**
310
- * @license lucide-react v0.563.0 - ISC
311
- *
312
- * This source code is licensed under the ISC license.
313
- * See the LICENSE file in the root directory of this source tree.
314
- */const Ky=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],Vy=X("network",Ky);/**
315
- * @license lucide-react v0.563.0 - ISC
316
- *
317
- * This source code is licensed under the ISC license.
318
- * See the LICENSE file in the root directory of this source tree.
319
- */const Hy=[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"pqwjuv"}]],Gy=X("notebook-pen",Hy);/**
320
- * @license lucide-react v0.563.0 - ISC
321
- *
322
- * This source code is licensed under the ISC license.
323
- * See the LICENSE file in the root directory of this source tree.
324
- */const Jy=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],Qy=X("package",Jy);/**
325
- * @license lucide-react v0.563.0 - ISC
326
- *
327
- * This source code is licensed under the ISC license.
328
- * See the LICENSE file in the root directory of this source tree.
329
- */const Yy=[["path",{d:"M12 22a1 1 0 0 1 0-20 10 9 0 0 1 10 9 5 5 0 0 1-5 5h-2.25a1.75 1.75 0 0 0-1.4 2.8l.3.4a1.75 1.75 0 0 1-1.4 2.8z",key:"e79jfc"}],["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}]],Xy=X("palette",Yy);/**
330
- * @license lucide-react v0.563.0 - ISC
331
- *
332
- * This source code is licensed under the ISC license.
333
- * See the LICENSE file in the root directory of this source tree.
334
- */const Zy=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],ex=X("panel-left",Zy);/**
335
- * @license lucide-react v0.563.0 - ISC
336
- *
337
- * This source code is licensed under the ISC license.
338
- * See the LICENSE file in the root directory of this source tree.
339
- */const tx=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],nx=X("plug",tx);/**
340
- * @license lucide-react v0.563.0 - ISC
341
- *
342
- * This source code is licensed under the ISC license.
343
- * See the LICENSE file in the root directory of this source tree.
344
- */const rx=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ox=X("plus",rx);/**
345
- * @license lucide-react v0.563.0 - ISC
346
- *
347
- * This source code is licensed under the ISC license.
348
- * See the LICENSE file in the root directory of this source tree.
349
- */const sx=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Ir=X("refresh-cw",sx);/**
350
- * @license lucide-react v0.563.0 - ISC
351
- *
352
- * This source code is licensed under the ISC license.
353
- * See the LICENSE file in the root directory of this source tree.
354
- */const ix=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Li=X("search",ix);/**
355
- * @license lucide-react v0.563.0 - ISC
356
- *
357
- * This source code is licensed under the ISC license.
358
- * See the LICENSE file in the root directory of this source tree.
359
- */const ax=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],lx=X("settings-2",ax);/**
360
- * @license lucide-react v0.563.0 - ISC
361
- *
362
- * This source code is licensed under the ISC license.
363
- * See the LICENSE file in the root directory of this source tree.
364
- */const cx=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],dx=X("settings",cx);/**
365
- * @license lucide-react v0.563.0 - ISC
366
- *
367
- * This source code is licensed under the ISC license.
368
- * See the LICENSE file in the root directory of this source tree.
369
- */const ux=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],px=X("shield-alert",ux);/**
370
- * @license lucide-react v0.563.0 - ISC
371
- *
372
- * This source code is licensed under the ISC license.
373
- * See the LICENSE file in the root directory of this source tree.
374
- */const fx=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],hx=X("shield-check",fx);/**
375
- * @license lucide-react v0.563.0 - ISC
376
- *
377
- * This source code is licensed under the ISC license.
378
- * See the LICENSE file in the root directory of this source tree.
379
- */const mx=[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]],gx=X("sigma",mx);/**
380
- * @license lucide-react v0.563.0 - ISC
381
- *
382
- * This source code is licensed under the ISC license.
383
- * See the LICENSE file in the root directory of this source tree.
384
- */const yx=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Lc=X("sparkles",yx);/**
385
- * @license lucide-react v0.563.0 - ISC
386
- *
387
- * This source code is licensed under the ISC license.
388
- * See the LICENSE file in the root directory of this source tree.
389
- */const xx=[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}]],bx=X("square-dashed",xx);/**
390
- * @license lucide-react v0.563.0 - ISC
391
- *
392
- * This source code is licensed under the ISC license.
393
- * See the LICENSE file in the root directory of this source tree.
394
- */const vx=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],Sx=X("tag",vx);/**
395
- * @license lucide-react v0.563.0 - ISC
396
- *
397
- * This source code is licensed under the ISC license.
398
- * See the LICENSE file in the root directory of this source tree.
399
- */const kx=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],wx=X("terminal",kx);/**
400
- * @license lucide-react v0.563.0 - ISC
401
- *
402
- * This source code is licensed under the ISC license.
403
- * See the LICENSE file in the root directory of this source tree.
404
- */const jx=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Nc=X("trash-2",jx);function Cx(e,t){if(!t)return 1;const n=(e.label+" "+e.group+" "+(e.keywords||"")).toLowerCase(),r=t.toLowerCase();if(n.includes(r))return 100-n.indexOf(r);let o=0;for(const i of n)if(i===r[o]&&o++,o===r.length)return 10;return 0}function Ex(e,t){const n=e.mode??"both";return n==="both"||n===t}function Ax({open:e,onClose:t}){const{state:n,dispatch:r}=xe(),[o,i]=u.useState(""),[l,a]=u.useState(0),d=u.useRef(null);u.useEffect(()=>{e&&(i(""),a(0))},[e]);const c=u.useMemo(()=>{const g=v=>r(v),S=()=>t(),x=v=>()=>{v(),S()},b=[["Files","files",Cy],["Lineage","lineage",Iy],["Git","git",Sn],["Block Library","block_library",$s],["Apps","apps",Vy],["Connections","connection",nx]],k=[{mode:"obsidian",label:"Obsidian"},{mode:"paper",label:"Paper"},{mode:"white",label:"White"}],C=[];C.push({id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",icon:ex,shortcut:"⌘B",mode:"studio",run:x(()=>g({type:"TOGGLE_SIDEBAR"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",icon:n.inspectorOpen?ly:Dc,shortcut:"⌘⇧I",mode:"studio",run:x(()=>g({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",icon:By,shortcut:"⌘D",run:x(()=>g({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:wx,shortcut:"⌘J",mode:"studio",run:x(()=>g({type:"TOGGLE_DEV_PANEL"}))});for(const[v,w,A]of b)C.push({id:`panel.${w}`,label:`Go to ${v}`,group:"Navigate",icon:A,mode:"studio",run:x(()=>{g({type:"SET_SIDEBAR_PANEL",panel:w}),w!=="lineage"&&!n.sidebarOpen&&g({type:"TOGGLE_SIDEBAR"})})});C.push({id:"notebook.new",label:"New notebook…",group:"Create",icon:Mc,mode:"studio",run:x(()=>g({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:bx,mode:"studio",run:x(()=>g({type:"OPEN_NEW_BLOCK_MODAL"}))});const E=n.themeMode==="dark"||n.themeMode==="midnight"?"obsidian":n.themeMode==="light"?"paper":n.themeMode==="arctic"?"white":n.themeMode;for(const v of k)v.mode!==E&&C.push({id:`theme.${v.mode}`,label:`Switch to ${v.label}`,group:"Theme",icon:Xy,keywords:"appearance color",run:x(()=>g({type:"SET_THEME",mode:v.mode}))});return C},[n.sidebarOpen,n.inspectorOpen,n.themeMode,n.dashboardMode,n.appMode,n.sidebarPanel,r,t]),f=u.useMemo(()=>{const S=c.filter(x=>Ex(x,n.appMode)).map(x=>({a:x,s:Cx(x,o)})).filter(x=>x.s>0);return S.sort((x,b)=>b.s-x.s),S.map(x=>x.a)},[c,o,n.appMode]);u.useEffect(()=>{a(0)},[o]),u.useEffect(()=>{var S;const g=(S=d.current)==null?void 0:S.querySelector(`[data-palette-idx="${l}"]`);g==null||g.scrollIntoView({block:"nearest"})},[l]);const p=g=>{var S;g.key==="ArrowDown"?(g.preventDefault(),a(x=>Math.min(f.length-1,x+1))):g.key==="ArrowUp"?(g.preventDefault(),a(x=>Math.max(0,x-1))):g.key==="Enter"&&(g.preventDefault(),(S=f[l])==null||S.run())};let h="";return s.jsx(lh,{open:e,onOpenChange:g=>!g&&t(),children:s.jsxs(ch,{children:[s.jsx(dh,{style:{position:"fixed",inset:0,background:le("surfaceOverlay"),zIndex:zn.overlay}}),s.jsxs(uh,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:le("surfaceRaised"),color:le("textPrimary"),border:`1px solid ${le("borderDefault")}`,borderRadius:Dt.lg,boxShadow:le("shadowLg"),zIndex:zn.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:p,children:[s.jsx(ph,{style:{position:"absolute",left:-9999},children:"Command palette"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:fe[2],padding:`${fe[3]}px ${fe[4]}px`,borderBottom:`1px solid ${le("borderSubtle")}`},children:[s.jsx(oy,{size:14,strokeWidth:1.75,color:le("textMuted")}),s.jsx("input",{autoFocus:!0,value:o,onChange:g=>i(g.target.value),placeholder:"Type a command…",style:{flex:1,border:"none",outline:"none",background:"transparent",color:le("textPrimary"),fontSize:Be.md}})]}),s.jsxs("div",{ref:d,style:{maxHeight:360,overflowY:"auto",padding:`${fe[1]}px 0`},children:[f.length===0&&s.jsx("div",{style:{padding:fe[4],fontSize:Be.sm,color:le("textMuted"),textAlign:"center"},children:"No matching commands"}),f.map((g,S)=>{const x=g.group!==h;h=g.group;const b=S===l,k=g.icon;return s.jsxs(Pe.Fragment,{children:[x&&s.jsx("div",{style:{padding:`${fe[2]}px ${fe[4]}px ${fe[1]}px`},children:s.jsx(Rc,{tone:"neutral",children:g.group})}),s.jsxs("div",{"data-palette-idx":S,role:"option","aria-selected":b,onMouseEnter:()=>a(S),onMouseDown:C=>{C.preventDefault(),g.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:fe[3],padding:`${fe[2]}px ${fe[4]}px`,fontSize:Be.sm,cursor:"pointer",background:b?le("surfaceHover"):"transparent",color:le("textPrimary")},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:fe[2],minWidth:0,flex:1},children:[k&&s.jsx(k,{size:14,strokeWidth:1.75}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.label})]}),g.shortcut&&s.jsx(rg,{shortcut:g.shortcut})]})]},g.id)})]})]})]})})}function Bc(e){const t=Lt(e);if(!t)return;const n=_x(t.kind),r=Tx(t.source);if(!n||!r)return;const o=zx(t.limit);return{kind:n,source:r,name:xt(t.name),sourcePath:xt(t.sourcePath),metrics:Jo(t.metrics),dimensions:Jo(t.dimensions),filters:$x(t.filters),timeDimension:Ox(t.timeDimension),orderBy:Px(t.orderBy),parameters:Dx(t.parameters),parameterValues:Nx(t.parameterValues),persistence:Bx(t.persistence),trustState:Fx(t.trustState),compiledSql:xt(t.compiledSql),executionReceipt:Rx(t.executionReceipt),...o===void 0?{}:{limit:o}}}function Tx(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Rx(e){const t=Lt(e);if(!t)return;const n=gr(t.sourceFingerprint),r=gr(t.compiledSqlFingerprint),o=gr(t.parameterFingerprint),i=gr(t.resultFingerprint);return n&&r&&o&&i?{sourceFingerprint:n,compiledSqlFingerprint:r,parameterFingerprint:o,resultFingerprint:i}:void 0}function gr(e){return typeof e=="string"&&/^[a-f0-9]{64}$/i.test(e.trim())?e.trim().toLowerCase():void 0}function _x(e){return e==="certified_block"||e==="semantic_block"||e==="sql_block"?e:void 0}function $x(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Lt(n);if(!r)return[];const o=xt(r.dimension),i=xt(r.operator);return!o||!i?[]:[{dimension:o,operator:i,values:Jo(r.values)??[]}]});return t.length?t:void 0}function Ox(e){const t=Lt(e);if(!t)return;const n=xt(t.name),r=xt(t.granularity);return n&&r?{name:n,granularity:r}:void 0}function Px(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Lt(n);if(!r)return[];const o=xt(r.name),i=r.direction==="asc"||r.direction==="desc"?r.direction:void 0;return o&&i?[{name:o,direction:i}]:[]});return t.length?t:void 0}function Dx(e){if(!Array.isArray(e))return;const t=new Set,n=e.flatMap(r=>{const o=Lt(r),i=xt(o==null?void 0:o.name),l=Mx(o==null?void 0:o.type),a=Ix(o==null?void 0:o.policy);if(!o||!i||!l||!a||t.has(i))return[];t.add(i);const d=Lx(o.binding);return[{name:i,type:l,required:o.required===!0,...o.default===void 0?{}:{default:o.default},policy:a,...d?{binding:d}:{}}]});return n.length?n:void 0}function Mx(e){return e==="string"||e==="number"||e==="boolean"||e==="date"||e==="string[]"||e==="number[]"||e==="date[]"?e:void 0}function Ix(e){return e==="dynamic"||e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:void 0}function Lx(e){const t=Lt(e);if(!t)return;if(t.kind==="sql_value")return{kind:"sql_value"};if(t.kind==="limit")return{kind:"limit"};const n=xt(t.field);if(t.kind==="semantic_filter"&&n&&(t.operator==="equals"||t.operator==="in"||t.operator==="gte"||t.operator==="lte"))return{kind:"semantic_filter",field:n,operator:t.operator}}function Nx(e){const t=Lt(e);if(!t)return;const n=Object.entries(t).filter(([r])=>r.trim().length>0);return n.length?Object.fromEntries(n):void 0}function Bx(e){return e==="transient"||e==="saved"?e:void 0}function Fx(e){return e==="certified"||e==="governed"||e==="review_required"?e:void 0}function Lt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function xt(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Jo(e){if(!Array.isArray(e))return;const t=e.filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim());return t.length?t:void 0}function zx(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}const Fc="dql_token",Ni="dql.server-token.v1";function qx(e){var r;return((r=new URLSearchParams(e.replace(/^#/,"")).get(Fc))==null?void 0:r.trim())||void 0}function Ux(e){const t=new URLSearchParams(e.replace(/^#/,""));t.delete(Fc);const n=t.toString();return n?`#${n}`:""}function Wx(){var e;if(!(typeof window>"u"))try{const t=qx(window.location.hash);if(t){window.sessionStorage.setItem(Ni,t);const n=Ux(window.location.hash);return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${n}`),t}return((e=window.sessionStorage.getItem(Ni))==null?void 0:e.trim())||void 0}catch{return}}const Bi=Wx();function $n(e){const t=new Headers(e);return Bi&&t.set("Authorization",`Bearer ${Bi}`),t}const Kx={totals:{modelsScanned:0,businessModels:0,plumbingExcluded:0,metricsFound:0},willGenerate:0,willSkip:0,domains:[],config:{businessLayers:[],excludeLayers:[],maxPerDomain:0,minScore:0,aiEnrichment:"auto"}};function yr(){return{total:0,tracked:0,changed:0,untracked:0,ignored:0,paths:[]}}const On=window.location.origin;class bt extends Error{constructor(n){super(n.message);Ce(this,"status");Ce(this,"code");Ce(this,"recoverable");Ce(this,"details");Ce(this,"nextActions");Ce(this,"requestId");Ce(this,"snapshotId");this.name="DqlApiError",this.status=n.status,this.code=n.code,this.recoverable=n.recoverable,this.details=n.details,this.nextActions=n.nextActions,this.requestId=n.requestId,this.snapshotId=n.snapshotId}}function Qo(e,t){const n=t.trim()||e.statusText||`HTTP ${e.status}`;if(!t.trim())return new bt({message:n,status:e.status});try{const r=JSON.parse(t),o=typeof(r==null?void 0:r.message)=="string"&&r.message.trim()?r.message:typeof(r==null?void 0:r.error)=="string"&&r.error.trim()?r.error:n;return new bt({message:o,status:e.status,code:typeof(r==null?void 0:r.code)=="string"?r.code:void 0,recoverable:typeof(r==null?void 0:r.recoverable)=="boolean"?r.recoverable:void 0,details:r==null?void 0:r.details,nextActions:Array.isArray(r==null?void 0:r.nextActions)?r.nextActions.filter(i=>typeof i=="string"):void 0,requestId:typeof(r==null?void 0:r.requestId)=="string"?r.requestId:void 0,snapshotId:typeof(r==null?void 0:r.snapshotId)=="string"?r.snapshotId:void 0})}catch{return new bt({message:n,status:e.status})}}async function j(e,t){var r;let n;try{const o=$n(t==null?void 0:t.headers);o.has("Content-Type")||o.set("Content-Type","application/json"),n=await fetch(`${On}${e}`,{...t,headers:o})}catch(o){if((r=t==null?void 0:t.signal)!=null&&r.aborted)throw o;const i=o instanceof Error&&o.message?` ${o.message}`:"";throw new Error(`Unable to reach the local DQL notebook server. Check that it is still running, then retry.${i}`)}if(!n.ok){const o=await n.text().catch(()=>"");throw Qo(n,o)}if(n.status!==204)return n.json()}async function Vx(e,t){if(!e.body)throw new Error("Agent run stream is not available in this browser.");const n=e.body.getReader(),r=new TextDecoder;let o="",i;const l=a=>{const d=a.split(/\r?\n/);let c="message";const f=[];for(const h of d)h.startsWith("event:")&&(c=h.slice(6).trim()),h.startsWith("data:")&&f.push(h.slice(5).trimStart());if(f.length===0)return;const p=JSON.parse(f.join(`
405
- `));if(c==="agent-run-event")t({kind:"event",event:p});else if(c==="agent-run-answer-delta"){const h=typeof(p==null?void 0:p.delta)=="string"?p.delta:"";h&&t({kind:"answer-delta",delta:h})}else if(c==="agent-run-complete")i=p,t({kind:"complete",run:i});else if(c==="agent-run-error")throw new Error(typeof(p==null?void 0:p.error)=="string"?p.error:"Agent run failed.")};for(;;){const{value:a,done:d}=await n.read();if(a){o+=r.decode(a,{stream:!d});let c=o.search(/\r?\n\r?\n/);for(;c>=0;){const f=o.slice(0,c);o=o.slice(o[c]==="\r"?c+4:c+2),l(f),c=o.search(/\r?\n\r?\n/)}}if(d)break}if(o.trim()&&l(o),!i)throw new Error("Agent run stream ended before completion.");return i}function cn(e){var r;const t=Array.isArray(e==null?void 0:e.columns)?e.columns.map(o=>typeof o=="string"?o:typeof(o==null?void 0:o.name)=="string"?o.name:String(o)):[],n=e!=null&&e.semanticRefs&&typeof e.semanticRefs=="object"?{metrics:Array.isArray(e.semanticRefs.metrics)?e.semanticRefs.metrics.map(String):[],dimensions:Array.isArray(e.semanticRefs.dimensions)?e.semanticRefs.dimensions.map(String):[]}:void 0;return{columns:t,rows:Array.isArray(e==null?void 0:e.rows)?e.rows:[],rowCount:(e==null?void 0:e.rowCount)??((r=e==null?void 0:e.rows)==null?void 0:r.length)??0,executionTime:(e==null?void 0:e.executionTime)??(e==null?void 0:e.executionTimeMs)??0,...n?{semanticRefs:n}:{}}}function St(e){var n;const t=e!=null&&e.resultPreview&&typeof e.resultPreview=="object"?cn(e.resultPreview):void 0;return{...e,domain:typeof(e==null?void 0:e.domain)=="string"&&e.domain.trim()?e.domain:void 0,owner:typeof(e==null?void 0:e.owner)=="string"&&e.owner.trim()?e.owner:void 0,warnings:Array.isArray(e==null?void 0:e.warnings)?e.warnings:[],dqlCandidateIds:Array.isArray(e==null?void 0:e.dqlCandidateIds)?e.dqlCandidateIds:[],dqlArtifact:Bc(e==null?void 0:e.dqlArtifact),dqlPromotionAction:nb((e==null?void 0:e.dqlPromotionAction)??((n=e==null?void 0:e.dqlPromotion)==null?void 0:n.recommendedAction)),dqlPromotion:zc(e==null?void 0:e.dqlPromotion),researchPlan:Hx(e==null?void 0:e.researchPlan),reviewChecklist:eb(e==null?void 0:e.reviewChecklist,e),...t?{resultPreview:t}:{resultPreview:void 0}}}function Hx(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n=t.evidence&&typeof t.evidence=="object"&&!Array.isArray(t.evidence)?t.evidence:{},r=t.preview&&typeof t.preview=="object"&&!Array.isArray(t.preview)?t.preview:{},o=t.promotion&&typeof t.promotion=="object"&&!Array.isArray(t.promotion)?t.promotion:{},i=t.sqlState==="generated"||t.sqlState==="reviewed"?t.sqlState:"missing",l=r.status==="ready"||r.status==="error"?r.status:"not_run",a=o.path==="review_context"||o.path==="run_preview"||o.path==="reuse_existing"||o.path==="create_dql_draft"||o.path==="open_certification"||o.path==="complete_review"?o.path:"needs_sql",d=typeof r.rowCount=="number"&&Number.isFinite(r.rowCount)?r.rowCount:void 0;return{sqlState:i,grain:typeof t.grain=="string"&&t.grain.trim()?t.grain:void 0,parameterPolicy:Gx(t.parameterPolicy),allowedFilters:Array.isArray(t.allowedFilters)?t.allowedFilters.map(String).filter(Boolean):[],evidence:{trustLabel:typeof n.trustLabel=="string"&&n.trustLabel.trim()?n.trustLabel:void 0,contextPackId:typeof n.contextPackId=="string"&&n.contextPackId.trim()?n.contextPackId:void 0,evidenceCount:me(n.evidenceCount),relationCount:me(n.relationCount),missingContextCount:me(n.missingContextCount)},preview:{status:l,...d===void 0?{}:{rowCount:d}},promotion:{path:a,duplicateDecision:typeof o.duplicateDecision=="string"&&o.duplicateDecision.trim()?o.duplicateDecision:void 0},reviewFocus:Array.isArray(t.reviewFocus)?t.reviewFocus.map(String).filter(Boolean):[],generatedAt:typeof t.generatedAt=="string"&&t.generatedAt.trim()?t.generatedAt:new Date(0).toISOString()}}function Gx(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];const n=t,r=typeof n.name=="string"&&n.name.trim()?n.name:void 0,o=typeof n.policy=="string"&&n.policy.trim()?n.policy:void 0;return r&&o?[{name:r,policy:o}]:[]}):[]}function me(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function sn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Jx(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{totalReviewCount:me(t.totalReviewCount),openReviewCount:me(t.openReviewCount),terminalReviewCount:me(t.terminalReviewCount),draftCreatedCount:me(t.draftCreatedCount),certifiedCount:me(t.certifiedCount),completedCount:me(t.completedCount),rejectedCount:me(t.rejectedCount),draftCreationRate:sn(t.draftCreationRate),certifyConversionRate:sn(t.certifyConversionRate),medianOpenReviewAgeMs:sn(t.medianOpenReviewAgeMs),medianTimeToDraftMs:sn(t.medianTimeToDraftMs),medianTimeToCertificationMs:sn(t.medianTimeToCertificationMs),medianTimeToTerminalMs:sn(t.medianTimeToTerminalMs)}}function Qx(e){const t=e&&typeof e=="object"?e:{},n=t.counts&&typeof t.counts=="object"?t.counts:{},r=t.health&&typeof t.health=="object"?t.health:{},o=t.search&&typeof t.search=="object"?t.search:{},i=t.updatedAt&&typeof t.updatedAt=="object"?t.updatedAt:{},l=t.limits&&typeof t.limits=="object"?t.limits:{};return{counts:{totalRuns:me(n.totalRuns),activeRuns:me(n.activeRuns),closedRuns:me(n.closedRuns),notebooks:me(n.notebooks),domains:me(n.domains),owners:me(n.owners),sourceLinkedRuns:me(n.sourceLinkedRuns)},health:{staleOpenRuns:me(r.staleOpenRuns),expiredOpenRuns:me(r.expiredOpenRuns),staleThresholdDays:me(r.staleThresholdDays)||7,expiredThresholdDays:me(r.expiredThresholdDays)||30,oldestOpenUpdatedAt:typeof r.oldestOpenUpdatedAt=="string"&&r.oldestOpenUpdatedAt.trim()?r.oldestOpenUpdatedAt:void 0,newestOpenUpdatedAt:typeof r.newestOpenUpdatedAt=="string"&&r.newestOpenUpdatedAt.trim()?r.newestOpenUpdatedAt:void 0},search:{indexed:o.indexed===!0,indexRows:me(o.indexRows),indexVersion:typeof o.indexVersion=="string"&&o.indexVersion.trim()?o.indexVersion:void 0,stale:o.stale===!0},updatedAt:{oldest:typeof i.oldest=="string"&&i.oldest.trim()?i.oldest:void 0,newest:typeof i.newest=="string"&&i.newest.trim()?i.newest:void 0},limits:{pageSize:me(l.pageSize)||25,maxPageSize:me(l.maxPageSize)||500,sourceCoverageLimit:me(l.sourceCoverageLimit)||1e4,seedCellLimit:me(l.seedCellLimit)||1e3},warnings:Array.isArray(t.warnings)?t.warnings.filter(a=>typeof a=="string"):[]}}function Yx(e){return e==="diagnose_change"||e==="driver_breakdown"||e==="segment_compare"||e==="entity_drilldown"||e==="anomaly_investigation"||e==="trust_gap_review"?e:"ad_hoc_analysis"}function Xx(e){const t=typeof e=="string"?e:"";return(t.split(/[\\/]/).pop()??t).replace(/\.dqlnb$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()||"Untitled notebook"}function Zx(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=r=>typeof t[r]=="number"&&Number.isFinite(t[r])?t[r]:0;return{fix_blockers:n("fix_blockers"),review_sql:n("review_sql"),review_context:n("review_context"),run_preview:n("run_preview"),reuse_existing:n("reuse_existing"),create_dql_draft:n("create_dql_draft"),open_certification:n("open_certification"),complete_review:n("complete_review"),continue_review:n("continue_review")}}function xr(e){return e==="fix_blockers"||e==="review_sql"||e==="review_context"||e==="run_preview"||e==="reuse_existing"||e==="create_dql_draft"||e==="open_certification"||e==="complete_review"||e==="continue_review"?e:void 0}function eb(e,t){var c,f;if(e&&typeof e=="object"&&Array.isArray(e.items))return{readyForDqlDraft:e.readyForDqlDraft===!0,readyForCertificationReview:e.readyForCertificationReview===!0,blockers:Array.isArray(e.blockers)?e.blockers.filter(p=>typeof p=="string"):[],warnings:Array.isArray(e.warnings)?e.warnings.filter(p=>typeof p=="string"):[],items:e.items.map(p=>({id:typeof p.id=="string"?p.id:"item",label:typeof p.label=="string"?p.label:"Review item",status:p.status==="passed"||p.status==="pending"||p.status==="warning"||p.status==="blocked"?p.status:"pending",detail:typeof p.detail=="string"?p.detail:""}))};const n=!!t.reviewedSql,r=n||!!t.generatedSql,o=((c=t.resultPreview)==null?void 0:c.rowCount)??((f=t.resultPreview)==null?void 0:f.rows.length)??0,i=!!(t.resultPreview&&(t.resultPreview.columns.length>0||o>0)),l=!!t.draftBlockPath,a=!!(t.contextPackId||t.evidence),d=t.dqlPromotionAction==="reuse_existing";return{readyForDqlDraft:!!(!d&&t.question&&n&&a&&t.status!=="error"),readyForCertificationReview:!!(!d&&t.question&&n&&a&&i&&l),blockers:t.status==="error"?[t.error??"Preview failed."]:[],warnings:i||d?[]:["Run a bounded preview before certification review."],items:[{id:"question",label:"Question",status:t.question?"passed":"blocked",detail:t.question?"Business question is captured.":"Add a business question."},{id:"sql",label:"Reviewed SQL",status:r||d?"passed":"blocked",detail:d&&!r?"Existing DQL should be reused; no new SQL is required.":r?"SQL is available.":"Add SQL before promotion."},{id:"evidence",label:"Evidence",status:a||d?"passed":"warning",detail:a?"Context evidence is saved.":d?"Reuse evidence is captured in the recommendation.":"Preview and save metadata context."},{id:"preview",label:"Preview",status:i||d?"passed":"pending",detail:i?"Preview result is available.":d?"Certified block reuse does not require a new raw SQL preview.":"Run a bounded preview."},{id:"dql_draft",label:"DQL draft",status:l||d?"passed":"pending",detail:l?`Draft saved at ${t.draftBlockPath}.`:d?"No new DQL draft is required.":"Create a DQL draft after review."}]}}function tb(e){var r,o,i,l;const t=e&&typeof e=="object"?e:{},n=t.routeDecision&&typeof t.routeDecision=="object"?{route:typeof t.routeDecision.route=="string"?t.routeDecision.route:void 0,intent:typeof t.routeDecision.intent=="string"?t.routeDecision.intent:void 0,reason:typeof t.routeDecision.reason=="string"?t.routeDecision.reason:void 0}:void 0;return{contextPackId:typeof t.contextPackId=="string"?t.contextPackId:"",trustLabel:typeof t.trustLabel=="string"?t.trustLabel:void 0,routeDecision:n,evidence:Array.isArray(t.evidence)?t.evidence.map(a=>({objectKey:typeof a.objectKey=="string"?a.objectKey:void 0,objectType:typeof a.objectType=="string"?a.objectType:void 0,name:typeof a.name=="string"?a.name:"Evidence",role:typeof a.role=="string"?a.role:void 0,reason:typeof a.reason=="string"?a.reason:""})):[],summaries:Array.isArray(t.summaries)?t.summaries.map(a=>({title:typeof a.title=="string"?a.title:"Context",detail:typeof a.detail=="string"?a.detail:"",objectType:typeof a.objectType=="string"?a.objectType:void 0,reason:typeof a.reason=="string"?a.reason:void 0})):[],relations:Array.isArray(t.relations)?t.relations.map(a=>({relation:typeof a.relation=="string"?a.relation:"",name:typeof a.name=="string"?a.name:"Relation",source:typeof a.source=="string"?a.source:"",columns:Array.isArray(a.columns)?a.columns.map(String):[]})).filter(a=>a.relation||a.name):[],missingContext:Array.isArray(t.missingContext)?t.missingContext.map(a=>({kind:typeof a.kind=="string"?a.kind:"metadata",message:typeof a.message=="string"?a.message:"",severity:typeof a.severity=="string"?a.severity:"warning"})).filter(a=>a.message):[],warnings:Array.isArray(t.warnings)?t.warnings.filter(a=>typeof a=="string"):[],topRejected:Array.isArray(t.topRejected)?t.topRejected.map(a=>({name:typeof a.name=="string"?a.name:"Rejected context",objectType:typeof a.objectType=="string"?a.objectType:void 0,reason:typeof a.reason=="string"?a.reason:"",score:typeof a.score=="number"&&Number.isFinite(a.score)?a.score:void 0})).filter(a=>a.reason):[],counts:{objects:typeof((r=t.counts)==null?void 0:r.objects)=="number"?t.counts.objects:0,evidence:typeof((o=t.counts)==null?void 0:o.evidence)=="number"?t.counts.evidence:0,relations:typeof((i=t.counts)==null?void 0:i.relations)=="number"?t.counts.relations:0,warnings:typeof((l=t.counts)==null?void 0:l.warnings)=="number"?t.counts.warnings:0}}}function nb(e){return e==="reuse_existing"||e==="extend_existing"||e==="create_replacement"||e==="create_new"||e==="review_required"?e:void 0}function zc(e){if(!(!e||typeof e!="object"))return{importId:typeof e.importId=="string"?e.importId:"",candidateIds:Array.isArray(e.candidateIds)?e.candidateIds.filter(t=>typeof t=="string"):[],draftBlockPath:typeof e.draftBlockPath=="string"?e.draftBlockPath:void 0,recommendedAction:typeof e.recommendedAction=="string"?e.recommendedAction:void 0,similarityMatches:Array.isArray(e.similarityMatches)?e.similarityMatches:[],candidates:Array.isArray(e.candidates)?e.candidates.map(t=>({...t,similarityMatches:Array.isArray(t.similarityMatches)?t.similarityMatches:[],parameterPolicy:Array.isArray(t.parameterPolicy)?t.parameterPolicy:[],allowedFilters:Array.isArray(t.allowedFilters)?t.allowedFilters:[],warnings:Array.isArray(t.warnings)?t.warnings:[]})):[],createdAt:typeof e.createdAt=="string"?e.createdAt:""}}const N={async getDbtFirstModeling(){return j("/api/modeling/dbt-first")},async getDbtModelingNode(e){return j(`/api/modeling/dbt-first/nodes/${encodeURIComponent(e)}`)},async getDbtModelingNodes(e){return j("/api/modeling/dbt-first/nodes/batch",{method:"POST",body:JSON.stringify({uniqueIds:e})})},async getDbtModelInventory(e={}){const t=new URLSearchParams;return e.q&&t.set("q",e.q),e.domain&&t.set("domain",e.domain),e.cursor!==void 0&&t.set("cursor",String(e.cursor)),e.limit!==void 0&&t.set("limit",String(e.limit)),j(`/api/modeling/dbt-first/inventory?${t.toString()}`)},async getDomainWorkspaces(){return j("/api/domain-workspaces")},async getRelatedDomainProducts(e){return j(`/api/domain-workspaces/${encodeURIComponent(e)}/related-products`)},async getAllRelatedDomainProducts(){return j("/api/domain-workspaces/related-products")},async getDomainKnowledge(e){return j(`/api/domain-workspaces/${encodeURIComponent(e)}/knowledge`)},async previewModelingChange(e,t){return j("/api/modeling/dbt-first/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyModelingChange(e,t,n){return j("/api/modeling/dbt-first/apply",{method:"POST",body:JSON.stringify({change:e,fingerprint:t,expectedSnapshotId:n})})},async validateModelingRelationship(e,t){return(await j("/api/modeling/dbt-first/relationships/validate",{method:"POST",body:JSON.stringify({relationship:e,expectedSnapshotId:t})})).evidence},async previewDbtSourcePatch(e,t){return j("/api/modeling/dbt-first/dbt-source/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyDbtSourcePatch(e,t,n){return j("/api/modeling/dbt-first/dbt-source/apply",{method:"POST",body:JSON.stringify({change:e,expectedFingerprint:t,expectedSnapshotId:n})})},async getSettingsEnvStatus(){try{return await j("/api/settings/env-status")}catch{return{groups:[]}}},async getProposeReadiness(e){try{return await j("/api/propose",{method:"POST",body:JSON.stringify(e??{})})}catch{return{ready:!1,reason:"Unable to reach the propose engine. Is the local DQL server running?",summary:{modelsScanned:0,businessModels:0,plumbingExcluded:0,metricsFound:0,proposalsRanked:0,draftsExisting:0,readyForReview:0,blockingTotal:0,warningTotal:0},plan:Kx,proposals:[]}}},async generateProposeDrafts(e){try{return await j("/api/propose/generate",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ready:!1,reason:t instanceof Error?t.message:"Unable to reach the propose engine.",draftsWritten:0,draftsSkipped:0,proposals:[]}}},async proposePreview(e){return j(`/api/propose/preview?slug=${encodeURIComponent(e)}`)},async aiBuild(e){return j("/api/ai/build",{method:"POST",body:JSON.stringify(e)})},async createAgentRun(e){return(await j("/api/agent-runs",{method:"POST",body:JSON.stringify(e)})).run},async createAgentRunStream(e,t,n){let r;try{r=await fetch(`${On}/api/agent-runs?stream=1`,{method:"POST",headers:$n({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:n})}catch(o){if(n!=null&&n.aborted)throw o;const i=o instanceof Error&&o.message?` ${o.message}`:"";throw new Error(`Unable to reach the local DQL notebook server. Check that it is still running, then retry.${i}`)}if(!r.ok){const o=await r.text().catch(()=>"");throw Qo(r,o)}return Vx(r,t)},async listAgentRuns(e){const t=new URLSearchParams;typeof(e==null?void 0:e.limit)=="number"&&Number.isFinite(e.limit)&&t.set("limit",String(e.limit));const n=t.toString()?`?${t.toString()}`:"";return j(`/api/agent-runs${n}`)},async getAgentRun(e){const t=await this.getAgentRunState(e);if(t.lifecycleState!=="terminal")throw new Error(`Agent run ${e} is still ${t.lifecycleState}.`);return t.run},async getAgentRunState(e){return j(`/api/agent-runs/${encodeURIComponent(e)}`)},async deriveAnalyticalRepair(e,t){return j(`/api/agent-runs/${encodeURIComponent(e)}/analytical-repair`,{method:"POST",body:JSON.stringify({repair:t})})},async cancelAgentRun(e){return j(`/api/agent-runs/${encodeURIComponent(e)}/cancel`,{method:"POST"})},async listAgentThreads(e){const t=new URLSearchParams;typeof(e==null?void 0:e.limit)=="number"&&Number.isFinite(e.limit)&&t.set("limit",String(e.limit)),e!=null&&e.archived&&t.set("archived","1");const n=t.toString()?`?${t.toString()}`:"";return j(`/api/agent/threads${n}`)},async createAgentThread(e={}){return(await j("/api/agent/threads",{method:"POST",body:JSON.stringify(e)})).thread},async getAgentThread(e){return j(`/api/agent/threads/${encodeURIComponent(e)}`)},async archiveAgentThread(e){return j(`/api/agent/threads/${encodeURIComponent(e)}/archive`,{method:"POST"})},async deleteAgentThread(e){return j(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestCertification(e){return j("/api/agent-runs/request-certification",{method:"POST",body:JSON.stringify(e)})},async getIdentity(){return j("/api/identity")},async getProviderSettings(){try{return await j("/api/settings/providers")}catch{return{providers:[]}}},async getProviderCliStatus(){try{return await j("/api/settings/providers/cli-status")}catch{return{status:{}}}},async saveProviderSettings(e){return j("/api/settings/providers",{method:"POST",body:JSON.stringify(e)})},async startOAuth(e){return j(`/api/auth/${e}/start`,{method:"POST"})},async getOAuthStatus(e){return j(`/api/auth/${e}/status`)},async signOutOAuth(e){return j(`/api/auth/${e}/signout`,{method:"POST"})},async testProviderSettings(e,t){try{return await j("/api/settings/providers/test",{method:"POST",body:JSON.stringify({id:e,...t})})}catch(n){return{ok:!1,message:n instanceof Error?n.message:String(n)}}},async getRemoteMcpSettings(){try{return await j("/api/settings/mcp")}catch{return{settings:{path:"",entries:[],warnings:[]}}}},async saveRemoteMcpSettings(e){return j("/api/settings/mcp",{method:"POST",body:JSON.stringify({entries:e})})},async recordAgentCorrection(e){return j("/api/agent/learnings/correction",{method:"POST",body:JSON.stringify(e)})},async listAgentHints(e){const t=e?`?status=${encodeURIComponent(e)}`:"";return j(`/api/agent/hints${t}`)},async reviewAgentHint(e,t,n){return j(`/api/agent/hints/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({decision:t,...n?{note:n}:{}})})},async updateAgentHint(e,t){return j(`/api/agent/hints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async transitionAgentHint(e,t){return j(`/api/agent/hints/${encodeURIComponent(e)}/lifecycle`,{method:"POST",body:JSON.stringify(t)})},async listAgentMemory(e){const t=e?`?scope=${encodeURIComponent(e)}`:"";try{return await j(`/api/agent/memory${t}`)}catch{return{memories:[]}}},async saveAgentMemory(e){return j("/api/agent/memory",{method:"POST",body:JSON.stringify(e)})},async deleteAgentMemory(e){return j(`/api/agent/memory?id=${encodeURIComponent(e)}`,{method:"DELETE"})},async ensureAgentMemoryFiles(){return j("/api/agent/memory/default-files",{method:"POST"})},async listNotebooks(){try{return await j("/api/notebooks")}catch{return[]}},async readNotebook(e){return j(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async deleteNotebook(e){return j(`/api/notebooks?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async createNotebook(e,t,n={}){return j("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t,...n})})},async createBlock(e,t){return j("/api/blocks",{method:"POST",body:JSON.stringify({name:e,...t})})},async getBlockLibrary(){try{return await j("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await j("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return j("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await j(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return j("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(e={}){const t=new URLSearchParams;e.includeSemantic===!1&&t.set("includeSemantic","false");const n=t.toString();return j(`/api/block-studio/catalog${n?`?${n}`:""}`)},async getBlockStudioDbtStatus(){return j("/api/block-studio/dbt-status")},async openBlockStudio(e){return j(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return j(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t){return j("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t})})},async runBlockStudio(e,t,n){return j("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t,parameters:n})})},async getCertifiedBlockParameters(e){return j(`/api/blocks/parameters?name=${encodeURIComponent(e)}`)},async invokeCertifiedBlock(e,t,n){var o,i,l,a,d,c;const r=await j("/api/blocks/invoke",{method:"POST",body:JSON.stringify({blockName:e,parameters:t,question:n})});return{parameters:Array.isArray(r==null?void 0:r.parameters)?r.parameters:[],result:{...cn(r==null?void 0:r.result),...typeof((o=r==null?void 0:r.result)==null?void 0:o.sql)=="string"?{sql:r.result.sql}:{},...typeof((i=r==null?void 0:r.result)==null?void 0:i.blockName)=="string"?{blockName:r.result.blockName}:{},...typeof((l=r==null?void 0:r.result)==null?void 0:l.blockPath)=="string"?{blockPath:r.result.blockPath}:{},...(a=r==null?void 0:r.result)!=null&&a.chartConfig?{chartConfig:r.result.chartConfig}:{},...Array.isArray((d=r==null?void 0:r.result)==null?void 0:d.parameters)?{parameters:r.result.parameters}:{},...typeof((c=r==null?void 0:r.result)==null?void 0:c.auditId)=="string"?{auditId:r.result.auditId}:{}}}},async invokeDqlArtifact(e,t,n,r){var l,a,d,c,f,p;const o=await j("/api/dql/artifacts/execute",{method:"POST",body:JSON.stringify({artifact:e,parameters:t,question:n,blockName:r})}),i=Bc(o==null?void 0:o.artifact);if(!i)throw new Error("DQL artifact execution returned an invalid artifact contract.");return{artifact:i,parameters:i.parameters??[],result:{...cn(o==null?void 0:o.result),...typeof((l=o==null?void 0:o.result)==null?void 0:l.sql)=="string"?{sql:o.result.sql}:{},...typeof((a=o==null?void 0:o.result)==null?void 0:a.blockName)=="string"?{blockName:o.result.blockName}:{},...typeof((d=o==null?void 0:o.result)==null?void 0:d.blockPath)=="string"?{blockPath:o.result.blockPath}:{},...(c=o==null?void 0:o.result)!=null&&c.chartConfig?{chartConfig:o.result.chartConfig}:{},...Array.isArray((f=o==null?void 0:o.result)==null?void 0:f.parameters)?{parameters:o.result.parameters}:{},...typeof((p=o==null?void 0:o.result)==null?void 0:p.auditId)=="string"?{auditId:o.result.auditId}:{}}}},async composeSemanticBlock(e){return j("/api/block-studio/compose-semantic",{method:"POST",body:JSON.stringify({question:e})})},async saveBlockStudio(e){return j("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAgentBlockDraft(e){return j("/api/block-studio/agent-drafts",{method:"POST",body:JSON.stringify(e)})},async deleteBlockStudio(e){return j(`/api/block-studio/block?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async previewBlockStudioImport(e){return j("/api/block-studio/import/preview",{method:"POST",body:JSON.stringify(e)})},async listBlockStudioImports(){return j("/api/block-studio/imports")},async createBlockStudioImport(e){return j("/api/block-studio/imports",{method:"POST",body:JSON.stringify(e)})},async createDqlGenerationSession(e){return j("/api/block-studio/ai-imports",{method:"POST",body:JSON.stringify(e)})},async getDqlGenerationSession(e){return j(`/api/block-studio/ai-imports/${encodeURIComponent(e)}`)},async getBlockStudioImport(e){return j(`/api/block-studio/imports/${encodeURIComponent(e)}`)},async deleteBlockStudioImport(e){return j(`/api/block-studio/imports/${encodeURIComponent(e)}`,{method:"DELETE"})},async clearBlockStudioImports(){return j("/api/block-studio/imports",{method:"DELETE"})},async updateBlockStudioImportCandidate(e,t,n){return j(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async updateDqlGenerationCandidate(e,t,n){return j(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async matchSqlForBlockReuse(e,t){return j("/api/block-studio/match-sql",{method:"POST",body:JSON.stringify({sql:e,...t??{}})})},async previewDqlGenerationCandidate(e,t){return j(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/preview`,{method:"POST"})},async certifyDqlGenerationCandidate(e,t){return j(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/certify`,{method:"POST"})},async saveSelectedDqlGenerationCandidates(e,t){return j(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify(t)})},async runBlockStudioImportCandidate(e,t){return j(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/run`,{method:"POST"})},async saveBlockStudioImportCandidate(e,t){return j(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/save`,{method:"POST"})},async saveAllBlockStudioImportCandidates(e){return j(`/api/block-studio/imports/${encodeURIComponent(e)}/save-all`,{method:"POST"})},async assistBlockStudioImportCandidate(e,t,n){return j(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/ai-assist`,{method:"POST",body:JSON.stringify({action:n})})},async getSemanticLayerDiagnostics(){return j("/api/semantic-layer/diagnostics")},async reloadSemanticLayer(){return j("/api/semantic-layer/reload",{method:"POST"})},async certifyBlockStudio(e){const t=await fetch(`${On}/api/block-studio/certify`,{headers:$n({"Content-Type":"application/json"}),method:"POST",body:JSON.stringify(e)}),n=await t.json().catch(()=>({ok:!1,error:t.statusText}));if(!t.ok&&t.status!==422)throw new Error(JSON.stringify(n));return n},async saveAsBlock(e){return j("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await j("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await j("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return j("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t,n,r){var i,l,a;const o=await j("/api/query",{method:"POST",body:JSON.stringify({sql:e,executionContext:n,executionTarget:r}),signal:t});if(n!=null&&n.runId&&typeof((i=o==null?void 0:o.executionContext)==null?void 0:i.runId)=="string"&&o.executionContext.runId!==n.runId)throw new bt({message:"The notebook server returned a result for a different cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:o.executionContext}});return{...cn(o),executionTarget:((l=o==null?void 0:o.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((a=o==null?void 0:o.executionTarget)==null?void 0:a.target)==="connection"?{target:"connection",...typeof o.executionTarget.connectionName=="string"?{connectionName:o.executionTarget.connectionName}:{}}:void 0,compiledSql:typeof(o==null?void 0:o.compiledSql)=="string"?o.compiledSql:void 0,executedSql:typeof(o==null?void 0:o.executedSql)=="string"?o.executedSql:void 0,targetBinding:o!=null&&o.targetBinding&&typeof o.targetBinding=="object"?o.targetBinding:void 0,executionReceipt:o!=null&&o.executionReceipt&&typeof o.executionReceipt=="object"?o.executionReceipt:void 0}},async previewGeneratedSql(e,t){try{const n=await j("/api/ai/sql-draft/preview",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return{ok:!0,result:cn(n.result)}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async executeNotebookCell(e,t,n){var o,i,l,a,d,c;const r=await j("/api/notebook/execute",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig},executionTarget:e.executionTarget,parameters:((o=e.blockBinding)==null?void 0:o.state)==="bound"?e.blockBinding.parameterValues:e.dqlParameterValues,executionContext:n}),signal:t});if(n!=null&&n.runId&&typeof((i=r==null?void 0:r.executionContext)==null?void 0:i.runId)=="string"&&r.executionContext.runId!==n.runId)throw new bt({message:"The notebook server returned a result for a different semantic cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:r.executionContext}});return{cellType:String((r==null?void 0:r.cellType)??e.type),cellId:typeof((l=r==null?void 0:r.executionContext)==null?void 0:l.cellId)=="string"?r.executionContext.cellId:void 0,runId:typeof((a=r==null?void 0:r.executionContext)==null?void 0:a.runId)=="string"?r.executionContext.runId:void 0,title:typeof(r==null?void 0:r.title)=="string"?r.title:void 0,blockName:typeof(r==null?void 0:r.blockName)=="string"?r.blockName:void 0,blockPath:typeof(r==null?void 0:r.blockPath)=="string"?r.blockPath:void 0,chartConfig:r!=null&&r.chartConfig&&typeof r.chartConfig=="object"?r.chartConfig:void 0,tests:Array.isArray(r==null?void 0:r.tests)?r.tests:void 0,result:r!=null&&r.result?cn(r.result):null,executionTarget:((d=r==null?void 0:r.executionTarget)==null?void 0:d.target)==="local"?{target:"local"}:((c=r==null?void 0:r.executionTarget)==null?void 0:c.target)==="connection"?{target:"connection",...typeof r.executionTarget.connectionName=="string"?{connectionName:r.executionTarget.connectionName}:{}}:void 0,engine:(r==null?void 0:r.engine)==="native"||(r==null?void 0:r.engine)==="metricflow-cli"||(r==null?void 0:r.engine)==="dbt-cloud"?r.engine:void 0,semanticTrace:r!=null&&r.semanticTrace&&typeof r.semanticTrace=="object"?r.semanticTrace:void 0,compiledSql:typeof(r==null?void 0:r.compiledSql)=="string"?r.compiledSql:void 0,executedSql:typeof(r==null?void 0:r.executedSql)=="string"?r.executedSql:void 0,targetBinding:r!=null&&r.targetBinding&&typeof r.targetBinding=="object"?r.targetBinding:void 0,executionReceipt:r!=null&&r.executionReceipt&&typeof r.executionReceipt=="object"?r.executionReceipt:void 0}},async getDatasets(){return j("/api/datasets")},async importDataset(e){if(e.file){const t=new FormData;t.set("file",e.file,e.file.name);for(const[r,o]of Object.entries(e))r==="file"||o===void 0||t.set(r,Array.isArray(o)?o.join(","):String(o));const n=await fetch(`${On}/api/datasets/import`,{method:"POST",headers:$n(),body:t});if(!n.ok){const r=await n.text().catch(()=>"");throw Qo(n,r)}return n.json()}return j("/api/datasets/import",{method:"POST",body:JSON.stringify(e)})},async refreshDataset(e){return j(`/api/datasets/${encodeURIComponent(e)}/refresh`,{method:"POST"})},async updateDatasetSchema(e,t){return j(`/api/datasets/${encodeURIComponent(e)}/schema`,{method:"POST",body:JSON.stringify({overrides:t})})},async renameDataset(e,t,n){return j(`/api/datasets/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({name:t,alias:n})})},async pinDataset(e,t=!0){return j(`/api/datasets/${encodeURIComponent(e)}/pin`,{method:"POST",body:JSON.stringify({pinned:t})})},async removeDataset(e){await j(`/api/datasets/${encodeURIComponent(e)}`,{method:"DELETE"})},async stageDataset(e){return j("/api/datasets/stage",{method:"POST",body:JSON.stringify(e)})},async listNotebookResearch(e){var o,i,l,a,d,c,f,p,h,g,S,x,b,k,C,E,v,w,A,R;const t=new URLSearchParams;typeof e=="string"?e&&t.set("path",e):e&&(e.path&&t.set("path",e.path),e.sourceCellId&&t.set("sourceCellId",e.sourceCellId),e.domain&&t.set("domain",e.domain),e.owner&&t.set("owner",e.owner),e.intent&&t.set("intent",e.intent),e.search&&t.set("q",e.search),e.status&&t.set("status",e.status),e.reviewStatus&&t.set("reviewStatus",e.reviewStatus),e.promotionAction&&t.set("promotionAction",e.promotionAction),e.readiness&&t.set("readiness",e.readiness),e.age&&t.set("age",e.age),e.nextAction&&t.set("nextAction",e.nextAction),e.activeOnly&&t.set("activeOnly","true"),e.sort&&t.set("sort",e.sort),typeof e.limit=="number"&&t.set("limit",String(e.limit)),typeof e.offset=="number"&&t.set("offset",String(e.offset)));const n=t.toString()?`?${t.toString()}`:"",r=await j(`/api/notebook/research${n}`);return{runs:r.runs.map(St),total:typeof r.total=="number"?r.total:r.runs.length,domains:Array.isArray(r.domains)?r.domains.map(y=>({domain:typeof y.domain=="string"&&y.domain.trim()?y.domain:"uncategorized",total:typeof y.total=="number"?y.total:0,draftReady:typeof y.draftReady=="number"?y.draftReady:0,certificationReady:typeof y.certificationReady=="number"?y.certificationReady:0,blocked:typeof y.blocked=="number"?y.blocked:0,staleOpen:typeof y.staleOpen=="number"?y.staleOpen:0,expiredOpen:typeof y.expiredOpen=="number"?y.expiredOpen:0,nextAction:xr(y.nextAction),nextActionCount:typeof y.nextActionCount=="number"&&Number.isFinite(y.nextActionCount)?Math.max(0,Math.floor(y.nextActionCount)):void 0})):[],owners:Array.isArray(r.owners)?r.owners.map(y=>({owner:typeof y.owner=="string"&&y.owner.trim()?y.owner:"unassigned",total:typeof y.total=="number"?y.total:0,draftReady:typeof y.draftReady=="number"?y.draftReady:0,certificationReady:typeof y.certificationReady=="number"?y.certificationReady:0,blocked:typeof y.blocked=="number"?y.blocked:0,staleOpen:typeof y.staleOpen=="number"?y.staleOpen:0,expiredOpen:typeof y.expiredOpen=="number"?y.expiredOpen:0,nextAction:xr(y.nextAction),nextActionCount:typeof y.nextActionCount=="number"&&Number.isFinite(y.nextActionCount)?Math.max(0,Math.floor(y.nextActionCount)):void 0})):[],intents:Array.isArray(r.intents)?r.intents.map(y=>({intent:Yx(y.intent),total:typeof y.total=="number"?y.total:0,draftReady:typeof y.draftReady=="number"?y.draftReady:0,certificationReady:typeof y.certificationReady=="number"?y.certificationReady:0,blocked:typeof y.blocked=="number"?y.blocked:0,staleOpen:typeof y.staleOpen=="number"?y.staleOpen:0,expiredOpen:typeof y.expiredOpen=="number"?y.expiredOpen:0,nextAction:xr(y.nextAction),nextActionCount:typeof y.nextActionCount=="number"&&Number.isFinite(y.nextActionCount)?Math.max(0,Math.floor(y.nextActionCount)):void 0})):[],notebooks:Array.isArray(r.notebooks)?r.notebooks.map(y=>({path:typeof y.path=="string"&&y.path.trim()?y.path:"notebooks/untitled.dqlnb",title:typeof y.title=="string"&&y.title.trim()?y.title:Xx(y.path),total:typeof y.total=="number"?y.total:0,draftReady:typeof y.draftReady=="number"?y.draftReady:0,certificationReady:typeof y.certificationReady=="number"?y.certificationReady:0,blocked:typeof y.blocked=="number"?y.blocked:0,staleOpen:typeof y.staleOpen=="number"?y.staleOpen:0,expiredOpen:typeof y.expiredOpen=="number"?y.expiredOpen:0,nextAction:xr(y.nextAction),nextActionCount:typeof y.nextActionCount=="number"&&Number.isFinite(y.nextActionCount)?Math.max(0,Math.floor(y.nextActionCount)):void 0})):[],counts:{total:typeof((o=r.counts)==null?void 0:o.total)=="number"?r.counts.total:r.runs.length,ready:typeof((i=r.counts)==null?void 0:i.ready)=="number"?r.counts.ready:0,needsReview:typeof((l=r.counts)==null?void 0:l.needsReview)=="number"?r.counts.needsReview:0,dqlDrafts:typeof((a=r.counts)==null?void 0:a.dqlDrafts)=="number"?r.counts.dqlDrafts:0,errors:typeof((d=r.counts)==null?void 0:d.errors)=="number"?r.counts.errors:0,reuseExisting:typeof((c=r.counts)==null?void 0:c.reuseExisting)=="number"?r.counts.reuseExisting:0,extendExisting:typeof((f=r.counts)==null?void 0:f.extendExisting)=="number"?r.counts.extendExisting:0,replacements:typeof((p=r.counts)==null?void 0:p.replacements)=="number"?r.counts.replacements:0,createNew:typeof((h=r.counts)==null?void 0:h.createNew)=="number"?r.counts.createNew:0,draftReady:typeof((g=r.counts)==null?void 0:g.draftReady)=="number"?r.counts.draftReady:0,certificationReady:typeof((S=r.counts)==null?void 0:S.certificationReady)=="number"?r.counts.certificationReady:0,blocked:typeof((x=r.counts)==null?void 0:x.blocked)=="number"?r.counts.blocked:0,staleOpen:typeof((b=r.counts)==null?void 0:b.staleOpen)=="number"?r.counts.staleOpen:0,expiredOpen:typeof((k=r.counts)==null?void 0:k.expiredOpen)=="number"?r.counts.expiredOpen:0,sourceLinked:typeof((C=r.counts)==null?void 0:C.sourceLinked)=="number"?r.counts.sourceLinked:0,nextActions:Zx((E=r.counts)==null?void 0:E.nextActions)},groupCounts:{domains:typeof((v=r.groupCounts)==null?void 0:v.domains)=="number"&&Number.isFinite(r.groupCounts.domains)?Math.max(0,Math.floor(r.groupCounts.domains)):Array.isArray(r.domains)?r.domains.length:0,owners:typeof((w=r.groupCounts)==null?void 0:w.owners)=="number"&&Number.isFinite(r.groupCounts.owners)?Math.max(0,Math.floor(r.groupCounts.owners)):Array.isArray(r.owners)?r.owners.length:0,intents:typeof((A=r.groupCounts)==null?void 0:A.intents)=="number"&&Number.isFinite(r.groupCounts.intents)?Math.max(0,Math.floor(r.groupCounts.intents)):Array.isArray(r.intents)?r.intents.length:0,notebooks:typeof((R=r.groupCounts)==null?void 0:R.notebooks)=="number"&&Number.isFinite(r.groupCounts.notebooks)?Math.max(0,Math.floor(r.groupCounts.notebooks)):Array.isArray(r.notebooks)?r.notebooks.length:0},reviewMetrics:Jx(r.reviewMetrics),limit:r.limit,offset:typeof r.offset=="number"?r.offset:0}},async getNotebookResearchDiagnostics(){const e=await j("/api/notebook/research/diagnostics");return Qx(e)},async createNotebookResearch(e){const t=await j("/api/notebook/research",{method:"POST",body:JSON.stringify(e)});return St(t.run)},async seedNotebookResearchFromCells(e){const t=await j("/api/notebook/research/seed-cells",{method:"POST",body:JSON.stringify(e)});return{created:Array.isArray(t.created)?t.created.map(St):[],createdCount:typeof t.createdCount=="number"?t.createdCount:Array.isArray(t.created)?t.created.length:0,skippedCount:typeof t.skippedCount=="number"?t.skippedCount:0,limitApplied:t.limitApplied===!0}},async listNotebookResearchSourceCoverage(e){const t=await j("/api/notebook/research/source-coverage",{method:"POST",body:JSON.stringify({path:e.path,sourceCellIds:e.sourceCellIds,sourceCells:e.sourceCells,limit:e.limit})});return{runs:Array.isArray(t.runs)?t.runs.map(St):[],requestedCount:typeof t.requestedCount=="number"?t.requestedCount:e.sourceCellIds.length,matchedCount:typeof t.matchedCount=="number"?t.matchedCount:Array.isArray(t.runs)?t.runs.length:0,limitApplied:t.limitApplied===!0}},async previewNotebookResearchContext(e){const t=await j("/api/notebook/research/context-preview",{method:"POST",body:JSON.stringify(e)});return tb(t)},async getNotebookResearch(e){const t=await j(`/api/notebook/research/${encodeURIComponent(e)}`);return St(t.run)},async updateNotebookResearch(e,t){const n=await j(`/api/notebook/research/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});return St(n.run)},async runNotebookResearch(e,t){const n=await j(`/api/notebook/research/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t??{})});return St(n.run)},async checkNotebookResearchReuse(e,t){const n=await j(`/api/notebook/research/${encodeURIComponent(e)}/reuse-check`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:St(n.run),promotion:zc(n.promotion)??n.promotion}},async promoteNotebookResearchToDql(e,t){const n=await j(`/api/notebook/research/${encodeURIComponent(e)}/promote-dql`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:St(n.run)}},async getSchema(){try{const e=await fetch(`${On}/api/schema`,{headers:$n()});if(e.ok)return await e.json();const t=await e.json().catch(()=>null);return t!=null&&t.error&&console.warn(`[dql] schema introspection failed: ${t.error}`),(t==null?void 0:t.fallback)??[]}catch(e){return console.warn("[dql] getSchema request failed",e),[]}},async getConnections(){try{return await j("/api/connections")}catch{return{default:"unknown",connections:{}}}},async previewDbtProfiles(e){return j("/api/connections/dbt-profiles/preview",{method:"POST",body:JSON.stringify({path:e})})},async saveConnections(e,t){return j("/api/connections",{method:"PUT",body:JSON.stringify({connections:e,defaultConnectionName:t})})},async previewConnectionMetadataScope(e,t={}){return j(`/api/connections/${encodeURIComponent(e)}/metadata-scope/preview`,{method:"POST",body:JSON.stringify(t)})},async discoverConnectionMetadataScopes(e){return j(`/api/connections/${encodeURIComponent(e)}/metadata-scope/discovery`,{method:"POST"})},async getConnectionMetadataScope(e){return j(`/api/connections/${encodeURIComponent(e)}/metadata-scope`)},async applyConnectionMetadataScope(e,t){return j(`/api/connections/${encodeURIComponent(e)}/metadata-scope`,{method:"PUT",body:JSON.stringify(t)})},async refreshConnectionMetadata(e){return j(`/api/connections/${encodeURIComponent(e)}/metadata-sync`,{method:"POST"})},async installConnector(e){return j("/api/connectors/install",{method:"POST",body:JSON.stringify({driver:e})})},async testConnection(){try{return await j("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticRuntimeSettings(){return j("/api/semantic-runtime")},async getMetricFlowInstallerStatus(){return j("/api/semantic-runtime/metricflow/installer")},async installMetricFlow(e){return j("/api/semantic-runtime/metricflow/install",{method:"POST",body:JSON.stringify(e?{adapter:e}:{})})},async testDbtCloudSemanticRuntime(e){try{return await j("/api/semantic-runtime/dbt-cloud/test",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:(t==null?void 0:t.message)??"dbt Cloud Semantic Layer test failed."}}},async applyDbtCloudSemanticRuntime(e){return j("/api/semantic-runtime/dbt-cloud/apply",{method:"POST",body:JSON.stringify(e)})},async setSemanticRuntimePreference(e){return j("/api/semantic-runtime/preference",{method:"POST",body:JSON.stringify({preference:e})})},async getSemanticLayer(){try{return await j("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[],domains:[],tags:[],favorites:[],recentlyUsed:[],lastSyncTime:null}}},async getSemanticTree(){return(await j("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return j(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async getSetupLaunch(){return j("/api/onboarding/launch")},async acknowledgeSetupLaunch(){return j("/api/onboarding/acknowledge",{method:"POST",body:"{}"})},async getOnboardingStatus(){return j("/api/onboarding/status")},async previewDbtOnboarding(e){return j("/api/onboarding/dbt/preview",{method:"POST",body:JSON.stringify(e)})},async applyDbtOnboarding(e){return j("/api/onboarding/dbt/apply",{method:"POST",body:JSON.stringify({...e,fingerprint:e.expectedFingerprint})})},async refreshDbtOnboarding(e={}){return j("/api/onboarding/refresh",{method:"POST",body:JSON.stringify(e)})},async getOnboardingJob(e){return j(`/api/onboarding/jobs/${encodeURIComponent(e)}`)},async cancelOnboardingJob(e){return j(`/api/onboarding/jobs/${encodeURIComponent(e)}`,{method:"DELETE"})},async discoverOnboardingDomains(e={}){return j("/api/onboarding/domains/discover",{method:"POST",body:JSON.stringify(e)})},async applyOnboardingDomains(e){return j("/api/onboarding/domains/apply",{method:"POST",body:JSON.stringify(e)})},async importSemanticLayer(e){return j("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return j("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return j("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return j("/api/semantic-layer/sync-preview",{method:"POST",body:JSON.stringify({})})},async searchSemanticLayer(e){const t=new URLSearchParams;e.query&&t.set("q",e.query),e.domain&&t.set("domain",e.domain),e.tag&&t.set("tag",e.tag),e.type&&t.set("type",e.type);try{return await j(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[]}}},async getFavorites(){try{return(await j("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await j("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await j("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await j("/api/user-prefs/recent",{method:"POST",body:JSON.stringify({name:e})})).recentlyUsed}catch{return[]}},async getCompatibleDimensions(e){const t=new URLSearchParams;e.length>0&&t.set("metrics",e.join(","));try{return(await j(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async getCompatibility(e){const t=new URLSearchParams;e.length>0&&t.set("metrics",e.join(","));const n=await j(`/api/semantic-layer/compatible-dims?${t.toString()}`);return{dimensions:n.dimensions??[],engine:n.engine??"native",incompatible:n.incompatible??[],degraded:n.degraded??null}},async composeQuery(e,t,n){try{return await j("/api/semantic-query",{method:"POST",body:JSON.stringify({metrics:e,dimensions:t,timeDimension:n})})}catch(r){return{error:r.message??"Failed to compose query"}}},async previewSemanticBuilder(e){try{return await j("/api/semantic-builder/preview",{method:"POST",body:JSON.stringify(e)})}catch(t){return t instanceof bt?{error:t.message,code:t.code,details:t.details}:{error:t instanceof Error?t.message:"Failed to preview semantic block"}}},async saveSemanticBuilder(e){return j("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await j("/api/semantic-layer/metric",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t.message??"Failed to create metric"}}},async describeTable(e){const t=e.split("."),n=t.length>1?t[t.length-1]:e,r=t.length>1?t.slice(0,-1).join("."):"",o=new URLSearchParams({table:n});r&&o.set("schema",r);try{return await j(`/api/describe-table?${o.toString()}`)}catch{return[]}},async fetchLineage(){try{return await j("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await j(`/api/lineage/search?q=${encodeURIComponent(e)}`)}catch{return{matches:[]}}},async queryLineage(e){var n;const t=new URLSearchParams;e.focus&&t.set("focus",e.focus),e.search&&t.set("search",e.search),(n=e.types)!=null&&n.length&&t.set("types",e.types.join(",")),e.domain&&t.set("domain",e.domain),e.upstreamDepth!==void 0&&t.set("upstreamDepth",String(e.upstreamDepth)),e.downstreamDepth!==void 0&&t.set("downstreamDepth",String(e.downstreamDepth));try{return await j(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await j(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBusiness360(e){try{return await j(`/api/lineage/business-360/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await j(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await j(`/api/lineage/impact/${encodeURIComponent(e)}`)}catch{return null}},async fetchLineagePaths(e,t){try{const n=new URLSearchParams;t!=null&&t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),t!=null&&t.maxPaths&&n.set("maxPaths",String(t.maxPaths));const r=n.toString(),o=`/api/lineage/paths/${encodeURIComponent(e)}${r?`?${r}`:""}`;return await j(o)}catch{return null}},async fetchGitStatus(){try{return await j("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await j(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await j(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await j("/api/run-snapshot",{method:"PUT",body:JSON.stringify({path:e,snapshot:t})})},async fetchGitDiff(e,t){try{const n=new URLSearchParams;e&&n.set("path",e),t&&n.set("staged","true");const r=n.toString();return await j(`/api/git/diff${r?`?${r}`:""}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}},async fetchGitBranches(){try{return await j("/api/git/branches")}catch{return{inRepo:!1,current:null,branches:[]}}},async fetchGitRemote(){try{return await j("/api/git/remote")}catch{return{inRepo:!1,url:null,name:null}}},async fetchGitGovernedContext(){try{return await j("/api/git/governed-context")}catch{return{inRepo:!1,trackingReady:!1,legacyBroadIgnore:!1,domains:yr(),skills:yr(),artifacts:yr(),learning:yr()}}},async enableGitGovernedContextTracking(){try{return await j("/api/git/governed-context/enable",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitStage(e){try{return await j("/api/git/stage",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitUnstage(e){try{return await j("/api/git/unstage",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitDiscard(e){try{return await j("/api/git/discard",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitCommit(e,t=!1){try{return await j("/api/git/commit",{method:"POST",body:JSON.stringify({message:e,stageAll:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async gitPush(){try{return await j("/api/git/push",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitPull(){try{return await j("/api/git/pull",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitCreateBranch(e,t=!0){try{return await j("/api/git/branch",{method:"POST",body:JSON.stringify({name:e,checkout:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async gitCreateReview(e){try{return await j("/api/git/review",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitOpenReview(e){try{return await j("/api/git/review/open",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitCheckout(e){try{return await j("/api/git/checkout",{method:"POST",body:JSON.stringify({name:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async listApps(){try{const{apps:e}=await j("/api/apps");return e}catch{return[]}},async listAppsStrict(){const{apps:e}=await j("/api/apps");return e},async recommendAppBlocks(e){try{const{blocks:t}=await j("/api/apps/recommend-blocks",{method:"POST",body:JSON.stringify(e)});return t}catch{return[]}},async createApp(e){return j("/api/apps",{method:"POST",body:JSON.stringify(e)})},async generateApp(e){try{return await j("/api/apps/generate",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async createAppAiBuild(e){try{return await j("/api/apps/ai-builds",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async getAppAiBuild(e){try{const{session:t}=await j(`/api/apps/ai-builds/${encodeURIComponent(e)}`);return t}catch{return null}},async proposeAppAiBuild(e){try{return await j("/api/apps/ai-builds/propose",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async commitAppAiBuild(e,t={}){try{return await j(`/api/apps/ai-builds/${encodeURIComponent(e)}/commit`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getApp(e){try{return await j(`/api/apps/${encodeURIComponent(e)}`)}catch{return null}},async attachAppNotebook(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/notebooks`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppNotebookCandidates(e){try{const{notebooks:t}=await j(`/api/apps/${encodeURIComponent(e)}/notebook-candidates`);return t}catch{return[]}},async createAppNotebook(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/notebooks/create`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async previewAppNotebook(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/notebooks/preview?path=${encodeURIComponent(t)}`)}catch{return null}},async runAppNotebook(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/notebooks/run`,{method:"POST",body:JSON.stringify({path:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppConversations(e){try{const{conversations:t}=await j(`/api/apps/${encodeURIComponent(e)}/conversations`);return t}catch{return[]}},async createAppConversation(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/conversations`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getAppConversation(e,t){try{const{conversation:n}=await j(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`);return n}catch{return null}},async updateAppConversation(e,t,n){try{return await j(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async deleteAppConversation(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`,{method:"DELETE"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppInvestigations(e,t){try{const n=new URLSearchParams;t&&n.set("dashboardId",t);const r=n.toString(),{investigations:o}=await j(`/api/apps/${encodeURIComponent(e)}/investigations${r?`?${r}`:""}`);return o}catch{return[]}},async createAppInvestigation(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/investigations`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getAppInvestigation(e,t){try{const{investigation:n}=await j(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}`);return n}catch{return null}},async runAppInvestigation(e,t,n){try{return await j(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n??{})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async pinAppInvestigation(e,t,n){try{return await j(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}/pin`,{method:"POST",body:JSON.stringify(n??{})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async getDashboard(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`)}catch{return null}},async dashboardFilterOptions(e,t){try{const n=new URLSearchParams({block:e,column:t});return await j(`/api/dashboard/filter-options?${n.toString()}`)}catch{return null}},async getAppEditorCatalog(e,t){try{const n=new URLSearchParams;t!=null&&t.domain&&n.set("domain",t.domain),(t==null?void 0:t.certifiedOnly)===!1&&n.set("certifiedOnly","false");const r=n.toString();return await j(`/api/apps/${encodeURIComponent(e)}/editor/catalog${r?`?${r}`:""}`)}catch{return null}},async createAppDashboard(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/dashboards`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async patchDashboardLayout(e,t,n){try{return await j(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/layout`,{method:"PATCH",body:JSON.stringify({layout:n})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async askApp(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/ask`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteApp(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/promote`,{method:"POST",body:JSON.stringify(t??{})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async recommendVisualization(e){try{return await j("/api/visualizations/recommend",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async recommendDashboardTile(e,t,n){try{return await j(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/tiles/recommend`,{method:"POST",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async createAiPin(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/ai-pins`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAiPins(e,t){try{const n=new URLSearchParams;t&&n.set("dashboardId",t);const r=n.toString(),{pins:o}=await j(`/api/apps/${encodeURIComponent(e)}/ai-pins${r?`?${r}`:""}`);return o}catch{return[]}},async refreshAiPin(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/ai-pins/${encodeURIComponent(t)}/refresh`,{method:"POST"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteAiPin(e,t){try{return await j(`/api/apps/${encodeURIComponent(e)}/ai-pins/${encodeURIComponent(t)}/promote`,{method:"POST"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async fetchScopedLineage(e){try{const t=new URLSearchParams;return e.domain&&t.set("domain",e.domain),e.appId&&t.set("appId",e.appId),e.dashboardId&&t.set("dashboardId",e.dashboardId),e.blockId&&t.set("blockId",e.blockId),await j(`/api/lineage/scope?${t.toString()}`)}catch{return null}},async runDashboard(e,t,n){try{return await j(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})}catch{return null}},async getDashboardStory(e,t,n){try{return await j(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/story`,{method:"POST",body:JSON.stringify({runId:n})})}catch{return null}},async saveDashboard(e,t,n){try{return{ok:!!(await j(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)})).ok}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async getPersona(){try{const{persona:e}=await j("/api/persona");return e}catch{return null}},async setPersona(e,t){try{const{persona:n}=await j("/api/persona",{method:"POST",body:JSON.stringify({userId:e,appId:t})});return n}catch{return null}},async clearPersona(){try{await j("/api/persona",{method:"DELETE"})}catch{}},async getSkills(){return j("/api/skills")},async getSkillPathSettings(){return j("/api/skills/settings")},async updateSkillPath(e){return j("/api/skills/settings",{method:"PUT",body:JSON.stringify({path:e})})},async getSkillOptions(e=""){const t=e.trim()?`?q=${encodeURIComponent(e.trim())}`:"";return j(`/api/skills/options${t}`)},async createSkill(e){return j("/api/skills",{method:"POST",body:JSON.stringify({skill:e})})},async updateSkill(e,t){return j(`/api/skills/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({skill:t})})},async getEmbeddingSettings(){return j("/api/settings/embeddings")},async saveEmbeddingSettings(e){return j("/api/settings/embeddings",{method:"PUT",body:JSON.stringify(e)})},async listEmbeddingModels(e){const t=e?`?endpoint=${encodeURIComponent(e)}`:"";return j(`/api/settings/embeddings/models${t}`)},async installEmbeddingModel(e,t){return j("/api/settings/embeddings/install",{method:"POST",body:JSON.stringify({model:e,endpoint:t})})},async testEmbeddingProvider(){return j("/api/settings/embeddings/test",{method:"POST"})},async reindexEmbeddings(){return j("/api/settings/embeddings/reindex",{method:"POST"})},async deleteSkill(e){return j(`/api/skills/${encodeURIComponent(e)}`,{method:"DELETE"})},async getDomains(){try{return await j("/api/domains")}catch{return{domains:[]}}},async createDomain(e){return j("/api/domains",{method:"POST",body:JSON.stringify({domain:e})})},async updateDomain(e,t){return j(`/api/domains/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({domain:t})})},async deleteDomain(e){return j(`/api/domains/${encodeURIComponent(e)}`,{method:"DELETE"})},async startContextBootstrap(e={}){return j("/api/context-bootstrap",{method:"POST",body:JSON.stringify(e)})},async getContextBootstrap(e){return j(`/api/context-bootstrap/${encodeURIComponent(e)}`)},async getLatestContextBootstrap(){return(await j("/api/context-bootstrap/latest")).session??null},async saveContextBootstrapSelected(e,t){return j(`/api/context-bootstrap/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify({candidateIds:t})})}},rb={source_table:"#8a8d96",dbt_model:"#4a74c9",dbt_source:"#4a74c9",term:"#0a6b5e",block:"#b26b1f",business_view:"#c14545",metric:"#6b5dd3",dimension:"#0a6b5e",domain:"#7c5cff",chart:"#c14590",notebook:"#2e8b57",dashboard:"#2e8b57",app:"#2e8b57"},ob={source_table:"TBL",dbt_model:"DBT",dbt_source:"SRC",term:"TERM",block:"BLK",business_view:"VIEW",metric:"MET",dimension:"DIM",domain:"DOM",chart:"CHT",notebook:"NB",dashboard:"DASH",app:"APP"},qc={source_table:"Source Table",dbt_model:"dbt Model",dbt_source:"dbt Source",term:"Business Term",block:"DQL Block",business_view:"Business View",metric:"Metric",dimension:"Dimension",domain:"Domain",chart:"Chart",notebook:"Notebook",dashboard:"Dashboard",app:"App"},$1={reads_from:"#8b949e",feeds_into:"#56d364",defines:"#39c5cf",composes:"#f2cc60",aggregates:"#388bfd",visualizes:"#f778ba",depends_on:"#ff7b72",contains:"#d2a8ff",crosses_domain:"#d2a8ff",certified_by:"#56d364"},O1={reads_from:"reads from",feeds_into:"feeds into",defines:"defines",composes:"composes into",aggregates:"aggregates into",visualizes:"visualizes",depends_on:"dbt depends on",contains:"contains",crosses_domain:"crosses domain",certified_by:"certified by"},sb={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Fi={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},zi=["source","transform","answer","consumption"],P1=["term","business_view","block","metric","dimension","domain","source_table","dbt_source","dbt_model","chart","notebook","dashboard","app"],D1=["source_table","dbt_source","dbt_model"],ib=["term","domain","business_view","metric","dimension","block"];[...ib];function ab(e){if(e.layer)return e.layer;switch(e.type){case"source_table":case"dbt_source":return"source";case"dbt_model":return"transform";case"term":case"block":case"business_view":case"metric":case"dimension":case"domain":return"answer";case"chart":case"notebook":case"dashboard":case"app":return"consumption";default:return"answer"}}function lb(){const{state:e,dispatch:t}=xe(),n=e.inspectorContext;return s.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${le("borderSubtle")}`,background:le("surfaceBase"),color:le("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${fe[3]}px ${fe[4]}px`,borderBottom:`1px solid ${le("borderSubtle")}`},children:[s.jsx("div",{style:{fontSize:Be.sm,fontWeight:Zo.semibold},children:n?cb(n):"Inspector"}),s.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:le("textMuted"),cursor:"pointer",fontSize:Be.md,padding:2,borderRadius:Dt.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:fe[4]},children:n?s.jsx(db,{context:n}):s.jsx(hb,{})})]})}function cb(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function db({context:e}){return e.kind==="cell"?s.jsx(ub,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx(pb,{nodeId:e.nodeId}):s.jsx(fb,{name:e.name})}function ub({cellId:e}){const{state:t}=xe(),n=t.cells.find(r=>r.id===e);return n?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:fe[3],fontSize:Be.sm},children:[s.jsx(Ee,{label:"Type",children:n.type}),s.jsx(Ee,{label:"ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),s.jsxs(Ee,{label:"Length",children:[n.content.length," chars"]}),n.status&&s.jsx(Ee,{label:"Status",children:n.status})]}):s.jsx(Lr,{children:"No matching cell in the active notebook."})}function pb({nodeId:e}){const[t,n]=u.useState(null),[r,o]=u.useState(!0);if(u.useEffect(()=>{let a=!1;return o(!0),N.fetchLineageNode(e).then(d=>{a||(n(d),o(!1))}).catch(()=>{a||o(!1)}),()=>{a=!0}},[e]),r)return s.jsx(Lr,{children:"Loading node…"});if(!t||!t.node)return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:fe[3]},children:[s.jsx(Ee,{label:"Node ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),s.jsx(Lr,{children:"No metadata available for this node."})]});const i=t.node,l=i.metadata??{};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:fe[3]},children:[s.jsx(Ee,{label:"Name",children:i.name??e}),s.jsx(Ee,{label:"Type",children:qc[i.type]??i.type}),i.domain&&s.jsx(Ee,{label:"Domain",children:i.domain}),i.owner&&s.jsx(Ee,{label:"Owner",children:i.owner}),i.status&&s.jsx(Ee,{label:"Status",children:i.status}),typeof l.termType=="string"&&s.jsx(Ee,{label:"Term Type",children:l.termType}),typeof l.description=="string"&&s.jsx(Ee,{label:"Description",children:l.description}),Array.isArray(l.identifiers)&&l.identifiers.length>0&&s.jsx(Ee,{label:"Identifiers",children:l.identifiers.map(String).join(", ")}),Array.isArray(l.synonyms)&&l.synonyms.length>0&&s.jsx(Ee,{label:"Synonyms",children:l.synonyms.map(String).join(", ")}),typeof l.businessOutcome=="string"&&s.jsx(Ee,{label:"Business Outcome",children:l.businessOutcome}),i.layer&&s.jsx(Ee,{label:"Layer",children:i.layer}),s.jsx(Ee,{label:"Upstream",children:t.incoming.length}),s.jsx(Ee,{label:"Downstream",children:t.outgoing.length}),(i.path||l.filePath)&&s.jsx(Ee,{label:"Path",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Be.xs},children:i.path??l.filePath})})]})}function fb({name:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:fe[3]},children:[s.jsx(Ee,{label:"Metric",children:e}),s.jsx(Lr,{children:"Definition, dimensions, and governance surface will render here."})]})}function Ee({label:e,children:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[s.jsx("div",{style:{fontSize:Be.xs,color:le("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Zo.medium},children:e}),s.jsx("div",{style:{fontSize:Be.sm,color:le("textPrimary")},children:t})]})}function Lr({children:e}){return s.jsx("div",{style:{fontSize:Be.sm,color:le("textSecondary"),lineHeight:1.5,background:le("surfaceSunken"),border:`1px solid ${le("borderSubtle")}`,borderRadius:Dt.md,padding:fe[3]},children:e})}function hb(){return s.jsx("div",{style:{fontSize:Be.sm,color:le("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const Pn={appBg:"--color-bg-primary",sidebarBg:"--color-bg-secondary",activityBarBg:"--color-bg-sunken",headerBg:"--color-bg-toolbar",headerBorder:"--color-border-primary",cellBg:"--color-bg-card",cellBorder:"--color-border-subtle",cellBorderActive:"--color-accent-blue",cellBorderRunning:"--color-status-success",textPrimary:"--color-text-primary",textSecondary:"--color-text-secondary",textMuted:"--color-text-tertiary",editorBg:"--color-bg-surface",editorBorder:"--color-border-subtle",tableBorder:"--color-border-subtle",tableHeaderBg:"--color-bg-secondary",tableRowHover:"--color-bg-hover",accent:"--color-accent-blue",accentHover:"--color-accent-blue",success:"--color-status-success",error:"--color-status-error",warning:"--color-status-warning",btnBg:"--color-bg-tertiary",btnBorder:"--color-border-primary",btnHover:"--color-bg-hover",sidebarItemHover:"--color-bg-hover",sidebarItemActive:"--color-bg-active",scrollbarThumb:"--color-border-secondary",modalBg:"--color-bg-secondary",modalOverlay:"--color-bg-overlay",inputBg:"--color-bg-sunken",inputBorder:"--color-border-subtle",pillBg:"--color-bg-tertiary",font:"--font-ui",fontMono:"--font-mono",fontSerif:"--font-ui"},qi={appBg:"#fbfaf7",sidebarBg:"#fbfaf7",activityBarBg:"#ffffff",headerBg:"#ffffff",headerBorder:"#e9e6e0",cellBg:"#ffffff",cellBorder:"#e9e6e0",cellBorderActive:"#6b5dd3",cellBorderRunning:"#2e8b57",textPrimary:"#1a1a1a",textSecondary:"#4a4a52",textMuted:"#8a8d96",editorBg:"#fbfaf7",editorBorder:"#e9e6e0",tableBorder:"#f0eee9",tableHeaderBg:"#faf9f7",tableRowHover:"#f3f0ea",accent:"#6b5dd3",accentHover:"#5c4fc2",success:"#2e8b57",error:"#c14545",warning:"#b26b1f",btnBg:"#ffffff",btnBorder:"#e9e6e0",btnHover:"#f3f0ea",sidebarItemHover:"#f3f0ea",sidebarItemActive:"#f3f0fb",scrollbarThumb:"#d9d5cc",modalBg:"#ffffff",modalOverlay:"rgba(26,26,26,0.40)",inputBg:"#fbfaf7",inputBorder:"#e9e6e0",pillBg:"#f3f0ea",font:"'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', ui-monospace, 'SFMono-Regular', Menlo, Monaco, Consolas, monospace",fontSerif:"'Inter', -apple-system, BlinkMacSystemFont, sans-serif"};function Ui(e){if(typeof document>"u")return qi[e];const t=Pn[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||qi[e]}function mb(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Pn)return Ui(t)},has(e,t){return typeof t=="string"&&t in Pn},ownKeys(){return Object.keys(Pn)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Pn)))return{enumerable:!0,configurable:!0,value:Ui(t)}}})}const Kt=mb(),Fe={obsidian:Kt,paper:Kt,white:Kt,dark:Kt,light:Kt,midnight:Kt,arctic:Kt};function ot(e,t="0 0 24 24"){return function({size:r=16,strokeWidth:o=1.75,...i}){return s.jsx("svg",{width:r,height:r,viewBox:t,fill:"none",stroke:"currentColor",strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round",...i,children:e})}}const gb=ot(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1.5"})]}));ot(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]}));const yb=ot(s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"5",cy:"12",r:"2"}),s.jsx("circle",{cx:"19",cy:"5",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("path",{d:"M7 12l10-6M7 12l10 6"})]})),M1=ot(s.jsxs(s.Fragment,{children:[s.jsx("ellipse",{cx:"12",cy:"5",rx:"8",ry:"3"}),s.jsx("path",{d:"M4 5v6c0 1.66 3.58 3 8 3s8-1.34 8-3V5"}),s.jsx("path",{d:"M4 11v6c0 1.66 3.58 3 8 3s8-1.34 8-3v-6"})]}));ot(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),s.jsx("path",{d:"M16 20l4 4"})]}));ot(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 3v18h18"}),s.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]}));ot(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("path",{d:"M3 9h18M9 3v18"})]}));ot(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),s.jsx("path",{d:"M8 12h8M12 8v8"})]}));const I1=ot(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),s.jsx("circle",{cx:"18",cy:"17",r:"2"})]}));ot(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));ot(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h10l6 6v10H4z"}),s.jsx("path",{d:"M14 4v6h6"}),s.jsx("path",{d:"M8 14l3 3 5-5"})]}));ot(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M21 12a8 8 0 01-11.5 7.2L4 21l1.8-5.5A8 8 0 1121 12z"})}));const Uc=44,Wc=188,Kc="dql-activitybar-expanded";function xb(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(Kc))==="1"}catch{return!1}}function bb(e){var t;try{(t=window.localStorage)==null||t.setItem(Kc,e?"1":"0")}catch{}}function Wi({title:e,icon:t,active:n,expanded:r,onClick:o,t:i}){const[l,a]=u.useState(!1),d=s.jsxs("button",{"aria-label":e,onClick:o,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{width:r?Wc-12:Uc-8,height:32,display:"flex",alignItems:"center",justifyContent:r?"flex-start":"center",gap:10,padding:r?"0 10px":0,marginLeft:r?6:4,marginRight:r?6:4,background:n?i.accent+"1f":l?i.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?i.accent:l?i.textPrimary:i.textSecondary,transition:"background 0.15s, color 0.15s",fontFamily:i.font,fontSize:13,fontWeight:n?500:400,textAlign:"left",overflow:"hidden",whiteSpace:"nowrap"},children:[s.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,width:18,height:18},children:t}),r&&s.jsx("span",{style:{flex:1,textOverflow:"ellipsis",overflow:"hidden"},children:e})]});return r?d:s.jsx(fl,{content:e,side:"right",children:d})}function vb(){const{state:e,dispatch:t}=xe(),n=Fe[e.themeMode],[r,o]=u.useState(xb);u.useEffect(()=>{bb(r)},[r]);function i(d){if(d==="home"||d==="ask"||d==="modeling"){t({type:"SET_MAIN_VIEW",view:d});return}if(d==="lineage"){t({type:"SET_SIDEBAR_PANEL",panel:"lineage"});return}if(d==="connection"||d==="git"||d==="apps"||d==="readiness"||d==="skills"||d==="domains"||d==="settings"){t({type:"SET_SIDEBAR_PANEL",panel:d});return}e.sidebarPanel===d&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:d})}const l=[{label:"Insights",items:[{key:"apps",title:"Apps",icon:s.jsx(Qy,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"ask",title:"Ask",icon:s.jsx(qy,{size:16,strokeWidth:1.75}),active:e.mainView==="ask"}]},{label:"Build",items:[{key:"files",title:"Notebooks",icon:s.jsx(Ps,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"block_library",title:"Blocks",icon:s.jsx(gb,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(yb,{size:16}),active:e.mainView==="lineage"||e.mainView==="lineage_detail"}]},{label:"Govern",items:[{key:"domains",title:"Domains",icon:s.jsx(Go,{size:16,strokeWidth:1.75}),active:e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills"},{key:"git",title:"Source control",icon:s.jsx(Sn,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"settings",title:"Settings",icon:s.jsx(dx,{size:16,strokeWidth:1.75}),active:e.mainView==="settings"||e.mainView==="connection"}]}],a=[{key:"help",title:"Help",icon:s.jsx(ey,{size:16,strokeWidth:1.75}),active:e.mainView==="help",onClick:()=>t({type:"SET_MAIN_VIEW",view:"help"})}];return s.jsxs("div",{style:{width:r?Wc:Uc,flexShrink:0,background:n.activityBarBg,borderRight:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",paddingTop:6,paddingBottom:6,gap:2,userSelect:"none",transition:"width 0.18s ease",overflow:"hidden"},children:[s.jsx("div",{style:{display:"flex",justifyContent:r?"flex-end":"center",paddingLeft:r?6:0,paddingRight:r?6:0,marginBottom:4},children:s.jsx(fl,{content:r?"Collapse":"Expand",side:"right",children:s.jsx("button",{"aria-label":r?"Collapse sidebar rail":"Expand sidebar rail",onClick:()=>o(d=>!d),style:{width:28,height:26,display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderRadius:5,cursor:"pointer",color:n.textMuted,padding:0},onMouseEnter:d=>{d.currentTarget.style.color=n.textPrimary,d.currentTarget.style.background=n.textPrimary+"0f"},onMouseLeave:d=>{d.currentTarget.style.color=n.textMuted,d.currentTarget.style.background="transparent"},children:r?s.jsx(Hg,{size:14,strokeWidth:2}):s.jsx(Jg,{size:14,strokeWidth:2})})})}),l.map((d,c)=>s.jsxs(Pe.Fragment,{children:[c>0?s.jsx("div",{style:{height:1,margin:r?"8px 10px 2px":"8px 12px",background:n.headerBorder}}):null,r?s.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.textMuted,letterSpacing:"0.04em",padding:"4px 12px 2px"},children:d.label}):null,d.items.map(f=>s.jsx(Wi,{title:f.title,icon:f.icon,active:f.active,expanded:r,onClick:()=>i(f.key),t:n},f.key))]},d.label)),s.jsx("div",{style:{flex:1}}),a.map(d=>s.jsx(Wi,{title:d.title,icon:d.icon,active:d.active,expanded:r,onClick:d.onClick,t:n},d.key))]})}const Sb=2e4,L1="application/dql-semantic-ref",Ki=new Map;let Vn=null;function kb(e){N.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function Vi(e,t){const n=`${e}:${t.toLowerCase()}`,r=Ki.get(n);if(r&&Date.now()<r.expiresAt)return r.items;const o=new URLSearchParams({kind:e,q:t,limit:"50"}),i=await fetch(`${window.location.origin}/api/editor/completions?${o.toString()}`);if(!i.ok)throw new Error(`Failed to load semantic completions: HTTP ${i.status}`);const l=await i.json(),a=Array.isArray(l.completions)?l.completions:[];return Ki.set(n,{items:a,expiresAt:Date.now()+Sb}),a}function Vc(e,t,n){const r=n??e.state.selection.main.from;e.dispatch({changes:{from:r,to:n??e.state.selection.main.to,insert:t},selection:{anchor:r+t.length}}),e.focus()}function N1(e){Vn=e}function B1(e){Vn===e&&(Vn=null)}function wb(e){return Vn?(Vc(Vn,e),!0):!1}function F1(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;Vc(e,t,r)}function Hi(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
406
- ${e.description}`:""}${e.sql?`
407
- ${e.sql}`:""}`,apply(r){const i=r.state.sliceDoc(n,n+1)===")"?e.name:`${e.name})`;r.dispatch({changes:{from:t,to:n,insert:i},selection:{anchor:t+i.length}}),kb(e.name)}}}function jb(e){return{from:e,options:[{label:"@metric(",detail:"semantic metric",type:"function",apply(t,n,r,o){t.dispatch({changes:{from:r,to:o,insert:"@metric("},selection:{anchor:r+8}})}},{label:"@dim(",detail:"semantic dimension",type:"function",apply(t,n,r,o){t.dispatch({changes:{from:r,to:o,insert:"@dim("},selection:{anchor:r+5}})}}]}}const z1=async e=>{const{state:t,pos:n}=e,r=t.sliceDoc(Math.max(0,n-120),n),o=/@metric\(([^)]*)$/i.exec(r);if(o){const a=o[1].trim().toLowerCase(),d=n-o[1].length,c=await Vi("metric",a);return{from:d,options:c.map(f=>Hi(f,d,n)),validFor:/^[\w-]*$/}}const i=/@dim\(([^)]*)$/i.exec(r);if(i){const a=i[1].trim().toLowerCase(),d=n-i[1].length,c=await Vi("dimension",a);return{from:d,options:c.map(f=>Hi(f,d,n)),validFor:/^[\w-]*$/}}const l=/@([md][a-z_]*)?$/i.exec(r);return l?jb(n-l[0].length):(e.explicit,null)};function q1(e){if(!e)return null;try{const t=JSON.parse(e);return(t.type==="metric"||t.type==="dimension")&&t.name&&t.reference?{type:t.type,name:t.name,reference:t.reference}:null}catch{return null}}const Cb=6,Eb=999,Ab={xs:{height:22,fontSize:10.5,paddingX:7,gap:4,icon:11},sm:{height:26,fontSize:11.5,paddingX:9,gap:5,icon:12},md:{height:32,fontSize:12.5,paddingX:12,gap:6,icon:14},lg:{height:54,fontSize:12.5,paddingX:17,gap:7,icon:15}};function ke(e,t={}){const{variant:n="secondary",size:r="sm",active:o=!1,disabled:i=!1,pill:l=!1}=t,a=Ab[r],d=n==="danger"?e.error:n==="success"?e.success:n==="accent"?e.accent:void 0,c={boxSizing:"border-box",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:a.gap,height:a.height,padding:`0 ${a.paddingX}px`,borderRadius:l?Eb:Cb,fontSize:a.fontSize,fontWeight:n==="primary"?700:600,fontFamily:e.font,lineHeight:1,whiteSpace:"nowrap",cursor:i?"not-allowed":"pointer",opacity:i?.55:1,transition:"background 0.15s, border-color 0.15s, color 0.15s"};return n==="primary"?{...c,background:e.accent,border:`1px solid ${e.accent}`,color:"#ffffff"}:n==="ghost"?{...c,background:o?`${e.accent}14`:"transparent",border:"1px solid transparent",color:o?e.accent:e.textMuted,fontWeight:550}:d?{...c,background:o?`${d}22`:`${d}12`,border:`1px solid ${d}${o?"66":"33"}`,color:d}:{...c,background:o?`${e.accent}14`:e.btnBg,border:`1px solid ${o?e.accent:e.btnBorder}`,color:o?e.accent:e.textSecondary}}function Hc(e){var r,o;if(e.objectType==="staged_dataset"||e.storageMode==="staged")return{kind:"staged",label:"snapshot",title:"Bounded warehouse snapshot in the local workspace",tone:"warning"};const t=(r=e.path.toLowerCase().match(/\.([a-z0-9]+)$/))==null?void 0:r[1],n=e.source==="file"||e.objectType==="dataset";return n&&t==="csv"?{kind:"csv",label:e.storageMode==="project"?"project csv":"csv",title:e.storageMode==="project"?"Project-controlled CSV dataset":"Local CSV dataset",tone:e.storageMode==="project"?"success":"accent"}:n&&(t==="json"||t==="jsonl"||t==="ndjson")?{kind:"json",label:"json",title:"Local JSON dataset",tone:"accent"}:n&&t==="parquet"?{kind:"parquet",label:"parquet",title:"Local Parquet dataset",tone:"accent"}:(o=e.objectType)!=null&&o.toLowerCase().includes("view")?{kind:"view",label:"view",title:"Warehouse view",tone:"muted"}:{kind:"table",label:"table",title:"Warehouse table",tone:"accent"}}function Tb({table:e,colors:t,size:n=13}){const r=Hc(e),o=t[r.tone],i={size:n,color:o,strokeWidth:2,style:{flexShrink:0}},l=r.kind==="csv"?s.jsx(vy,{...i}):r.kind==="json"?s.jsx(uy,{...i}):r.kind==="parquet"||r.kind==="staged"?s.jsx(Ds,{...i}):r.kind==="view"?s.jsx(Dc,{...i}):s.jsx(tr,{...i});return s.jsx("span",{"aria-label":r.title,title:r.title,style:{display:"inline-flex"},children:l})}const Rb=new Set(["metric","measure","dimension","time_dimension"]);function so(e){var r;if(typeof((r=e.meta)==null?void 0:r.reference)=="string"&&e.meta.reference.trim())return e.meta.reference;const t=`${e.kind}:`;if(e.id.startsWith(t))return e.id.slice(t.length);const n=e.id.lastIndexOf(":");return n>=0?e.id.slice(n+1):e.id}function Yo(e){const t=so(e);return e.kind==="metric"||e.kind==="measure"?`@metric(${t})`:`@dim(${t})`}function Gc(e){var r,o;const t=typeof((r=e.meta)==null?void 0:r.qualifiedName)=="string"?e.meta.qualifiedName.trim():"";return t||(typeof((o=e.meta)==null?void 0:o.localName)=="string"?e.meta.localName.trim():"")||so(e)}function Ms(e,t){return!t||e.label.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||so(e).toLowerCase().includes(t)||Gc(e).toLowerCase().includes(t)?!0:(e.children??[]).some(n=>Ms(n,t))}function Jc(e){var r;const t=[],n=new Map;for(const o of e){const i=(((r=o.children)==null?void 0:r.length)??0)>0,l=i?`group:${o.label.toLowerCase()}`:`leaf:${Yo(o).toLowerCase()}`,a=n.get(l);if(a){i&&a.children&&(a.children=a.children.concat(o.children??[]));continue}const d=o.children?{...o,children:[...o.children]}:o;n.set(l,d),t.push(d)}for(const o of t)o.children&&(o.children=Jc(o.children));return t}const So={metric:{Icon:$y,tone:e=>e.accent},measure:{Icon:gx,tone:e=>e.accent},dimension:{Icon:Sx,tone:e=>e.success},time_dimension:{Icon:ny,tone:e=>e.warning},entity:{Icon:Ng,tone:e=>e.textSecondary},segment:{Icon:Ry,tone:e=>e.textMuted},hierarchy:{Icon:Sn,tone:e=>e.textMuted},pre_aggregation:{Icon:Ds,tone:e=>e.textMuted},cube:{Icon:Go,tone:e=>e.textSecondary},semantic_model:{Icon:Go,tone:e=>e.textSecondary},saved_query:{Icon:Ig,tone:e=>e.textMuted},provider:{Icon:Bn,tone:e=>e.textMuted},domain:{Icon:Bn,tone:e=>e.textMuted},group:{Icon:Bn,tone:e=>e.textMuted}};function _b(e){var t;if(e.kind==="group"){const n=typeof((t=e.meta)==null?void 0:t.objectKind)=="string"?e.meta.objectKind:"";return So[n]??So.group}return So[e.kind]}function $b({tree:e,themeMode:t,search:n="",onInsert:r,selectionMode:o=!1,selected:i=new Set,onToggleSelection:l,canSelect:a=()=>({allowed:!0})}){const d=Fe[t],c=n.trim().toLowerCase(),f=Jc(e.children??[]).filter(p=>Ms(p,c));return f.length===0?s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:d.textMuted,textAlign:"center"},children:c?"No matches.":"No semantic objects."}):s.jsx(s.Fragment,{children:f.map(p=>s.jsx(Qc,{node:p,t:d,q:c,onInsert:r,depth:0,selectionMode:o,selected:i,onToggleSelection:l,canSelect:a},p.id))})}function Qc({node:e,t,q:n,onInsert:r,depth:o,selectionMode:i,selected:l,onToggleSelection:a,canSelect:d}){var R;const c=(((R=e.children)==null?void 0:R.length)??0)>0,[f,p]=u.useState(o<1||!!n);u.useEffect(()=>{n&&p(!0)},[n]);const h=Rb.has(e.kind),g=_b(e),S=g==null?void 0:g.Icon,x=10+o*13,b=e.kind==="metric"||e.kind==="measure"?"metric":e.kind==="dimension"||e.kind==="time_dimension"?"dimension":null,k=so(e),C=Gc(e),E=k!==C?` · DQL ${k}`:"",v=b?`${b}:${k}`:"",w=b?d(b,k):{allowed:!1};if(!c)return s.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",minWidth:0,borderBottom:`1px solid ${t.cellBorder}`},children:s.jsxs("button",{type:"button",onClick:()=>{i&&b&&w.allowed?a==null||a(b,k):!i&&h&&r(Yo(e))},disabled:i&&!!b&&!w.allowed,title:i&&b?w.allowed?`Select ${e.label} · dbt ${C}${E}`:w.reason||"Not compatible with the current selection":h?`Insert ${Yo(e)} · dbt ${C}${E}`:e.label,style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,boxSizing:"border-box",padding:`5px 6px 5px ${x+15}px`,border:"none",background:"transparent",cursor:i&&b?w.allowed?"pointer":"not-allowed":h?"pointer":"default",textAlign:"left",fontFamily:t.font,color:w.allowed||!b?t.textPrimary:t.textMuted,opacity:i&&b&&!w.allowed?.55:1},children:[i&&b&&s.jsx("input",{type:"checkbox",readOnly:!0,checked:l.has(v),disabled:!w.allowed,style:{accentColor:t.accent,margin:0,flexShrink:0}}),S&&s.jsx(S,{size:13,color:g.tone(t),style:{flexShrink:0}}),s.jsxs("span",{style:{flex:1,minWidth:0,display:"grid",gap:1,overflow:"hidden"},children:[s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5},children:e.label}),C!==e.label?s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:9.5,fontFamily:t.fontMono,color:t.textMuted},children:C}):null]})]})});const A=(e.children??[]).filter(y=>Ms(y,n));return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>p(y=>!y),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,boxSizing:"border-box",padding:`6px 10px 6px ${x}px`,border:"none",borderBottom:`1px solid ${t.cellBorder}`,background:"transparent",cursor:"pointer",textAlign:"left",fontFamily:t.font,color:t.textPrimary},children:[f?s.jsx(Os,{size:13,color:t.textMuted,style:{flexShrink:0}}):s.jsx(oo,{size:13,color:t.textMuted,style:{flexShrink:0}}),S&&s.jsx(S,{size:13,color:g.tone(t),style:{flexShrink:0}}),s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:600},children:e.label}),s.jsx("span",{style:{fontSize:10,color:t.textMuted,flexShrink:0},children:e.count??A.length})]}),f&&A.map(y=>s.jsx(Qc,{node:y,t,q:n,onInsert:r,depth:o+1,selectionMode:i,selected:l,onToggleSelection:a,canSelect:d},y.id))]})}function Ob(e){return[...new Set(e.map(t=>{var n;return((n=t.domain)==null?void 0:n.trim())||"uncategorized"}))].sort((t,n)=>t.localeCompare(n))}function Pb(e,t,n=""){const r=n.trim().toLowerCase();return Array.from(new Map(e.map(o=>[o.path,o])).values()).filter(o=>{var i;return t&&(((i=o.domain)==null?void 0:i.trim())||"uncategorized")!==t?!1:!r||o.name.toLowerCase().includes(r)||(o.description??"").toLowerCase().includes(r)})}var V;(function(e){e.Program="Program",e.Workbook="Workbook",e.Page="Page",e.Dashboard="Dashboard",e.ChartCall="ChartCall",e.FilterCall="FilterCall",e.VariableDecl="VariableDecl",e.ParamDecl="ParamDecl",e.ImportDecl="ImportDecl",e.UseDecl="UseDecl",e.LayoutBlock="LayoutBlock",e.LayoutRow="LayoutRow",e.Decorator="Decorator",e.SQLQuery="SQLQuery",e.NamedArg="NamedArg",e.StringLiteral="StringLiteral",e.NumberLiteral="NumberLiteral",e.BooleanLiteral="BooleanLiteral",e.ArrayLiteral="ArrayLiteral",e.Identifier="Identifier",e.BinaryExpr="BinaryExpr",e.IntervalExpr="IntervalExpr",e.FunctionCall="FunctionCall",e.TemplateString="TemplateString",e.BlockDecl="BlockDecl",e.DomainDecl="DomainDecl",e.TermDecl="TermDecl",e.BusinessViewDecl="BusinessViewDecl",e.BusinessViewInclude="BusinessViewInclude",e.BlockParams="BlockParams",e.BlockVisualization="BlockVisualization",e.BlockTest="BlockTest",e.Digest="Digest",e.Narrative="Narrative"})(V||(V={}));var dn;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(dn||(dn={}));class Db{constructor(){Ce(this,"diagnostics",[])}report(t){this.diagnostics.push(t)}error(t,n,r){this.report({severity:dn.Error,message:t,span:n,hint:r})}warning(t,n,r){this.report({severity:dn.Warning,message:t,span:n,hint:r})}hasErrors(){return this.diagnostics.some(t=>t.severity===dn.Error)}getErrors(){return this.diagnostics.filter(t=>t.severity===dn.Error)}getAll(){return[...this.diagnostics]}clear(){this.diagnostics=[]}format(t){return this.diagnostics.map(n=>Mb(n,t)).join(`
408
-
409
- `)}}function Mb(e,t){const{severity:n,message:r,span:o,hint:i}=e,a=t.split(`
410
- `)[o.start.line-1]??"",d=String(o.start.line),c=" ".repeat(d.length),f=o.start.file?`${o.start.file}:`:"";let p=`${n}: ${r}
411
- `;p+=` --> ${f}${o.start.line}:${o.start.column}
412
- `,p+=`${c} |
413
- `,p+=`${d} | ${a}
414
- `;const h=o.start.column-1,g=Math.max(1,o.start.line===o.end.line?o.end.column-o.start.column:a.length-h);return p+=`${c} | ${" ".repeat(h)}${"^".repeat(g)}`,i&&(p+=`
415
- ${c} = hint: ${i}`),p}class Ib extends Error{constructor(n,r){super(n);Ce(this,"diagnostics");this.diagnostics=r,this.name="DQLSyntaxError"}}var m;(function(e){e.StringLiteral="StringLiteral",e.NumberLiteral="NumberLiteral",e.BooleanLiteral="BooleanLiteral",e.Identifier="Identifier",e.DashboardKeyword="DashboardKeyword",e.WorkbookKeyword="WorkbookKeyword",e.PageKeyword="PageKeyword",e.LetKeyword="LetKeyword",e.ParamKeyword="ParamKeyword",e.ChartKeyword="ChartKeyword",e.FilterKeyword="FilterKeyword",e.IntervalKeyword="IntervalKeyword",e.ImportKeyword="ImportKeyword",e.FromKeyword="FromKeyword",e.UseKeyword="UseKeyword",e.LayoutKeyword="LayoutKeyword",e.RowKeyword="RowKeyword",e.BlockKeyword="BlockKeyword",e.TermKeyword="TermKeyword",e.TermsKeyword="TermsKeyword",e.BusinessViewKeyword="BusinessViewKeyword",e.IncludesKeyword="IncludesKeyword",e.DomainKeyword="DomainKeyword",e.TypeKeyword="TypeKeyword",e.DescriptionKeyword="DescriptionKeyword",e.TagsKeyword="TagsKeyword",e.OwnerKeyword="OwnerKeyword",e.QueryKeyword="QueryKeyword",e.VisualizationKeyword="VisualizationKeyword",e.TestsKeyword="TestsKeyword",e.ParamsKeyword="ParamsKeyword",e.AssertKeyword="AssertKeyword",e.VarKeyword="VarKeyword",e.DefaultKeyword="DefaultKeyword",e.MetricKeyword="MetricKeyword",e.MetricsKeyword="MetricsKeyword",e.DimensionsKeyword="DimensionsKeyword",e.DigestKeyword="DigestKeyword",e.NarrativeKeyword="NarrativeKeyword",e.ColonToken="ColonToken",e.TripleQuoteString="TripleQuoteString",e.GreaterThan="GreaterThan",e.LessThan="LessThan",e.GreaterThanOrEqual="GreaterThanOrEqual",e.LessThanOrEqual="LessThanOrEqual",e.DoubleEquals="DoubleEquals",e.NotEquals="NotEquals",e.InKeyword="InKeyword",e.SQLFragment="SQLFragment",e.AtSign="AtSign",e.LeftParen="LeftParen",e.RightParen="RightParen",e.LeftBrace="LeftBrace",e.RightBrace="RightBrace",e.LeftBracket="LeftBracket",e.RightBracket="RightBracket",e.Comma="Comma",e.Dot="Dot",e.Equals="Equals",e.Plus="Plus",e.Minus="Minus",e.Star="Star",e.Comment="Comment",e.Newline="Newline",e.EOF="EOF"})(m||(m={}));const Lb={dashboard:m.DashboardKeyword,workbook:m.WorkbookKeyword,page:m.PageKeyword,let:m.LetKeyword,param:m.ParamKeyword,chart:m.ChartKeyword,filter:m.FilterKeyword,true:m.BooleanLiteral,false:m.BooleanLiteral,INTERVAL:m.IntervalKeyword,import:m.ImportKeyword,from:m.FromKeyword,use:m.UseKeyword,layout:m.LayoutKeyword,row:m.RowKeyword,block:m.BlockKeyword,term:m.TermKeyword,terms:m.TermsKeyword,business_view:m.BusinessViewKeyword,includes:m.IncludesKeyword,domain:m.DomainKeyword,type:m.TypeKeyword,description:m.DescriptionKeyword,tags:m.TagsKeyword,owner:m.OwnerKeyword,query:m.QueryKeyword,visualization:m.VisualizationKeyword,tests:m.TestsKeyword,params:m.ParamsKeyword,assert:m.AssertKeyword,var:m.VarKeyword,default:m.DefaultKeyword,IN:m.InKeyword,metric:m.MetricKeyword,metrics:m.MetricsKeyword,dimensions:m.DimensionsKeyword,digest:m.DigestKeyword,narrative:m.NarrativeKeyword};function Nb(e){return Lb[e]??m.Identifier}const ko=new Set(["line","bar","kpi","pie","donut","scatter","area","stacked-area","stacked_area","heatmap","table","metric","stacked-bar","stacked_bar","grouped-bar","grouped_bar","combo","histogram","funnel","treemap","tree-map","sankey","flow","sparkline","spark-line","spark","small_multiples","small-multiples","small_multiple","small-multiple","gauge","waterfall","boxplot","geo","forecast"]),Bb={"grouped-bar":"grouped_bar",grouped_bar:"grouped_bar","stacked-bar":"stacked_bar",stacked_bar:"stacked_bar","stacked-area":"area",stacked_area:"area",donut:"pie",forecast:"line","tree-map":"treemap",flow:"sankey","spark-line":"sparkline",spark:"sparkline","small-multiples":"small_multiples",small_multiple:"small_multiples","small-multiple":"small_multiples"};function Fb(e){return Bb[e]??e}const wo=new Set(["dropdown","date_range","text","multi_select","range"]),zb=new Set(["SELECT","WITH"]);class Nr{constructor(t,n){Ce(this,"source");Ce(this,"pos",0);Ce(this,"line",1);Ce(this,"column",1);Ce(this,"file");this.source=t,this.file=n}tokenize(){const t=[];for(;!this.isAtEnd()&&(this.skipWhitespace(),!this.isAtEnd());){const n=this.nextToken();n.type!==m.Comment&&t.push(n)}return t.push(this.makeToken(m.EOF,"",this.location())),t}nextToken(){if(this.skipWhitespace(),this.isAtEnd())return this.makeToken(m.EOF,"",this.location());const t=this.location(),n=this.peek();return n==="/"&&this.peekNext()==="/"?this.readComment(t):n==='"'&&this.peekNext()==='"'&&this.source[this.pos+2]==='"'?this.readTripleQuoteString(t):n==='"'||n==="'"?this.readString(n,t):this.isDigit(n)||n==="-"&&this.isDigit(this.peekNext()??"")?this.readNumber(t):this.isAlpha(n)||n==="_"?this.readIdentifierOrKeyword(t):n===">"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(m.GreaterThanOrEqual,">=",t)):n==="<"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(m.LessThanOrEqual,"<=",t)):n==="="&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(m.DoubleEquals,"==",t)):n==="!"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(m.NotEquals,"!=",t)):this.readPunctuation(t)}static scanSQLBoundary(t,n,r){let o=n,i=r;const l=t.length;for(;o<l;){const d=t[o];if(d==="'"||d==='"'){o=Nr.skipStringInSQL(t,o);continue}if(d==="("){i++,o++;continue}if(d===")"){if(i===1)return{sql:t.substring(n,o).trim(),endOffset:o};i--,o++;continue}if(d===","&&i===1){let c=o+1;for(;c<l&&/\s/.test(t[c]);)c++;if(c<l&&/[a-zA-Z_]/.test(t[c])){let f=c;for(;f<l&&/[a-zA-Z0-9_]/.test(t[f]);)f++;let p=f;for(;p<l&&/\s/.test(t[p]);)p++;if(p<l&&t[p]==="="&&(p+1>=l||t[p+1]!=="="))return{sql:t.substring(n,o).trim(),endOffset:o}}}o++}return{sql:t.substring(n,o).trim(),endOffset:o}}static skipStringInSQL(t,n){const r=t[n];for(n++;n<t.length;){if(t[n]==="\\"){n+=2;continue}if(t[n]===r)return n++,n;n++}return n}readComment(t){let n="";for(;!this.isAtEnd()&&this.peek()!==`
416
- `;)n+=this.advance();return this.makeToken(m.Comment,n,t)}readString(t,n){this.advance();let r="";for(;!this.isAtEnd()&&this.peek()!==t;)if(this.peek()==="\\"){this.advance();const o=this.advance();switch(o){case"n":r+=`
417
- `;break;case"t":r+=" ";break;case"\\":r+="\\";break;case"'":r+="'";break;case'"':r+='"';break;default:r+=o}}else r+=this.advance();return this.isAtEnd()||this.advance(),this.makeToken(m.StringLiteral,r,n)}readNumber(t){let n="";for(this.peek()==="-"&&(n+=this.advance());!this.isAtEnd()&&this.isDigit(this.peek());)n+=this.advance();if(!this.isAtEnd()&&this.peek()==="."&&this.isDigit(this.peekNext()??""))for(n+=this.advance();!this.isAtEnd()&&this.isDigit(this.peek());)n+=this.advance();return this.makeToken(m.NumberLiteral,n,t)}readIdentifierOrKeyword(t){let n="";for(;!this.isAtEnd()&&(this.isAlphaNumeric(this.peek())||this.peek()==="_");)n+=this.advance();const r=Nb(n);return this.makeToken(r,n,t)}readPunctuation(t){const n=this.advance();switch(n){case"(":return this.makeToken(m.LeftParen,n,t);case")":return this.makeToken(m.RightParen,n,t);case"{":return this.makeToken(m.LeftBrace,n,t);case"}":return this.makeToken(m.RightBrace,n,t);case"[":return this.makeToken(m.LeftBracket,n,t);case"]":return this.makeToken(m.RightBracket,n,t);case",":return this.makeToken(m.Comma,n,t);case".":return this.makeToken(m.Dot,n,t);case"=":return this.makeToken(m.Equals,n,t);case"+":return this.makeToken(m.Plus,n,t);case"-":return this.makeToken(m.Minus,n,t);case"*":return this.makeToken(m.Star,n,t);case"@":return this.makeToken(m.AtSign,n,t);case":":return this.makeToken(m.ColonToken,n,t);case">":return this.makeToken(m.GreaterThan,n,t);case"<":return this.makeToken(m.LessThan,n,t);default:return this.makeToken(m.Identifier,n,t)}}skipWhitespace(){for(;!this.isAtEnd();){const t=this.peek();if(t===" "||t===" "||t==="\r"||t===`
418
- `)this.advance();else break}}peek(){return this.source[this.pos]}peekNext(){return this.source[this.pos+1]}advance(){const t=this.source[this.pos];return this.pos++,t===`
419
- `?(this.line++,this.column=1):this.column++,t}isAtEnd(){return this.pos>=this.source.length}isDigit(t){return t>="0"&&t<="9"}isAlpha(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"}isAlphaNumeric(t){return this.isAlpha(t)||this.isDigit(t)}readTripleQuoteString(t){this.advance(),this.advance(),this.advance(),!this.isAtEnd()&&this.peek()===`
420
- `&&this.advance();let n="";for(;!this.isAtEnd();){if(this.peek()==='"'&&this.peekNext()==='"'&&this.source[this.pos+2]==='"')return this.advance(),this.advance(),this.advance(),n=n.replace(/\n\s*$/,""),this.makeToken(m.TripleQuoteString,n,t);n+=this.advance()}return this.makeToken(m.TripleQuoteString,n,t)}location(){return{line:this.line,column:this.column,offset:this.pos,file:this.file}}makeToken(t,n,r){return{type:t,value:n,span:{start:r,end:this.location()}}}}const qb=new Set(["first_asked","last_asked","proposed_contract_id","proposed_domain","proposed_entity","source_question","source_block","source_dql_kind","source_dql_name","source_dql_path","source_dql_hash","source_dql_time_dimension","source_dql_granularity","followup_kind","context_pack_id","route_intent","time_dimension","granularity","draft_path"]),Ub=new Set(["upstream_refs","requested_filters","requested_dimensions","order_by","source_dql_metrics","source_dql_dimensions","source_dql_filters","source_dql_order_by","validation_warnings"]);function Wb(e){return qb.has(e)}function Kb(e){return Ub.has(e)}class Vb{constructor(t,n){Ce(this,"tokens");Ce(this,"pos",0);Ce(this,"source");Ce(this,"file");Ce(this,"reporter");this.source=t,this.file=n,this.reporter=new Db;const r=new Nr(t,n);this.tokens=r.tokenize()}parse(){const t=this.currentSpan(),n=[];for(;!this.isAtEnd();){const r=this.pos;try{const o=this.parseStatement();o&&n.push(o)}catch{this.synchronize()}this.pos===r&&!this.isAtEnd()&&this.advance()}if(this.reporter.hasErrors())throw new Ib(`Parse errors in ${this.file??"<input>"}`,this.reporter.getErrors());return{kind:V.Program,statements:n,span:this.makeSpan(t,this.currentSpan())}}parseStatement(){const t=this.parseDecoratorList();return this.check(m.WorkbookKeyword)?this.parseWorkbook(t):this.check(m.DashboardKeyword)?this.parseDashboard(t):this.check(m.DigestKeyword)?this.parseDigest(t):this.check(m.ChartKeyword)?this.parseChartCall(t):this.check(m.BlockKeyword)?this.parseBlockDecl(t):this.check(m.DomainKeyword)?this.parseDomainDecl(t):this.check(m.TermKeyword)?this.parseTermDecl(t):this.check(m.BusinessViewKeyword)?this.parseBusinessViewDecl(t):this.check(m.ImportKeyword)?(t.length>0&&this.error("Decorators cannot be applied to import statements."),this.parseImportDecl()):(this.check(m.EOF)||this.error(`Unexpected token '${this.current().value}'. Expected 'dashboard', 'digest', 'workbook', 'chart', 'domain', 'block', 'term', 'business_view', or 'import'.`),null)}parseFilterCall(){const t=this.currentSpan();this.expect(m.FilterKeyword),this.expect(m.Dot);const n=this.expect(m.Identifier);wo.has(n.value)||this.reporter.error(`Unknown filter type '${n.value}'. Valid types: ${[...wo].join(", ")}`,n.span,`Did you mean one of: ${[...wo].join(", ")}?`),this.expect(m.LeftParen);let r;const i=this.current().value.toUpperCase();(i==="SELECT"||i==="WITH")&&(r=this.parseSQLQuery());const l=[];for(;(this.check(m.Comma)||!r&&(this.check(m.Identifier)||this.isKeywordUsableAsArgName(this.current().type)))&&(this.check(m.Comma)&&this.advance(),!this.check(m.RightParen));)l.push(this.parseNamedArg());return this.expect(m.RightParen),{kind:V.FilterCall,filterType:n.value,query:r,args:l,span:this.makeSpan(t,this.previousSpan())}}parseDashboard(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(m.DashboardKeyword);const r=this.expect(m.StringLiteral);this.expect(m.LeftBrace);const o=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();){const i=this.parseDecoratorList();if(this.check(m.LetKeyword))i.length>0&&this.error("Decorators cannot be applied to variable declarations."),o.push(this.parseVariableDecl());else if(this.check(m.ParamKeyword))i.length>0&&this.error("Decorators cannot be applied to param declarations."),o.push(this.parseParamDecl());else if(this.check(m.ChartKeyword))o.push(this.parseChartCall(i));else if(this.check(m.FilterKeyword))i.length>0&&this.error("Decorators cannot be applied to filter declarations."),o.push(this.parseFilterCall());else if(this.check(m.UseKeyword))i.length>0&&this.error("Decorators cannot be applied to use declarations."),o.push(this.parseUseDecl());else if(this.check(m.LayoutKeyword))i.length>0&&this.error("Decorators cannot be applied to layout blocks."),o.push(this.parseLayoutBlock());else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside dashboard. Expected 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(m.RightBrace),{kind:V.Dashboard,title:r.value,decorators:t,body:o,span:this.makeSpan(n,this.previousSpan())}}parseDigest(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(m.DigestKeyword);const r=this.expect(m.StringLiteral);this.expect(m.LeftBrace);const o=[];let i;for(;!this.check(m.RightBrace)&&!this.isAtEnd();){const l=this.parseDecoratorList();if(this.check(m.NarrativeKeyword))l.length>0&&this.error("Decorators cannot be applied to narrative blocks."),i&&this.error("A digest can only contain one narrative block."),i=this.parseNarrative();else if(this.check(m.LetKeyword))l.length>0&&this.error("Decorators cannot be applied to variable declarations."),o.push(this.parseVariableDecl());else if(this.check(m.ParamKeyword))l.length>0&&this.error("Decorators cannot be applied to param declarations."),o.push(this.parseParamDecl());else if(this.check(m.ChartKeyword))o.push(this.parseChartCall(l));else if(this.check(m.FilterKeyword))l.length>0&&this.error("Decorators cannot be applied to filter declarations."),o.push(this.parseFilterCall());else if(this.check(m.UseKeyword))l.length>0&&this.error("Decorators cannot be applied to use declarations."),o.push(this.parseUseDecl());else if(this.check(m.LayoutKeyword))l.length>0&&this.error("Decorators cannot be applied to layout blocks."),o.push(this.parseLayoutBlock());else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside digest. Expected 'narrative', 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(m.RightBrace),{kind:V.Digest,title:r.value,decorators:t,narrative:i,body:o,span:this.makeSpan(n,this.previousSpan())}}parseNarrative(){const t=this.currentSpan();this.expect(m.NarrativeKeyword),this.expect(m.LeftBrace);const n=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();)n.push(this.parseNamedArg());return this.expect(m.RightBrace),{kind:V.Narrative,properties:n,span:this.makeSpan(t,this.previousSpan())}}parseChartCall(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(m.ChartKeyword),this.expect(m.Dot);const r=this.currentSpan();let i=this.expect(m.Identifier).value;for(;this.check(m.Minus);)this.advance(),i+=`-${this.expect(m.Identifier).value}`;const l=this.makeSpan(r,this.previousSpan());ko.has(i)||this.reporter.error(`Unknown chart type '${i}'. Valid types: ${[...ko].join(", ")}`,l,`Did you mean one of: ${[...ko].join(", ")}?`);const a=Fb(i);this.expect(m.LeftParen);const d=this.parseSQLQuery(),c=[];for(;this.check(m.Comma)&&(this.advance(),!this.check(m.RightParen));)c.push(this.parseNamedArg());return this.expect(m.RightParen),{kind:V.ChartCall,chartType:a,query:d,args:c,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseSQLQuery(){const t=this.currentSpan(),r=this.current().span.start.offset,{sql:o,endOffset:i}=Nr.scanSQLBoundary(this.source,r,1),l=this.extractInterpolations(o,t);for(;!this.isAtEnd()&&this.current().span.start.offset<i;)this.advance();const a=this.makeSpan(t,this.currentSpan());return{kind:V.SQLQuery,rawSQL:o,interpolations:l,span:a}}extractInterpolations(t,n){const r=[],o=/\$\{(\w+)\}|\{(\w+)\}/g;let i;for(;(i=o.exec(t))!==null;){const l=i[1]||i[2];l&&r.push({variableName:l,offsetInSQL:i.index,span:n})}return r}parseNamedArg(){const t=this.currentSpan(),n=this.current();n.type===m.Identifier||this.isKeywordUsableAsArgName(n.type)?this.advance():(this.error(`Expected argument name, got '${n.value}'.`),this.advance()),this.expect(m.Equals);const r=this.parseExpression();return{kind:V.NamedArg,name:n.value,value:r,span:this.makeSpan(t,this.previousSpan())}}isKeywordUsableAsArgName(t){return t===m.ParamKeyword||t===m.FromKeyword||t===m.LayoutKeyword||t===m.RowKeyword||t===m.UseKeyword||t===m.ImportKeyword||t===m.MetricKeyword||t===m.MetricsKeyword||t===m.TermsKeyword||t===m.IncludesKeyword}parseVariableDecl(){const t=this.currentSpan();this.expect(m.LetKeyword);const n=this.expect(m.Identifier);this.expect(m.Equals);const r=this.parseExpression();return{kind:V.VariableDecl,name:n.value,initializer:r,span:this.makeSpan(t,this.previousSpan())}}parseDecoratorList(){const t=[];for(;this.check(m.AtSign);)t.push(this.parseDecorator());return t}parseDecorator(){const t=this.currentSpan();this.expect(m.AtSign);const n=this.expect(m.Identifier),r=[];if(this.check(m.LeftParen)){if(this.advance(),!this.check(m.RightParen))for(r.push(this.parseExpression());this.check(m.Comma);)this.advance(),r.push(this.parseExpression());this.expect(m.RightParen)}return{kind:V.Decorator,name:n.value,arguments:r,span:this.makeSpan(t,this.previousSpan())}}parseExpression(){let t=this.parsePrimary();for(;this.check(m.Plus)||this.check(m.Minus);){const n=this.advance(),r=this.parsePrimary();t={kind:V.BinaryExpr,operator:n.value,left:t,right:r,span:this.makeSpan(t.span,r.span)}}return t}parsePrimary(){const t=this.current();if(this.check(m.StringLiteral))return this.advance(),{kind:V.StringLiteral,value:t.value,span:t.span};if(this.check(m.NumberLiteral))return this.advance(),{kind:V.NumberLiteral,value:Number(t.value),span:t.span};if(this.check(m.BooleanLiteral))return this.advance(),{kind:V.BooleanLiteral,value:t.value==="true",span:t.span};if(this.check(m.LeftBracket))return this.parseArrayLiteral();if(this.check(m.IntervalKeyword)){const n=this.currentSpan();this.advance();const r=this.expect(m.StringLiteral);return{kind:V.IntervalExpr,value:r.value,span:this.makeSpan(n,this.previousSpan())}}if(this.check(m.Identifier)){this.advance();const n=t.value;return this.check(m.LeftParen)?this.parseFunctionCall(n,t.span):{kind:V.Identifier,name:n,span:t.span}}if(this.check(m.Minus)){const n=this.currentSpan();this.advance();const r=this.expect(m.NumberLiteral);return{kind:V.NumberLiteral,value:-Number(r.value),span:this.makeSpan(n,r.span)}}return this.error(`Unexpected token '${t.value}'. Expected an expression.`),this.advance(),{kind:V.Identifier,name:"__error__",span:t.span}}parseArrayLiteral(){const t=this.currentSpan();this.expect(m.LeftBracket);const n=[];if(!this.check(m.RightBracket))for(n.push(this.parseExpression());this.check(m.Comma)&&(this.advance(),!this.check(m.RightBracket));)n.push(this.parseExpression());return this.expect(m.RightBracket),{kind:V.ArrayLiteral,elements:n,span:this.makeSpan(t,this.previousSpan())}}parseFunctionCall(t,n){this.expect(m.LeftParen);const r=[];if(!this.check(m.RightParen))for(r.push(this.parseExpression());this.check(m.Comma);)this.advance(),r.push(this.parseExpression());return this.expect(m.RightParen),{kind:V.FunctionCall,callee:t,arguments:r,span:this.makeSpan(n,this.previousSpan())}}current(){return this.tokens[this.pos]??this.tokens[this.tokens.length-1]}previous(){return this.tokens[this.pos-1]??this.tokens[0]}check(t){return this.current().type===t}advance(){const t=this.current();return this.isAtEnd()||this.pos++,t}skipBalancedBlock(){if(!this.check(m.LeftBrace))return;let t=0;for(;!this.isAtEnd();){if(this.check(m.LeftBrace)){t+=1,this.advance();continue}if(this.check(m.RightBrace)){if(t-=1,this.advance(),t<=0)return;continue}this.advance()}}expect(t){if(this.check(t))return this.advance();const n=this.current();return this.error(`Expected ${t} but found '${n.value}' (${n.type}).`),{type:t,value:"",span:n.span}}expectStringLike(){return this.check(m.StringLiteral)||this.check(m.TripleQuoteString)?this.advance():this.expect(m.StringLiteral)}isAtEnd(){return this.current().type===m.EOF}error(t){this.reporter.error(t,this.currentSpan())}currentSpan(){return this.current().span}previousSpan(){return this.previous().span}makeSpan(t,n){return{start:t.start,end:n.end}}parseDomainDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(m.DomainKeyword);const r=this.expect(m.StringLiteral);this.expect(m.LeftBrace);let o,i,l,a,d,c,f,p,h,g,S,x,b,k,C,E,v,w,A;for(;!this.check(m.RightBrace)&&!this.isAtEnd();)if(this.check(m.OwnerKeyword))this.advance(),this.expect(m.Equals),i=this.expect(m.StringLiteral).value;else if(this.check(m.DescriptionKeyword))this.advance(),this.expect(m.Equals),S=this.expectStringLike().value;else if(this.check(m.TagsKeyword))this.advance(),this.expect(m.Equals),h=this.parseStringArrayValues();else if(this.check(m.Identifier)&&(this.current().value==="id"||this.current().value==="parent"||this.current().value==="businessOwner"||this.current().value==="boundedContext"||this.current().value==="sourceSystems"||this.current().value==="primaryTerms"||this.current().value==="reviewCadence"||this.current().value==="businessOutcome"||this.current().value==="inScope"||this.current().value==="outOfScope"||this.current().value==="dbtGroups"||this.current().value==="dbtPaths"||this.current().value==="dbtTags"||this.current().value==="semanticDomains"||this.current().value==="semanticTags"||this.current().value==="exports")){const R=this.advance();this.expect(m.Equals),R.value==="id"?o=this.expect(m.StringLiteral).value:R.value==="parent"?l=this.expect(m.StringLiteral).value:R.value==="businessOwner"?a=this.expect(m.StringLiteral).value:R.value==="boundedContext"?d=this.expectStringLike().value:R.value==="sourceSystems"?c=this.parseStringArrayValues():R.value==="primaryTerms"?f=this.parseStringArrayValues():R.value==="reviewCadence"?p=this.expect(m.StringLiteral).value:R.value==="businessOutcome"?g=this.expect(m.StringLiteral).value:R.value==="inScope"?x=this.parseStringArrayValues():R.value==="outOfScope"?b=this.parseStringArrayValues():R.value==="dbtGroups"?k=this.parseStringArrayValues():R.value==="dbtPaths"?C=this.parseStringArrayValues():R.value==="dbtTags"?E=this.parseStringArrayValues():R.value==="semanticDomains"?v=this.parseStringArrayValues():R.value==="semanticTags"?w=this.parseStringArrayValues():R.value==="exports"&&(A=this.parseStringArrayValues())}else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside domain. Expected 'id', 'parent', 'owner', 'businessOwner', 'boundedContext', 'sourceSystems', 'primaryTerms', 'reviewCadence', 'tags', 'businessOutcome', 'description', or '}'.`),this.advance()}return this.expect(m.RightBrace),{kind:V.DomainDecl,name:r.value,id:o,parent:l,owner:i,businessOwner:a,boundedContext:d,sourceSystems:c,primaryTerms:f,reviewCadence:p,tags:h,businessOutcome:g,description:S,inScope:x,outOfScope:b,dbtGroups:k,dbtPaths:C,dbtTags:E,semanticDomains:v,semanticTags:w,exports:A,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseTermDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(m.TermKeyword);const r=this.expect(m.StringLiteral);this.expect(m.LeftBrace);let o,i,l,a,d,c,f,p,h,g,S,x,b,k,C;for(;!this.check(m.RightBrace)&&!this.isAtEnd();)if(this.check(m.DomainKeyword))this.advance(),this.expect(m.Equals),o=this.expect(m.StringLiteral).value;else if(this.check(m.TypeKeyword))this.advance(),this.expect(m.Equals),i=this.expect(m.StringLiteral).value;else if(this.check(m.DescriptionKeyword))this.advance(),this.expect(m.Equals),a=this.expectStringLike().value;else if(this.check(m.TagsKeyword))this.advance(),this.expect(m.Equals),d=this.parseStringArrayValues();else if(this.check(m.OwnerKeyword))this.advance(),this.expect(m.Equals),c=this.expect(m.StringLiteral).value;else if(this.check(m.Identifier)&&(this.current().value==="status"||this.current().value==="identifiers"||this.current().value==="synonyms"||this.current().value==="metricRefs"||this.current().value==="businessOutcome"||this.current().value==="businessOwner"||this.current().value==="decisionUse"||this.current().value==="reviewCadence"||this.current().value==="businessRules"||this.current().value==="caveats")){const E=this.advance();this.expect(m.Equals),E.value==="status"?l=this.expect(m.StringLiteral).value:E.value==="identifiers"?f=this.parseStringArrayValues():E.value==="synonyms"?p=this.parseStringArrayValues():E.value==="metricRefs"?h=this.parseStringArrayValues():E.value==="businessOutcome"?g=this.expect(m.StringLiteral).value:E.value==="businessOwner"?S=this.expect(m.StringLiteral).value:E.value==="decisionUse"?x=this.expect(m.StringLiteral).value:E.value==="reviewCadence"?b=this.expect(m.StringLiteral).value:E.value==="businessRules"?k=this.parseStringArrayValues():E.value==="caveats"&&(C=this.parseStringArrayValues())}else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside term. Expected 'domain', 'type', 'status', 'description', 'tags', 'owner', 'identifiers', 'synonyms', 'metricRefs', 'businessOutcome', 'businessOwner', 'decisionUse', 'reviewCadence', 'businessRules', 'caveats', or '}'.`),this.advance()}return this.expect(m.RightBrace),{kind:V.TermDecl,name:r.value,domain:o,termType:i,status:l,description:a,tags:d,owner:c,identifiers:f,synonyms:p,metricRefs:h,businessOutcome:g,businessOwner:S,decisionUse:x,reviewCadence:b,businessRules:k,caveats:C,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseBusinessViewDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(m.BusinessViewKeyword);const r=this.expect(m.StringLiteral);this.expect(m.LeftBrace);let o,i,l,a,d,c,f,p,h,g,S,x,b=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();)if(this.check(m.DomainKeyword))this.advance(),this.expect(m.Equals),o=this.expect(m.StringLiteral).value;else if(this.check(m.DescriptionKeyword))this.advance(),this.expect(m.Equals),l=this.expectStringLike().value;else if(this.check(m.TagsKeyword))this.advance(),this.expect(m.Equals),a=this.parseStringArrayValues();else if(this.check(m.OwnerKeyword))this.advance(),this.expect(m.Equals),d=this.expect(m.StringLiteral).value;else if(this.check(m.TermsKeyword))this.advance(),this.expect(m.Equals),c=this.parseStringArrayValues();else if(this.check(m.IncludesKeyword))b=this.parseBusinessViewIncludes();else if(this.check(m.Identifier)&&(this.current().value==="status"||this.current().value==="businessOutcome"||this.current().value==="businessOwner"||this.current().value==="decisionUse"||this.current().value==="reviewCadence"||this.current().value==="businessRules"||this.current().value==="caveats")){const k=this.advance();this.expect(m.Equals),k.value==="status"?i=this.expect(m.StringLiteral).value:k.value==="businessOutcome"?f=this.expect(m.StringLiteral).value:k.value==="businessOwner"?p=this.expect(m.StringLiteral).value:k.value==="decisionUse"?h=this.expect(m.StringLiteral).value:k.value==="reviewCadence"?g=this.expect(m.StringLiteral).value:k.value==="businessRules"?S=this.parseStringArrayValues():k.value==="caveats"&&(x=this.parseStringArrayValues())}else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside business_view. Expected 'domain', 'status', 'description', 'tags', 'owner', 'terms', 'businessOutcome', 'businessOwner', 'decisionUse', 'reviewCadence', 'businessRules', 'caveats', 'includes', or '}'.`),this.advance()}return this.expect(m.RightBrace),{kind:V.BusinessViewDecl,name:r.value,domain:o,status:i,description:l,tags:a,owner:d,termRefs:c,businessOutcome:f,businessOwner:p,decisionUse:h,reviewCadence:g,businessRules:S,caveats:x,includes:b,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseBusinessViewIncludes(){this.expect(m.IncludesKeyword),this.expect(m.LeftBrace);const t=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan();if(this.check(m.BlockKeyword)){this.advance();const r=this.expect(m.StringLiteral);t.push({kind:V.BusinessViewInclude,refType:"block",name:r.value,span:this.makeSpan(n,this.previousSpan())})}else if(this.check(m.BusinessViewKeyword)){this.advance();const r=this.expect(m.StringLiteral);t.push({kind:V.BusinessViewInclude,refType:"business_view",name:r.value,span:this.makeSpan(n,this.previousSpan())})}else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside includes. Expected 'block', 'business_view', or '}'.`),this.advance()}}return this.expect(m.RightBrace),t}parseStringArrayValues(){const t=this.parseArrayLiteral();return t.kind!==V.ArrayLiteral?[]:t.elements.filter(n=>n.kind===V.StringLiteral).map(n=>n.value)}parseBlockDecl(t){var de;const n=t.length>0?t[0].span:this.currentSpan();this.expect(m.BlockKeyword);const r=this.expect(m.StringLiteral);this.expect(m.LeftBrace);let o,i,l,a,d,c,f,p,h,g,S,x,b,k,C,E,v,w,A,R,y,M,$,T,L,I,G,Y,P,q,O,W,se,H,te,J,B,ne,ce,re,ge,ye,Ae,ze,Ie,be,ue,Le,qe,$e,De,Ze,ft,st,et,Et,Bt,Ft,zt,qt,Ut,F,ee,Te;for(;!this.check(m.RightBrace)&&!this.isAtEnd();)if(this.check(m.DomainKeyword))this.advance(),this.expect(m.Equals),o=this.expect(m.StringLiteral).value;else if(this.check(m.TypeKeyword)){this.advance(),this.expect(m.Equals);const K=this.expect(m.StringLiteral).value;K==="semantic"||K==="custom"?i=K:(this.error(`Block type must be "semantic" or "custom", got "${K}". Use type = "semantic" for dbt metric blocks or type = "custom" for SQL blocks.`),i="custom")}else if(this.check(m.MetricKeyword))this.advance(),this.expect(m.Equals),l=this.expect(m.StringLiteral).value;else if(this.check(m.MetricsKeyword)){this.advance(),this.expect(m.Equals);const Q=this.parseArrayLiteral();Q.kind===V.ArrayLiteral&&(a=Q.elements.filter(K=>K.kind===V.StringLiteral).map(K=>K.value))}else if(this.check(m.DimensionsKeyword)){this.advance(),this.expect(m.Equals);const Q=this.parseArrayLiteral();Q.kind===V.ArrayLiteral&&(d=Q.elements.filter(K=>K.kind===V.StringLiteral).map(K=>K.value))}else if(this.check(m.DescriptionKeyword))this.advance(),this.expect(m.Equals),c=this.expectStringLike().value;else if(this.check(m.TagsKeyword)){this.advance(),this.expect(m.Equals);const Q=this.parseArrayLiteral();Q.kind===V.ArrayLiteral&&(f=Q.elements.filter(K=>K.kind===V.StringLiteral).map(K=>K.value))}else if(this.check(m.OwnerKeyword))this.advance(),this.expect(m.Equals),p=this.expect(m.StringLiteral).value;else if(this.check(m.TermsKeyword))this.advance(),this.expect(m.Equals),h=this.parseStringArrayValues();else if(this.check(m.Identifier)&&(this.current().value==="grain"||this.current().value==="pattern"||this.current().value==="entities"||this.current().value==="outputs"||this.current().value==="allowedFilters"||this.current().value==="sourceSystems"||this.current().value==="replacementFor")){const Q=this.advance();this.expect(m.Equals),Q.value==="pattern"?g=this.expect(m.StringLiteral).value:Q.value==="grain"?S=this.expect(m.StringLiteral).value:Q.value==="entities"?x=this.parseStringArrayValues():Q.value==="outputs"?b=this.parseStringArrayValues():Q.value==="allowedFilters"?k=this.parseStringArrayValues():Q.value==="sourceSystems"?v=this.parseStringArrayValues():Q.value==="replacementFor"&&(w=this.parseStringArrayValues())}else if(this.check(m.ParamsKeyword))A=this.parseBlockParams();else if(this.check(m.Identifier)&&this.current().value==="parameterPolicy")C=this.parseBlockParameterPolicy();else if(this.check(m.Identifier)&&this.current().value==="filterBindings")E=this.parseBlockFilterBindings();else if(this.check(m.QueryKeyword))if(this.advance(),this.check(m.LeftBrace))R=this.parseLegacyBlockQuerySection();else if(this.expect(m.Equals),this.check(m.TripleQuoteString)){const Q=this.advance(),K=this.extractInterpolations(Q.value,Q.span);R={kind:V.SQLQuery,rawSQL:Q.value,interpolations:K,span:Q.span}}else R=this.parseSQLQuery();else if(this.check(m.VisualizationKeyword))y=this.parseBlockVisualization();else if(this.check(m.TestsKeyword))M=this.parseBlockTests();else{if(this.check(m.RightBrace))break;if(this.check(m.Identifier)&&this.current().value==="status")this.advance(),this.expect(m.Equals),W=this.expect(m.StringLiteral).value;else if(this.check(m.Identifier)&&this.current().value==="datalex_contract")this.advance(),this.expect(m.Equals),se=this.expect(m.StringLiteral).value;else if(this.check(m.Identifier)&&(this.current().value==="asked_times"||this.current().value==="limit"||this.current().value==="source_dql_limit")){const Q=this.advance();this.expect(m.Equals);const K=this.expect(m.NumberLiteral);Q.value==="asked_times"?H=Number(K.value):Q.value==="limit"?Ft=Number(K.value):ee=Number(K.value)}else if(this.check(m.Identifier)&&Wb(this.current().value)){const Q=this.advance();this.expect(m.Equals);const K=this.expect(m.StringLiteral);switch(Q.value){case"first_asked":te=K.value;break;case"last_asked":J=K.value;break;case"proposed_contract_id":B=K.value;break;case"proposed_domain":ne=K.value;break;case"proposed_entity":ce=K.value;break;case"source_question":re=K.value;break;case"source_block":ge=K.value;break;case"source_dql_kind":ye=K.value;break;case"source_dql_name":Ae=K.value;break;case"source_dql_path":ze=K.value;break;case"source_dql_hash":Ie=K.value;break;case"source_dql_time_dimension":be=K.value;break;case"source_dql_granularity":ue=K.value;break;case"followup_kind":Le=K.value;break;case"context_pack_id":qe=K.value;break;case"route_intent":$e=K.value;break;case"time_dimension":De=K.value;break;case"granularity":Ze=K.value;break;case"draft_path":ft=K.value;break}}else if(this.check(m.Identifier)&&Kb(this.current().value)){const Q=this.advance();this.expect(m.Equals);const K=this.parseStringArrayValues();switch(Q.value){case"upstream_refs":st=K;break;case"requested_filters":et=K;break;case"requested_dimensions":Et=K;break;case"order_by":Bt=K;break;case"source_dql_metrics":zt=K;break;case"source_dql_dimensions":qt=K;break;case"source_dql_filters":Ut=K;break;case"source_dql_order_by":F=K;break;case"validation_warnings":Te=K;break}}else if(this.check(m.Identifier)&&(this.current().value==="llmContext"||this.current().value==="invariants"||this.current().value==="examples"||this.current().value==="businessOutcome"||this.current().value==="businessOwner"||this.current().value==="decisionUse"||this.current().value==="reviewCadence"||this.current().value==="businessRules"||this.current().value==="caveats")){const Q=this.advance();if(this.expect(m.Equals),Q.value==="llmContext")$=this.expect(m.StringLiteral).value;else if(Q.value==="invariants"){const K=this.parseArrayLiteral();K.kind===V.ArrayLiteral&&(T=K.elements.filter(Se=>Se.kind===V.StringLiteral).map(Se=>Se.value))}else if(Q.value==="examples"){this.expect(m.LeftBracket);const K=[];for(;!this.check(m.RightBracket)&&!this.isAtEnd();){this.expect(m.LeftBrace);let Se,wn;for(;!this.check(m.RightBrace)&&!this.isAtEnd();){const en=this.current();if(en.type!==m.Identifier){this.error(`Expected 'question' or 'sql' in example entry, got '${en.value}'.`),this.advance();continue}this.advance(),this.expect(m.Equals);const nr=this.expect(m.StringLiteral);en.value==="question"?Se=nr.value:en.value==="sql"&&(wn=nr.value),this.check(m.Comma)&&this.advance()}this.expect(m.RightBrace),Se&&K.push(wn?{question:Se,sql:wn}:{question:Se}),this.check(m.Comma)&&this.advance()}this.expect(m.RightBracket),K.length>0&&(L=K)}else if(Q.value==="businessOutcome")I=this.expect(m.StringLiteral).value;else if(Q.value==="businessOwner")G=this.expect(m.StringLiteral).value;else if(Q.value==="decisionUse")Y=this.expect(m.StringLiteral).value;else if(Q.value==="reviewCadence")P=this.expect(m.StringLiteral).value;else if(Q.value==="businessRules"){const K=this.parseArrayLiteral();K.kind===V.ArrayLiteral&&(q=K.elements.filter(Se=>Se.kind===V.StringLiteral).map(Se=>Se.value))}else if(Q.value==="caveats"){const K=this.parseArrayLiteral();K.kind===V.ArrayLiteral&&(O=K.elements.filter(Se=>Se.kind===V.StringLiteral).map(Se=>Se.value))}}else{if(this.check(m.Identifier)&&((de=this.tokens[this.pos+1])==null?void 0:de.type)===m.LeftBrace){const Q=this.current().value;this.error(`Unexpected nested section '${Q}' inside block. Unknown block sections are skipped during parse recovery.`),this.advance(),this.skipBalancedBlock();continue}this.error(`Unexpected token '${this.current().value}' inside block. Expected 'domain', 'type', 'status', 'datalex_contract', 'metric', 'metrics', 'dimensions', 'description', 'tags', 'owner', 'terms', 'pattern', 'grain', 'entities', 'outputs', 'allowedFilters', 'parameterPolicy', 'filterBindings', 'sourceSystems', 'replacementFor', 'params', 'query', 'visualization', 'tests', 'llmContext', 'invariants', 'examples', 'businessOutcome', 'businessOwner', 'decisionUse', 'reviewCadence', 'businessRules', 'caveats', Tier-2 draft metadata fields, or '}'.`),this.advance()}}return i||(i="custom",this.reporter.warning(`Block "${r.value}" is missing a type declaration. DQL treated it as type = "custom" for backward compatibility.`,r.span)),this.expect(m.RightBrace),{kind:V.BlockDecl,name:r.value,domain:o,blockType:i,metricRef:l,metricsRef:a,dimensionsRef:i==="semantic"?d:void 0,description:c,tags:f,owner:p,termRefs:h,pattern:g,grain:S,entities:x,outputs:b,dimensions:i==="semantic"?void 0:d,allowedFilters:k,parameterPolicy:C,filterBindings:E,sourceSystems:v,replacementFor:w,params:A,query:R,visualization:y,tests:M,decorators:t,llmContext:$,invariants:T,examples:L,businessOutcome:I,businessOwner:G,decisionUse:Y,reviewCadence:P,businessRules:q,caveats:O,status:W,datalexContract:se,askedTimes:H,firstAsked:te,lastAsked:J,proposedContractId:B,proposedDomain:ne,proposedEntity:ce,sourceQuestion:re,sourceBlock:ge,sourceDqlKind:ye,sourceDqlName:Ae,sourceDqlPath:ze,sourceDqlHash:Ie,sourceDqlTimeDimension:be,sourceDqlGranularity:ue,followupKind:Le,contextPackId:qe,routeIntent:$e,timeDimension:De,granularity:Ze,draftPath:ft,upstreamRefs:st,requestedFilters:et,requestedDimensions:Et,orderBy:Bt,limit:Ft,sourceDqlMetrics:zt,sourceDqlDimensions:qt,sourceDqlFilters:Ut,sourceDqlOrderBy:F,sourceDqlLimit:ee,validationWarnings:Te,span:this.makeSpan(n,this.previousSpan())}}parseLegacyBlockQuerySection(){const t=this.currentSpan();this.expect(m.LeftBrace);let n;for(;!this.check(m.RightBrace)&&!this.isAtEnd();)if(this.check(m.Identifier)&&this.current().value==="sql")if(this.advance(),this.expect(m.Equals),this.check(m.TripleQuoteString)){const r=this.advance(),o=this.extractInterpolations(r.value,r.span);n={kind:V.SQLQuery,rawSQL:r.value,interpolations:o,span:r.span}}else n=this.parseSQLQuery();else this.check(m.Identifier)&&zb.has(this.current().value.toUpperCase())?n=this.parseSQLQuery():(this.error(`Unexpected token '${this.current().value}' inside query section. Expected 'sql' or inline SQL.`),this.advance());return this.expect(m.RightBrace),n||this.reporter.error('Query section must contain sql = """...""" or inline SQL.',this.makeSpan(t,this.previousSpan())),n}parseBlockParams(){var r;const t=this.currentSpan();this.expect(m.ParamsKeyword),this.expect(m.LeftBrace);const n=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();){const o=this.currentSpan(),i=this.current();if(i.type===m.Identifier||this.isBlockFieldKeyword(i.type))this.advance();else{this.error(`Expected parameter name, got '${i.value}'.`),this.advance();continue}let l;if(this.check(m.ColonToken)){this.advance();let c=this.expect(m.Identifier).value;this.check(m.LeftBracket)&&((r=this.tokens[this.pos+1])==null?void 0:r.type)===m.RightBracket&&(this.advance(),this.advance(),c+="[]");const f=["string","number","boolean","date","string[]","number[]","date[]"];f.includes(c)?l=c:this.error(`Invalid block parameter type '${c}'. Valid types: ${f.join(", ")}`)}let a;this.check(m.Equals)&&(this.advance(),a=this.parseExpression()),n.push({name:i.value,paramType:l,initializer:a,span:this.makeSpan(o,this.previousSpan())})}return this.expect(m.RightBrace),{kind:V.BlockParams,params:n,span:this.makeSpan(t,this.previousSpan())}}parseBlockParameterPolicy(){const t=[];for(this.expect(m.Identifier),this.expect(m.LeftBrace);!this.check(m.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan(),r=this.current();if(r.type===m.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected parameter name inside parameterPolicy, got '${r.value}'.`),this.advance();continue}this.expect(m.Equals);const o=this.expectStringLike();t.push({name:r.value,policy:o.value,span:this.makeSpan(n,this.previousSpan())})}return this.expect(m.RightBrace),t}parseBlockFilterBindings(){const t=[];for(this.expect(m.Identifier),this.expect(m.LeftBrace);!this.check(m.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan(),r=this.current();if(r.type===m.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected business filter name inside filterBindings, got '${r.value}'.`),this.advance();continue}this.expect(m.Equals);const o=this.expectStringLike();t.push({filter:r.value,binding:o.value,span:this.makeSpan(n,this.previousSpan())})}return this.expect(m.RightBrace),t}parseBlockVisualization(){const t=this.currentSpan();this.expect(m.VisualizationKeyword),this.expect(m.LeftBrace);const n=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();){const r=this.currentSpan(),o=this.current();if(o.type===m.Identifier||this.isBlockFieldKeyword(o.type))this.advance();else{this.error(`Expected property name, got '${o.value}'.`),this.advance();continue}this.expect(m.Equals);const i=this.parseExpression();n.push({kind:V.NamedArg,name:o.value,value:i,span:this.makeSpan(r,this.previousSpan())})}return this.expect(m.RightBrace),{kind:V.BlockVisualization,properties:n,span:this.makeSpan(t,this.previousSpan())}}parseBlockTests(){this.currentSpan(),this.expect(m.TestsKeyword),this.expect(m.LeftBrace);const t=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();)if(this.check(m.AssertKeyword)){const n=this.currentSpan();this.advance();const r=this.current();if(r.type===m.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected field name after 'assert', got '${r.value}'.`),this.advance();continue}let o;if(this.check(m.GreaterThan))this.advance(),o=">";else if(this.check(m.LessThan))this.advance(),o="<";else if(this.check(m.GreaterThanOrEqual))this.advance(),o=">=";else if(this.check(m.LessThanOrEqual))this.advance(),o="<=";else if(this.check(m.DoubleEquals))this.advance(),o="==";else if(this.check(m.NotEquals))this.advance(),o="!=";else if(this.check(m.InKeyword))this.advance(),o="IN";else{this.error(`Expected comparison operator (>, <, >=, <=, ==, !=, IN) after field name, got '${this.current().value}'.`),this.advance();continue}const i=this.parseExpression();t.push({kind:V.BlockTest,field:r.value,operator:o,expected:i,span:this.makeSpan(n,this.previousSpan())})}else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside tests. Expected 'assert' or '}'.`),this.advance()}return this.expect(m.RightBrace),t}isBlockFieldKeyword(t){return t===m.DomainKeyword||t===m.TypeKeyword||t===m.MetricKeyword||t===m.DescriptionKeyword||t===m.TagsKeyword||t===m.OwnerKeyword||t===m.TermsKeyword||t===m.ChartKeyword||t===m.QueryKeyword||t===m.DefaultKeyword||t===m.FromKeyword}parseWorkbook(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(m.WorkbookKeyword);const r=this.expect(m.StringLiteral);this.expect(m.LeftBrace);const o=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();)if(this.check(m.PageKeyword))o.push(this.parsePage());else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside workbook. Expected 'page' or '}'.`),this.advance()}return this.expect(m.RightBrace),{kind:V.Workbook,title:r.value,decorators:t,pages:o,span:this.makeSpan(n,this.previousSpan())}}parsePage(){const t=this.currentSpan();this.expect(m.PageKeyword);const n=this.expect(m.StringLiteral);this.expect(m.LeftBrace);const r=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();){const o=this.parseDecoratorList();if(this.check(m.LetKeyword))o.length>0&&this.error("Decorators cannot be applied to variable declarations."),r.push(this.parseVariableDecl());else if(this.check(m.ParamKeyword))o.length>0&&this.error("Decorators cannot be applied to param declarations."),r.push(this.parseParamDecl());else if(this.check(m.ChartKeyword))r.push(this.parseChartCall(o));else if(this.check(m.FilterKeyword))o.length>0&&this.error("Decorators cannot be applied to filter declarations."),r.push(this.parseFilterCall());else if(this.check(m.UseKeyword))o.length>0&&this.error("Decorators cannot be applied to use declarations."),r.push(this.parseUseDecl());else if(this.check(m.LayoutKeyword))o.length>0&&this.error("Decorators cannot be applied to layout blocks."),r.push(this.parseLayoutBlock());else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside page. Expected 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(m.RightBrace),{kind:V.Page,title:n.value,body:r,span:this.makeSpan(t,this.previousSpan())}}parseParamDecl(){const t=this.currentSpan();this.expect(m.ParamKeyword);const n=this.expect(m.Identifier);let r="string";if(this.check(m.ColonToken)){this.advance();const i=this.expect(m.Identifier),l=["string","number","boolean","date"];l.includes(i.value)?r=i.value:this.reporter.error(`Invalid param type '${i.value}'. Valid types: ${l.join(", ")}`,i.span)}let o;return this.check(m.Equals)&&(this.advance(),o=this.parseExpression()),{kind:V.ParamDecl,name:n.value,paramType:r,defaultValue:o,span:this.makeSpan(t,this.previousSpan())}}parseImportDecl(){const t=this.currentSpan();this.expect(m.ImportKeyword),this.expect(m.LeftBrace);const n=[];if(!this.check(m.RightBrace))for(n.push(this.expect(m.Identifier).value);this.check(m.Comma)&&(this.advance(),!this.check(m.RightBrace));)n.push(this.expect(m.Identifier).value);this.expect(m.RightBrace),this.expect(m.FromKeyword);const r=this.expect(m.StringLiteral);return{kind:V.ImportDecl,names:n,path:r.value,span:this.makeSpan(t,this.previousSpan())}}parseUseDecl(){const t=this.currentSpan();this.expect(m.UseKeyword);let n;return this.check(m.Identifier)||this.check(m.StringLiteral)?n=this.advance():n=this.expect(m.Identifier),{kind:V.UseDecl,name:n.value,span:this.makeSpan(t,this.previousSpan())}}parseLayoutBlock(){const t=this.currentSpan();this.expect(m.LayoutKeyword);let n=12;if(this.check(m.LeftParen)){this.advance();const o=[];if(!this.check(m.RightParen))for(o.push(this.parseNamedArg());this.check(m.Comma)&&(this.advance(),!this.check(m.RightParen));)o.push(this.parseNamedArg());this.expect(m.RightParen);const i=o.find(l=>l.name==="columns");i&&i.value.kind===V.NumberLiteral&&(n=i.value.value)}this.expect(m.LeftBrace);const r=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();)if(this.check(m.RowKeyword))r.push(this.parseLayoutRow());else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside layout. Expected 'row' or '}'.`),this.advance()}return this.expect(m.RightBrace),{kind:V.LayoutBlock,columns:n,rows:r,span:this.makeSpan(t,this.previousSpan())}}parseLayoutRow(){const t=this.currentSpan();this.expect(m.RowKeyword),this.expect(m.LeftBrace);const n=[];for(;!this.check(m.RightBrace)&&!this.isAtEnd();){const r=this.parseDecoratorList();let o;if(this.check(m.ChartKeyword))o=this.parseChartCall(r);else if(this.check(m.FilterKeyword))r.length>0&&this.error("Decorators cannot be applied to filter declarations."),o=this.parseFilterCall();else{if(this.check(m.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside row. Expected 'chart', 'filter', or '}'.`),this.advance();continue}let i;if(this.check(m.Identifier)&&this.current().value==="span"){this.advance();const l=this.expect(m.NumberLiteral);i=Number(l.value)}n.push({node:o,span:i})}return this.expect(m.RightBrace),{kind:V.LayoutRow,items:n,span:this.makeSpan(t,this.previousSpan())}}synchronize(){for(;!this.isAtEnd();){const t=this.current();if(t.type===m.DashboardKeyword||t.type===m.WorkbookKeyword||t.type===m.ChartKeyword||t.type===m.FilterKeyword||t.type===m.ImportKeyword||t.type===m.BlockKeyword||t.type===m.TermKeyword||t.type===m.BusinessViewKeyword||t.type===m.AtSign||t.type===m.RightBrace)return;this.advance()}}}function Hb(e,t){return new Vb(e,t).parse()}function Gb(e,t={}){const n=Hb(e);return Jb(n,t)}function Jb(e,t={}){const n={indentUnit:t.indent??" "},r=e.statements.map(o=>Qb(o,0,n)).join(`
421
-
422
- `).trimEnd();return t.finalNewline===!1?r:`${r}
423
- `}function D(e,t){return t.indentUnit.repeat(e)}function Qb(e,t,n){switch(e.kind){case V.Dashboard:return Yb(e,t,n);case V.ChartCall:return Ls(e,t,n);case V.Workbook:return ev(e,t,n);case V.ImportDecl:return nv(e,t,n);case V.DomainDecl:return cv(e,t,n);case V.BlockDecl:return lv(e,t,n);case V.TermDecl:return dv(e,t,n);case V.BusinessViewDecl:return uv(e,t,n);case V.Digest:return Xb(e,t,n);default:return""}}function Yb(e,t,n){const r=[];r.push(...Nt(e.decorators,t,n)),r.push(`${D(t,n)}dashboard ${U(e.title)} {`);for(const o of e.body)r.push(Is(o,t+1,n));return r.push(`${D(t,n)}}`),r.join(`
424
- `)}function Xb(e,t,n){const r=[];r.push(...Nt(e.decorators,t,n)),r.push(`${D(t,n)}digest ${U(e.title)} {`),e.narrative&&r.push(Zb(e.narrative,t+1,n));for(const o of e.body)r.push(Is(o,t+1,n));return r.push(`${D(t,n)}}`),r.join(`
425
- `)}function Zb(e,t,n){const r=[];r.push(`${D(t,n)}narrative {`);for(const o of e.properties)r.push(`${D(t+1,n)}${Ns(o)}`);return r.push(`${D(t,n)}}`),r.join(`
426
- `)}function ev(e,t,n){const r=[];r.push(...Nt(e.decorators,t,n)),r.push(`${D(t,n)}workbook ${U(e.title)} {`);for(const o of e.pages)r.push(tv(o,t+1,n));return r.push(`${D(t,n)}}`),r.join(`
427
- `)}function tv(e,t,n){const r=[];r.push(`${D(t,n)}page ${U(e.title)} {`);for(const o of e.body)r.push(Is(o,t+1,n));return r.push(`${D(t,n)}}`),r.join(`
428
- `)}function Is(e,t,n){switch(e.kind){case V.VariableDecl:return ov(e,t,n);case V.ParamDecl:return sv(e,t,n);case V.ChartCall:return Ls(e,t,n);case V.FilterCall:return Yc(e,t,n);case V.UseDecl:return rv(e,t,n);case V.LayoutBlock:return iv(e,t,n);default:return""}}function nv(e,t,n){return`${D(t,n)}import { ${e.names.join(", ")} } from ${U(e.path)}`}function rv(e,t,n){const r=/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.name);return`${D(t,n)}use ${r?e.name:U(e.name)}`}function ov(e,t,n){return`${D(t,n)}let ${e.name} = ${ct(e.initializer)}`}function sv(e,t,n){const r=`: ${e.paramType}`,o=e.defaultValue?` = ${ct(e.defaultValue)}`:"";return`${D(t,n)}param ${e.name}${r}${o}`}function Nt(e,t,n){return e.map(r=>{if(r.arguments.length===0)return`${D(t,n)}@${r.name}`;const o=r.arguments.map(i=>ct(i)).join(", ");return`${D(t,n)}@${r.name}(${o})`})}function Ls(e,t,n){return Xc(`chart.${e.chartType}`,e.decorators,e.query,e.args,t,n)}function Yc(e,t,n){return Xc(`filter.${e.filterType}`,[],e.query,e.args,t,n)}function Xc(e,t,n,r,o,i){const l=[];l.push(...Nt(t,o,i)),l.push(`${D(o,i)}${e}(`);const a=[];n&&a.push(Zc(n,o+1,i));for(const d of r)a.push([`${D(o+1,i)}${Ns(d)}`]);for(let d=0;d<a.length;d++){const c=d===a.length-1,f=a[d];for(let p=0;p<f.length;p++){const h=p===f.length-1;l.push(h&&!c?`${f[p]},`:f[p])}}return l.push(`${D(o,i)})`),l.join(`
429
- `)}function iv(e,t,n){const r=[];r.push(`${D(t,n)}layout(columns = ${e.columns}) {`);for(const o of e.rows)r.push(av(o,t+1,n));return r.push(`${D(t,n)}}`),r.join(`
430
- `)}function av(e,t,n){const r=[];r.push(`${D(t,n)}row {`);for(const o of e.items){const i=o.node.kind===V.ChartCall?Ls(o.node,t+1,n):Yc(o.node,t+1,n);if(o.span==null){r.push(i);continue}const l=i.split(`
431
- `);l[l.length-1]=`${l[l.length-1]} span ${o.span}`,r.push(l.join(`
432
- `))}return r.push(`${D(t,n)}}`),r.join(`
433
- `)}function lv(e,t,n){const r=[];if(r.push(...Nt(e.decorators,t,n)),r.push(`${D(t,n)}block ${U(e.name)} {`),e.domain&&r.push(`${D(t+1,n)}domain = ${U(e.domain)}`),e.blockType&&r.push(`${D(t+1,n)}type = ${U(e.blockType)}`),e.status&&r.push(`${D(t+1,n)}status = ${U(e.status)}`),e.description&&r.push(`${D(t+1,n)}description = ${U(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${D(t+1,n)}tags = [${e.tags.map(U).join(", ")}]`),e.owner&&r.push(`${D(t+1,n)}owner = ${U(e.owner)}`),e.termRefs&&e.termRefs.length>0&&r.push(`${D(t+1,n)}terms = [${e.termRefs.map(U).join(", ")}]`),e.pattern&&r.push(`${D(t+1,n)}pattern = ${U(e.pattern)}`),e.grain&&r.push(`${D(t+1,n)}grain = ${U(e.grain)}`),e.entities&&e.entities.length>0&&r.push(`${D(t+1,n)}entities = [${e.entities.map(U).join(", ")}]`),e.outputs&&e.outputs.length>0&&r.push(`${D(t+1,n)}outputs = [${e.outputs.map(U).join(", ")}]`),e.blockType!=="semantic"&&e.dimensions&&e.dimensions.length>0&&r.push(`${D(t+1,n)}dimensions = [${e.dimensions.map(U).join(", ")}]`),e.allowedFilters&&e.allowedFilters.length>0&&r.push(`${D(t+1,n)}allowedFilters = [${e.allowedFilters.map(U).join(", ")}]`),e.parameterPolicy&&e.parameterPolicy.length>0){r.push(`${D(t+1,n)}parameterPolicy {`);for(const o of e.parameterPolicy)r.push(`${D(t+2,n)}${o.name} = ${U(o.policy)}`);r.push(`${D(t+1,n)}}`)}if(e.filterBindings&&e.filterBindings.length>0){r.push(`${D(t+1,n)}filterBindings {`);for(const o of e.filterBindings)r.push(`${D(t+2,n)}${o.filter} = ${U(o.binding)}`);r.push(`${D(t+1,n)}}`)}if(e.sourceSystems&&e.sourceSystems.length>0&&r.push(`${D(t+1,n)}sourceSystems = [${e.sourceSystems.map(U).join(", ")}]`),e.replacementFor&&e.replacementFor.length>0&&r.push(`${D(t+1,n)}replacementFor = [${e.replacementFor.map(U).join(", ")}]`),e.llmContext&&r.push(`${D(t+1,n)}llmContext = ${U(e.llmContext)}`),e.businessOutcome&&r.push(`${D(t+1,n)}businessOutcome = ${U(e.businessOutcome)}`),e.businessOwner&&r.push(`${D(t+1,n)}businessOwner = ${U(e.businessOwner)}`),e.decisionUse&&r.push(`${D(t+1,n)}decisionUse = ${U(e.decisionUse)}`),e.reviewCadence&&r.push(`${D(t+1,n)}reviewCadence = ${U(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${D(t+1,n)}businessRules = [${e.businessRules.map(U).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${D(t+1,n)}caveats = [${e.caveats.map(U).join(", ")}]`),e.examples&&e.examples.length>0&&r.push(`${D(t+1,n)}examples = [${pv(e.examples)}]`),e.invariants&&e.invariants.length>0&&r.push(`${D(t+1,n)}invariants = [${e.invariants.map(U).join(", ")}]`),e.blockType==="semantic"){const o=e.metricsRef??(e.metricRef!==void 0?[e.metricRef]:[]);r.push(`${D(t+1,n)}metrics = [${o.map(U).join(", ")}]`),r.push(`${D(t+1,n)}dimensions = [${(e.dimensionsRef??[]).map(U).join(", ")}]`),e.timeDimension&&r.push(`${D(t+1,n)}time_dimension = ${U(e.timeDimension)}`),e.granularity&&r.push(`${D(t+1,n)}granularity = ${U(e.granularity)}`),e.requestedFilters&&e.requestedFilters.length>0&&r.push(`${D(t+1,n)}requested_filters = [${e.requestedFilters.map(U).join(", ")}]`),e.orderBy&&e.orderBy.length>0&&r.push(`${D(t+1,n)}order_by = [${e.orderBy.map(U).join(", ")}]`),e.limit!==void 0&&r.push(`${D(t+1,n)}limit = ${e.limit}`)}if(e.params){r.push(`${D(t+1,n)}params {`);for(const o of e.params.params){const i=o.paramType?`: ${o.paramType}`:"",l=o.initializer?` = ${ct(o.initializer)}`:"";r.push(`${D(t+2,n)}${o.name}${i}${l}`)}r.push(`${D(t+1,n)}}`)}if(e.query&&(r.push(`${D(t+1,n)}query = """`),r.push(...Zc(e.query,t+2,n)),r.push(`${D(t+1,n)}"""`)),e.visualization){r.push(`${D(t+1,n)}visualization {`);for(const o of e.visualization.properties)r.push(`${D(t+2,n)}${Ns(o)}`);r.push(`${D(t+1,n)}}`)}if(e.tests&&e.tests.length>0){r.push(`${D(t+1,n)}tests {`);for(const o of e.tests)r.push(`${D(t+2,n)}assert ${o.field} ${o.operator} ${ct(o.expected)}`);r.push(`${D(t+1,n)}}`)}return r.push(`${D(t,n)}}`),r.join(`
434
- `)}function cv(e,t,n){var o,i,l,a,d,c,f,p;const r=[];return r.push(...Nt(e.decorators,t,n)),r.push(`${D(t,n)}domain ${U(e.name)} {`),e.id&&r.push(`${D(t+1,n)}id = ${U(e.id)}`),e.parent&&r.push(`${D(t+1,n)}parent = ${U(e.parent)}`),e.owner&&r.push(`${D(t+1,n)}owner = ${U(e.owner)}`),e.businessOwner&&r.push(`${D(t+1,n)}businessOwner = ${U(e.businessOwner)}`),e.boundedContext&&r.push(`${D(t+1,n)}boundedContext = ${U(e.boundedContext)}`),e.sourceSystems&&e.sourceSystems.length>0&&r.push(`${D(t+1,n)}sourceSystems = [${e.sourceSystems.map(U).join(", ")}]`),e.primaryTerms&&e.primaryTerms.length>0&&r.push(`${D(t+1,n)}primaryTerms = [${e.primaryTerms.map(U).join(", ")}]`),e.reviewCadence&&r.push(`${D(t+1,n)}reviewCadence = ${U(e.reviewCadence)}`),e.tags&&e.tags.length>0&&r.push(`${D(t+1,n)}tags = [${e.tags.map(U).join(", ")}]`),e.businessOutcome&&r.push(`${D(t+1,n)}businessOutcome = ${U(e.businessOutcome)}`),e.description&&r.push(`${D(t+1,n)}description = ${U(e.description)}`),(o=e.inScope)!=null&&o.length&&r.push(`${D(t+1,n)}inScope = [${e.inScope.map(U).join(", ")}]`),(i=e.outOfScope)!=null&&i.length&&r.push(`${D(t+1,n)}outOfScope = [${e.outOfScope.map(U).join(", ")}]`),(l=e.dbtGroups)!=null&&l.length&&r.push(`${D(t+1,n)}dbtGroups = [${e.dbtGroups.map(U).join(", ")}]`),(a=e.dbtPaths)!=null&&a.length&&r.push(`${D(t+1,n)}dbtPaths = [${e.dbtPaths.map(U).join(", ")}]`),(d=e.dbtTags)!=null&&d.length&&r.push(`${D(t+1,n)}dbtTags = [${e.dbtTags.map(U).join(", ")}]`),(c=e.semanticDomains)!=null&&c.length&&r.push(`${D(t+1,n)}semanticDomains = [${e.semanticDomains.map(U).join(", ")}]`),(f=e.semanticTags)!=null&&f.length&&r.push(`${D(t+1,n)}semanticTags = [${e.semanticTags.map(U).join(", ")}]`),(p=e.exports)!=null&&p.length&&r.push(`${D(t+1,n)}exports = [${e.exports.map(U).join(", ")}]`),r.push(`${D(t,n)}}`),r.join(`
435
- `)}function dv(e,t,n){const r=[];return r.push(...Nt(e.decorators,t,n)),r.push(`${D(t,n)}term ${U(e.name)} {`),e.domain&&r.push(`${D(t+1,n)}domain = ${U(e.domain)}`),e.termType&&r.push(`${D(t+1,n)}type = ${U(e.termType)}`),e.status&&r.push(`${D(t+1,n)}status = ${U(e.status)}`),e.description&&r.push(`${D(t+1,n)}description = ${U(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${D(t+1,n)}tags = [${e.tags.map(U).join(", ")}]`),e.owner&&r.push(`${D(t+1,n)}owner = ${U(e.owner)}`),e.identifiers&&e.identifiers.length>0&&r.push(`${D(t+1,n)}identifiers = [${e.identifiers.map(U).join(", ")}]`),e.synonyms&&e.synonyms.length>0&&r.push(`${D(t+1,n)}synonyms = [${e.synonyms.map(U).join(", ")}]`),e.businessOutcome&&r.push(`${D(t+1,n)}businessOutcome = ${U(e.businessOutcome)}`),e.businessOwner&&r.push(`${D(t+1,n)}businessOwner = ${U(e.businessOwner)}`),e.decisionUse&&r.push(`${D(t+1,n)}decisionUse = ${U(e.decisionUse)}`),e.reviewCadence&&r.push(`${D(t+1,n)}reviewCadence = ${U(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${D(t+1,n)}businessRules = [${e.businessRules.map(U).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${D(t+1,n)}caveats = [${e.caveats.map(U).join(", ")}]`),r.push(`${D(t,n)}}`),r.join(`
436
- `)}function uv(e,t,n){const r=[];r.push(...Nt(e.decorators,t,n)),r.push(`${D(t,n)}business_view ${U(e.name)} {`),e.domain&&r.push(`${D(t+1,n)}domain = ${U(e.domain)}`),e.status&&r.push(`${D(t+1,n)}status = ${U(e.status)}`),e.description&&r.push(`${D(t+1,n)}description = ${U(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${D(t+1,n)}tags = [${e.tags.map(U).join(", ")}]`),e.owner&&r.push(`${D(t+1,n)}owner = ${U(e.owner)}`),e.termRefs&&e.termRefs.length>0&&r.push(`${D(t+1,n)}terms = [${e.termRefs.map(U).join(", ")}]`),e.businessOutcome&&r.push(`${D(t+1,n)}businessOutcome = ${U(e.businessOutcome)}`),e.businessOwner&&r.push(`${D(t+1,n)}businessOwner = ${U(e.businessOwner)}`),e.decisionUse&&r.push(`${D(t+1,n)}decisionUse = ${U(e.decisionUse)}`),e.reviewCadence&&r.push(`${D(t+1,n)}reviewCadence = ${U(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${D(t+1,n)}businessRules = [${e.businessRules.map(U).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${D(t+1,n)}caveats = [${e.caveats.map(U).join(", ")}]`),r.push(`${D(t+1,n)}includes {`);for(const o of e.includes)r.push(`${D(t+2,n)}${o.refType} ${U(o.name)}`);return r.push(`${D(t+1,n)}}`),r.push(`${D(t,n)}}`),r.join(`
437
- `)}function Zc(e,t,n){const r=e.rawSQL.replace(/^\n+|\s+$/g,"");if(!r.trim())return[`${D(t,n)}SELECT 1`];const o=r.split(`
438
- `).map(d=>d.trimEnd()),i=o.slice(1).filter(d=>d.length>0),l=i.length?i:o.filter(d=>d.length>0),a=l.length?Math.min(...l.map(d=>d.match(/^[ \t]*/)[0].length)):0;return o.map(d=>{if(d.length===0)return"";const c=d.startsWith(" ".repeat(a))||d.startsWith(" ".repeat(a))?d.slice(a):d.trimStart();return`${D(t,n)}${c}`})}function Ns(e){return`${e.name} = ${ct(e.value)}`}function pv(e){return e.map(t=>{const n=[`question = ${U(t.question)}`];return t.sql&&n.push(`sql = ${U(t.sql)}`),`{ ${n.join(", ")} }`}).join(", ")}function ct(e){switch(e.kind){case V.StringLiteral:return U(e.value);case V.NumberLiteral:return String(e.value);case V.BooleanLiteral:return e.value?"true":"false";case V.Identifier:return e.name;case V.ArrayLiteral:return`[${e.elements.map(t=>ct(t)).join(", ")}]`;case V.BinaryExpr:return`${ct(e.left)} ${e.operator} ${ct(e.right)}`;case V.IntervalExpr:return`INTERVAL ${U(e.value)}`;case V.FunctionCall:return`${e.callee}(${e.arguments.map(t=>ct(t)).join(", ")})`;case V.TemplateString:return U(e.parts.map(t=>typeof t=="string"?t:`{${ct(t)}}`).join(""));default:return""}}function U(e){return JSON.stringify(e)}function fv(e){var c,f,p,h,g,S,x,b;const t=Cn(e.metrics),n=Cn(e.dimensions??[]),r=Cn(e.requestedFilters??[]),o=Cn((e.orderBy??[]).map(k=>typeof k=="string"?k:`${k.name} ${k.direction}`)),i=mv(e.parameters??[]),l=[`block ${Oe(e.name)} {`,' type = "semantic"',` status = ${Oe(((c=e.status)==null?void 0:c.trim())||"draft")}`],a=hv(e.domain);a&&l.push(` domain = ${Oe(a)}`),(f=e.description)!=null&&f.trim()&&l.push(` description = ${Oe(e.description.trim())}`);const d=Cn(e.tags??[]);if(d.length>0&&l.push(` tags = [${d.map(Oe).join(", ")}]`),(p=e.owner)!=null&&p.trim()&&l.push(` owner = ${Oe(e.owner.trim())}`),l.push(` metrics = [${t.map(Oe).join(", ")}]`),l.push(` dimensions = [${n.map(Oe).join(", ")}]`),(h=e.timeDimension)!=null&&h.name.trim()&&(l.push(` time_dimension = ${Oe(e.timeDimension.name.trim())}`),e.timeDimension.granularity.trim()&&l.push(` granularity = ${Oe(e.timeDimension.granularity.trim())}`)),r.length>0&&l.push(` requested_filters = [${r.map(Oe).join(", ")}]`),o.length>0&&l.push(` order_by = [${o.map(Oe).join(", ")}]`),gv(e.limit)&&l.push(` limit = ${Math.floor(e.limit)}`),i.length>0){l.push(" params {");for(const E of i){const v=(g=E.type)!=null&&g.trim()?`: ${E.type.trim()}`:"",w=E.default!==void 0?` = ${ed(E.default)}`:"";l.push(` ${E.name}${v}${w}`)}l.push(" }");const k=i.filter(E=>{var v;return(v=E.policy)==null?void 0:v.trim()});if(k.length>0){l.push(" parameterPolicy {");for(const E of k)l.push(` ${E.name} = ${Oe(E.policy.trim())}`);l.push(" }")}const C=i.filter(E=>{var v;return(v=E.binding)==null?void 0:v.trim()});if(C.length>0){l.push(" filterBindings {");for(const E of C)l.push(` ${E.name} = ${Oe(E.binding.trim())}`);l.push(" }")}}return(S=e.visualization)!=null&&S.chart.trim()&&(l.push(" visualization {"),l.push(` chart = ${Oe(e.visualization.chart.trim())}`),(x=e.visualization.x)!=null&&x.trim()&&l.push(` x = ${Gi(e.visualization.x.trim())}`),(b=e.visualization.y)!=null&&b.trim()&&l.push(` y = ${Gi(e.visualization.y.trim())}`),l.push(" }")),l.push("}"),Gb(`${l.join(`
439
- `)}
440
- `)}function hv(e){const t=e==null?void 0:e.trim();if(!(!t||t==="uncategorized"||t==="_uncategorized"))return t}function Cn(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function mv(e){const t=new Map;for(const n of e){const r=n.name.trim();!r||t.has(r)||t.set(r,{...n,name:r})}return[...t.values()]}function gv(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function ed(e){return Array.isArray(e)?`[${e.map(ed).join(", ")}]`:typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":Oe(String(e??""))}function Oe(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Gi(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:Oe(e)}function yv(e,t){const n=Array.from(new Set(e.filter(Boolean))),r=Array.from(new Set(t.filter(Boolean))),i=([...n.slice(0,2),...r.slice(0,1)].join("_by_")||"semantic_query").replace(/[^a-zA-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64)||"semantic_query";return fv({name:i,status:"draft",metrics:n,dimensions:r}).trimEnd()}function xv(e,t){const n=e.replace(/\\/g,"/").replace(/^\/+|\/+$/g,""),r=n.match(/^domains\/[^/]+\/blocks\/(.+)$/);if(r)return r[1];const o=`blocks/${t.replace(/^\/+|\/+$/g,"")}/`;return n.startsWith(o)?n.slice(o.length):n.startsWith("blocks/")?n.slice(7):n}function bv(e,t){var o;const n={path:"",folders:new Map,blocks:[]};for(const i of e){const l=((o=i.domain)==null?void 0:o.trim())||"uncategorized",d=xv(i.path,t||l).split("/").filter(Boolean),c=t?d.slice(0,-1):[l,...d.slice(0,-1)];let f=n;for(const p of c){const h=[f.path,p].filter(Boolean).join("/");let g=f.folders.get(p);g||(g={name:p,path:h,folders:new Map,blocks:[]},f.folders.set(p,g)),f=g}f.blocks.push(i)}const r=i=>[...Array.from(i.folders.values()).sort((l,a)=>l.name.localeCompare(a.name)).map(l=>({kind:"folder",name:l.name,path:l.path,children:r(l)})),...i.blocks.sort((l,a)=>l.name.localeCompare(a.name)).map(l=>({kind:"block",block:l}))];return r(n)}function vv(e,t){const n={path:"",folders:new Map,files:[]};for(const o of e){const i=Sv(o,t);let l=n;for(const a of i){const d=[l.path,a].filter(Boolean).join("/");let c=l.folders.get(a);c||(c={name:a,path:d,folders:new Map,files:[]},l.folders.set(a,c)),l=c}l.files.push(o)}const r=o=>[...Array.from(o.folders.values()).sort((i,l)=>i.name.localeCompare(l.name)).map(i=>({kind:"folder",name:i.name,path:i.path,children:r(i)})),...o.files.sort((i,l)=>i.name.localeCompare(l.name)).map(i=>({kind:"file",file:i}))];return r(n)}function Sv(e,t){const n=e.path.replace(/\\/g,"/").split("/").filter(Boolean);if(n[0]==="domains"){const i=["notebooks","workbooks"],l=n.findIndex((a,d)=>d>0&&i.includes(a));if(l>0)return["Domains",...n.slice(1,l),...n.slice(l+1,-1)]}const r=n.findIndex(i=>i===t||i==="workbooks"||t==="business-views"),o=r>=0?n.slice(r+1,-1):n.slice(0,-1);return e.ownerDomain?["Domains",...e.ownerDomain.split(/[./]/).map(l=>l.trim()).filter(Boolean),...o]:["Project",...o]}function td({id:e,ariaLabel:t,value:n,options:r,onChange:o,summary:i,t:l}){return s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${l.headerBorder}`,display:"grid",gap:5},children:[s.jsx("label",{htmlFor:e,style:{color:l.textMuted,fontSize:9,fontWeight:750,letterSpacing:".06em",textTransform:"uppercase"},children:"Domain"}),s.jsxs("select",{id:e,"aria-label":t,value:n,onChange:a=>o(a.target.value),style:{width:"100%",background:l.inputBg,border:`1px solid ${l.inputBorder}`,borderRadius:6,color:l.textPrimary,fontFamily:l.font,fontSize:12,padding:"7px 8px"},children:[s.jsx("option",{value:"",children:"All domains"}),r.map(a=>{const d=typeof a=="string"?{value:a,label:a}:a;return s.jsx("option",{value:d.value,children:d.label??d.value},d.value)})]}),i!==void 0?s.jsx("span",{style:{color:l.textMuted,fontSize:10},children:i}):null]})}function kv(e){const t=e.filter(n=>n.type==="notebook").flatMap(n=>{const r=[n.ownerDomain,...n.usesDomains??[]].map(o=>o==null?void 0:o.trim()).filter(o=>!!o);return r.length>0?r:["uncategorized"]});return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function Ji(e,t,n=""){const r=t.trim().toLowerCase();return Array.from(new Map(e.filter(o=>o.type==="notebook").map(o=>[o.path,o])).values()).filter(o=>{var a,d;const i=[o.ownerDomain,...o.usesDomains??[]].map(c=>c==null?void 0:c.trim()).filter(c=>!!c);return(!n||(n==="uncategorized"?i.length===0:i.includes(n)))&&(!r||o.name.toLowerCase().includes(r)||o.path.toLowerCase().includes(r)||((a=o.ownerDomain)==null?void 0:a.toLowerCase().includes(r))||((d=o.usesDomains)==null?void 0:d.some(c=>c.toLowerCase().includes(r))))}).sort((o,i)=>o.name.localeCompare(i.name))}const wv=[{collection:"metrics",kind:"metric",label:"Metrics"},{collection:"dimensions",kind:"dimension",label:"Dimensions"},{collection:"timeDimensions",kind:"time_dimension",label:"Time Dimensions"},{collection:"entities",kind:"entity",label:"Entities"},{collection:"measures",kind:"measure",label:"Underlying measures"}];function Ve(e){return String(e??"").trim()||"uncategorized"}function lt(e){const t=Array.isArray(e.semanticModelIds)?e.semanticModelIds.map(String).filter(Boolean):[];return t.length>0?Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r)):e.cube?[String(e.cube)]:[]}function jv(e,t){return String((t==="dimension"||t==="time_dimension")&&e.reference||e.name)}function Cv(e,t,n){const r=jv(e,t),o=Ve(e.domain);return{id:`${t}:${r}`,label:String(e.label||e.name),kind:t,meta:{provider:n,domain:o,localName:String(e.name),reference:r,...e.canonicalId?{canonicalId:String(e.canonicalId)}:{},...e.qualifiedName?{qualifiedName:String(e.qualifiedName)}:{},...e.entityLink?{entityLink:String(e.entityLink)}:{},...e.table?{table:String(e.table)}:{},...e.cube?{cube:String(e.cube)}:{},...lt(e).length>0?{semanticModelIds:lt(e).join(",")}:{},...e.owner?{owner:String(e.owner)}:{},...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags.join(",")}:{}}}}function kt(e,t,n,r,o){if(r.length===0)return null;const i=r.map(l=>Cv(l,n,o)).sort((l,a)=>l.label.localeCompare(a.label)||l.id.localeCompare(a.id));return{id:e,label:t,kind:"group",count:i.length,meta:{provider:o,objectKind:n},children:i}}function un(e){var t;return(t=e.children)!=null&&t.length?e.children.reduce((n,r)=>n+un(r),0):1}function Ev(e){const t=e.provider??"dql",n=[...e.metrics,...e.measures,...e.dimensions,...e.timeDimensions,...e.entities,...e.hierarchies,...e.savedQueries];if(n.length===0&&e.semanticModels.length===0)return null;const r=new Map(e.semanticModels.map(c=>[c.name,c])),o=new Set(e.semanticModels.map(c=>c.name));for(const c of n)for(const f of lt(c))o.add(f);const i=c=>{const f=r.get(c);if(f)return Ve(f.domain);const p=n.find(h=>lt(h).includes(c));return Ve(p==null?void 0:p.domain)},l=new Set([...e.domains.map(Ve),...e.semanticModels.map(c=>Ve(c.domain)),...n.map(c=>Ve(c.domain))]),a=Array.from(l).sort((c,f)=>c.localeCompare(f)).flatMap(c=>{const p=Array.from(o).filter(v=>i(v)===c).sort((v,w)=>v.localeCompare(w)).flatMap(v=>{const w=r.get(v),A=wv.flatMap(({collection:y,kind:M,label:$})=>{const T=e[y].filter(I=>{const G=lt(I);return G.length===1&&G[0]===v&&(y!=="dimensions"||!I.isTimeDimension)}),L=kt(`group:${c}:${v}:${M}`,$,M,T,t);return L?[L]:[]});return A.length===0&&!w?[]:[{id:`semantic_model:${v}`,label:(w==null?void 0:w.label)||v,kind:"semantic_model",count:A.reduce((y,M)=>y+un(M),0),meta:{provider:t,domain:c,cube:v,...w!=null&&w.table?{table:w.table}:{},...w!=null&&w.owner?{owner:w.owner}:{}},children:A}]}),h=e.metrics.filter(v=>Ve(v.domain)===c&&lt(v).length>1),g=e.metrics.filter(v=>Ve(v.domain)===c&&lt(v).length===0),S=[kt(`group:${c}:unassigned-dimensions`,"Dimensions","dimension",e.dimensions.filter(v=>Ve(v.domain)===c&&lt(v).length===0&&!v.isTimeDimension),t),kt(`group:${c}:unassigned-time-dimensions`,"Time Dimensions","time_dimension",e.timeDimensions.filter(v=>Ve(v.domain)===c&&lt(v).length===0),t),kt(`group:${c}:unassigned-measures`,"Underlying measures","measure",e.measures.filter(v=>Ve(v.domain)===c&&lt(v).length===0),t),kt(`group:${c}:unassigned-entities`,"Entities","entity",e.entities.filter(v=>Ve(v.domain)===c&&lt(v).length===0),t)].filter(v=>!!v),x=[...p],b=kt(`group:${c}:cross-model-metrics`,"Cross-model metrics","metric",h,t);b&&x.push(b);const k=kt(`group:${c}:unassigned-metrics`,"Unassigned metrics","metric",g,t);k&&x.push(k),S.length>0&&x.push({id:`group:${c}:unassigned-objects`,label:"Unassigned objects",kind:"group",count:S.reduce((v,w)=>v+un(w),0),meta:{provider:t,domain:c},children:S});const C=kt(`group:${c}:hierarchies`,"Hierarchies","hierarchy",e.hierarchies.filter(v=>Ve(v.domain)===c),t);C&&x.push(C);const E=kt(`group:${c}:saved-queries`,"Saved Queries","saved_query",e.savedQueries.filter(v=>Ve(v.domain)===c),t);return E&&x.push(E),x.length===0?[]:[{id:`domain:${t}:${c}`,label:c,kind:"domain",count:x.reduce((v,w)=>v+un(w),0),meta:{provider:t,domain:c},children:x}]});if(a.length===0)return null;const d=a.flatMap(c=>c.label==="uncategorized"?c.children??[]:[c]);return{id:"root:semantic",label:"Semantic Layer",kind:"group",children:[{id:`provider:${t}`,label:t.toUpperCase(),kind:"provider",count:d.reduce((c,f)=>c+un(f),0),meta:{provider:t},children:d}]}}function Av(e,t,n,r){const o=i=>{var a,d;if(!((a=i.children)!=null&&a.length)){if(i.kind==="metric")return{...i};if(i.kind==="dimension"||i.kind==="time_dimension"){if(t===0||r!=="ready"||!n)return null;const c=String(((d=i.meta)==null?void 0:d.reference)||i.id.slice(i.id.indexOf(":")+1));return n.has(c)?{...i}:null}return null}const l=i.children.map(o).filter(c=>!!c);return l.length===0?null:{...i,count:l.reduce((c,f)=>c+un(f),0),children:l}};return o(e)??{...e,children:[]}}const Qi=[{id:"notebooks",label:"Notebooks",icon:Ps},{id:"semantic",label:"Semantic",icon:Ds},{id:"database",label:"Database",icon:tr},{id:"blocks",label:"Blocks",icon:$s}],Tv={certified:"var(--status-success)",published:"var(--status-success)",deprecated:"var(--status-error)",draft:"var(--status-warning)",pending:"var(--status-warning)",review:"#4a74c9",in_review:"#4a74c9"};function Rv({defaultTab:e,onOpenFile:t,tabs:n,onInsertText:r,onSemanticCompose:o,blockDomain:i="",onBlockDomainChange:l,onNewBlock:a,onDeleteBlock:d,blockLibraryRefreshKey:c=0,footer:f,footerStatus:p="ready",onCollapse:h}){var y;const{state:g,dispatch:S}=xe(),x=Fe[g.themeMode],b=n?n.map(M=>Qi.find($=>$.id===M)).filter(M=>!!M):Qi,[k,C]=u.useState(e??((y=b[0])==null?void 0:y.id)??"notebooks"),[E,v]=u.useState(""),[w,A]=u.useState("");u.useEffect(()=>{e&&C(e)},[e]);const R=r??(M=>{wb(M)||S({type:"ADD_CELL",cell:_s("sql",M)})});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",minHeight:0,background:x.cellBg,fontFamily:x.font},children:[s.jsxs("div",{style:{display:"flex",gap:2,padding:"6px 6px 0",borderBottom:`1px solid ${x.headerBorder}`},children:[b.map(({id:M,label:$,icon:T})=>{const L=k===M;return s.jsxs("button",{type:"button",onClick:()=>C(M),title:$,style:{flex:b.length>3?"1 1 auto":1,minWidth:0,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,border:"none",borderBottom:`2px solid ${L?x.accent:"transparent"}`,background:"transparent",color:L?x.accent:x.textMuted,cursor:"pointer",fontSize:11,fontWeight:700,padding:"6px 3px 7px"},children:[s.jsx(T,{size:13,style:{flexShrink:0}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:$})]},M)}),h?s.jsx("button",{type:"button",onClick:h,title:"Collapse explorer",style:{border:"none",background:"transparent",color:x.textMuted,cursor:"pointer",fontSize:13,padding:"0 6px",flexShrink:0},children:"‹"}):null]}),k==="notebooks"?s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${x.headerBorder}`,display:"flex",gap:6},children:[s.jsxs("div",{style:{position:"relative",flex:1},children:[s.jsx(Li,{size:12,style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:x.textMuted}}),s.jsx("input",{value:E,onChange:M=>v(M.target.value),placeholder:"Search notebooks…","aria-label":"Search notebooks",style:{width:"100%",boxSizing:"border-box",background:x.inputBg,border:`1px solid ${x.inputBorder}`,borderRadius:6,color:x.textPrimary,fontSize:12,fontFamily:x.font,padding:"6px 8px 6px 26px",outline:"none"}})]}),s.jsx("button",{type:"button",onClick:()=>S({type:"OPEN_NEW_NOTEBOOK_MODAL"}),title:"Create notebook","aria-label":"Create notebook",style:{width:28,height:28,flexShrink:0,borderRadius:7,border:`1px solid ${x.accent}55`,background:"var(--accent-dim)",color:x.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:s.jsx(Gy,{size:14,strokeWidth:2,"aria-hidden":"true"})})]}):s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${x.headerBorder}`,display:"flex",gap:6},children:[s.jsxs("div",{style:{position:"relative",flex:1},children:[s.jsx(Li,{size:12,style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:x.textMuted}}),s.jsx("input",{value:E,onChange:M=>v(M.target.value),placeholder:`Search ${k}…`,style:{width:"100%",boxSizing:"border-box",background:x.inputBg,border:`1px solid ${x.inputBorder}`,borderRadius:6,color:x.textPrimary,fontSize:12,fontFamily:x.font,padding:"6px 8px 6px 26px",outline:"none"}})]}),a?s.jsx("button",{type:"button",onClick:a,title:"New block",style:{width:28,height:28,flexShrink:0,borderRadius:6,border:`1px solid ${x.btnBorder}`,background:x.btnBg,color:x.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:s.jsx(ox,{size:14,strokeWidth:2})}):null]}),s.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:[k==="notebooks"&&t&&s.jsx($v,{t:x,onOpenFile:t,search:E,domain:w,onDomainChange:A}),k==="semantic"&&s.jsx(Mv,{t:x,search:E,onInsert:R,notebookMode:!r||!!o,onSemanticCompose:o}),k==="database"&&s.jsx(Iv,{t:x,search:E,onInsert:R}),k==="blocks"&&s.jsx(Lv,{t:x,search:E,domain:i,onDomainChange:l,onDeleteBlock:d,refreshKey:c})]}),f?s.jsxs("div",{style:{padding:"9px 12px",borderTop:`1px solid ${x.headerBorder}`,fontSize:10.5,color:x.textMuted,display:"flex",alignItems:"center",gap:6,fontFamily:x.font},children:[s.jsx("span",{style:{width:6,height:6,borderRadius:999,background:p==="ready"?"var(--status-success)":"var(--status-warning)",flexShrink:0}}),s.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f})]}):null]})}const Br=(e,t=!1)=>({display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,boxSizing:"border-box",padding:"6px 10px",border:"none",borderBottom:`1px solid ${e.cellBorder}`,background:t?`${e.accent}14`:"transparent",cursor:"pointer",textAlign:"left",fontFamily:e.font,color:e.textPrimary});function Ht({text:e,t}){return s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:t.textMuted,textAlign:"center"},children:e})}function _v(e,t){const n=e.toLowerCase();if(!(/(?:_id|_key|_uuid|_fk|_pk)$/.test(n)||n==="id"||n==="pk"))return;const r=t.toLowerCase().replace(/^(?:dim|fct|fact|stg|staging|raw|base)_/,""),o=r.replace(/s$/,"");return n==="id"||n==="pk"||n===`${r}_id`||n===`${o}_id`||n===`${r}id`||n===`${o}id`?"pk":"fk"}function $v({t:e,onOpenFile:t,search:n,domain:r,onDomainChange:o}){var v;const{state:i,dispatch:l}=xe(),[a,d]=u.useState(null),[c,f]=u.useState(!1),[p,h]=u.useState(null),g=kv(i.files),S=r&&!g.includes(r)?[r,...g]:g,x=Ji(i.files,"",r),b=Ji(i.files,n,r),k=vv(b,"notebooks"),C=r||"all domains",E=async()=>{if(a){f(!0),h(null);try{const w=await N.deleteNotebook(a.path);if(!w.ok){h(w.error??"Could not delete this notebook.");return}l({type:"FILE_REMOVED",path:a.path}),d(null)}catch(w){h(w instanceof Error?w.message:String(w))}finally{f(!1)}}};return s.jsxs("div",{children:[s.jsx(td,{id:"notebook-domain-filter",ariaLabel:"Notebook domain",value:r,options:S,onChange:o,summary:s.jsxs(s.Fragment,{children:[b.length," notebook",b.length===1?"":"s"," · ",C]}),t:e}),b.length===0?s.jsx(Ht,{text:x.length===0?r?`No notebooks are related to ${r} yet.`:"No notebooks yet. Use the notebook icon above to create one.":`No ${C} notebooks match “${n.trim()}”.`,t:e}):s.jsx(nd,{nodes:k,activePath:(v=i.activeFile)==null?void 0:v.path,onOpenFile:t,onDelete:w=>{h(null),d(w)},t:e}),s.jsx("style",{children:`
441
- .dql-nb-delete { opacity: 0; transition: opacity .12s, color .12s, background .12s, border-color .12s; }
442
- .dql-nb-row:hover .dql-nb-delete { opacity: 1; }
443
- .dql-nb-delete:hover { color: ${e.error} !important; background: ${e.error}12 !important; border-color: ${e.error}44 !important; }
444
- .dql-nb-delete:focus-visible { opacity: 1; }
445
- `}),a?s.jsx(Dv,{file:a,t:e,busy:c,error:p,onCancel:()=>{d(null),h(null)},onConfirm:()=>void E()}):null]})}function nd({nodes:e,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i=0}){return s.jsx(s.Fragment,{children:e.map(l=>l.kind==="folder"?s.jsx(Ov,{node:l,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i},`notebook-folder:${l.path}`):s.jsx(Pv,{file:l.file,active:t===l.file.path,onOpenFile:n,onDelete:r,t:o,depth:i},l.file.path))})}function Ov({node:e,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i}){const[l,a]=u.useState(!0);return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>a(d=>!d),"aria-expanded":l,title:e.path,style:{display:"flex",alignItems:"center",gap:5,width:"100%",boxSizing:"border-box",padding:`5px 8px 5px ${10+i*14}px`,border:"none",borderBottom:`1px solid ${o.cellBorder}`,background:"transparent",color:o.textMuted,cursor:"pointer",textAlign:"left",fontFamily:o.font,fontSize:11,fontWeight:i===0?700:600},children:[s.jsx(oo,{size:11,style:{transform:l?"rotate(90deg)":void 0,flexShrink:0}}),l?s.jsx(Ic,{size:13}):s.jsx(Bn,{size:13}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]}),l?s.jsx(nd,{nodes:e.children,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i+1}):null]})}function Pv({file:e,active:t,onOpenFile:n,onDelete:r,t:o,depth:i}){return s.jsxs("div",{style:{position:"relative",display:"flex",alignItems:"center"},className:"dql-nb-row",children:[s.jsxs("button",{type:"button",onClick:()=>n(e),style:{...Br(o,t),paddingLeft:10+i*14,paddingRight:30},title:`${e.path}${e.ownerDomain?` · Owner domain: ${e.ownerDomain}`:""}`,children:[s.jsx(Ps,{size:13,color:o.textMuted,style:{flexShrink:0}}),s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12.5},children:e.name.replace(/\.dqln?$|\.ipynb$/i,"")})]}),s.jsx("button",{type:"button",className:"dql-nb-delete",onClick:l=>{l.stopPropagation(),r(e)},title:`Delete ${e.name}`,"aria-label":`Delete ${e.name}`,style:{position:"absolute",right:6,display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,borderRadius:5,border:"1px solid transparent",background:"transparent",color:o.textMuted,cursor:"pointer",padding:0},children:s.jsx(Nc,{size:12})})]})}function Dv({file:e,t,busy:n,error:r,onCancel:o,onConfirm:i}){return s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":`Delete ${e.name}`,onClick:o,style:{position:"fixed",inset:0,zIndex:60,background:"rgba(15,23,42,0.34)",display:"grid",placeItems:"center"},children:s.jsxs("div",{onClick:l=>l.stopPropagation(),style:{width:"min(420px, calc(100vw - 40px))",background:t.cellBg,border:`1px solid ${t.headerBorder}`,borderRadius:12,padding:18,display:"grid",gap:10,boxShadow:"0 18px 60px rgba(15,23,42,0.22)"},children:[s.jsx("div",{style:{fontSize:14,fontWeight:700,color:t.textPrimary,fontFamily:t.font},children:"Delete this notebook?"}),s.jsxs("div",{style:{fontSize:12.5,color:t.textSecondary,fontFamily:t.font,lineHeight:1.5},children:[s.jsx("code",{style:{fontFamily:t.fontMono,fontSize:12},children:e.path})," will be removed from disk. Blocks and metrics it referenced are not affected."]}),r?s.jsx("div",{style:{fontSize:12,color:t.error,fontFamily:t.font},children:r}):null,s.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",marginTop:4},children:[s.jsx("button",{type:"button",onClick:o,disabled:n,style:ke(t,{variant:"secondary",size:"md",disabled:n}),children:"Cancel"}),s.jsx("button",{type:"button",onClick:i,disabled:n,style:ke(t,{variant:"danger",size:"md",disabled:n}),children:n?"Deleting…":"Delete notebook"})]})]})})}function Mv({t:e,search:t,onInsert:n,notebookMode:r,onSemanticCompose:o}){var se;const{state:i,dispatch:l}=xe(),a=u.useMemo(()=>Ev(i.semanticLayer),[i.semanticLayer.provider,i.semanticLayer.metrics,i.semanticLayer.measures,i.semanticLayer.dimensions,i.semanticLayer.timeDimensions,i.semanticLayer.entities,i.semanticLayer.hierarchies,i.semanticLayer.semanticModels,i.semanticLayer.savedQueries]),d=i.semanticLayer.loading,[c,f]=u.useState(new Set),[p,h]=u.useState(new Set),[g,S]=u.useState(null),[x,b]=u.useState("idle"),[k,C]=u.useState(null),[E,v]=u.useState(!1),[w,A]=u.useState(null),[R,y]=u.useState(null),[M,$]=u.useState(),T=new Map(i.semanticLayer.metrics.map(H=>[H.name,H])),L=()=>{l({type:"SET_SETTINGS_TAB",tab:"project"}),l({type:"SET_MAIN_VIEW",view:"settings"})};u.useEffect(()=>{let H=!0;return N.getConnections().then(te=>{H&&$(te.default?{target:"connection",connectionName:te.default}:void 0)}).catch(()=>{H&&$(void 0)}),()=>{H=!1}},[]),u.useEffect(()=>{let H=!0;if(A(null),y(null),c.size===0){S(null),b("idle"),C(null),h(new Set);return}return S(null),b("loading"),C(null),N.getCompatibility(Array.from(c)).then(te=>{if(!H)return;const J=new Set(te.dimensions.map(B=>B.reference??B.name));S(J),b("ready"),C(te.engine),h(B=>new Set(Array.from(B).filter(ne=>J.has(ne))))}).catch(te=>{H&&(S(new Set),b("error"),C(null),h(new Set),y(te instanceof bt?`${te.code?`${te.code}: `:""}${te.message}`:te instanceof Error?te.message:"Semantic compatibility could not be verified."))}),()=>{H=!1}},[Array.from(c).sort().join("|")]);const I=u.useMemo(()=>!a||!r?a:Av(a,c.size,g,x),[a,r,c.size,g,x]),G=(H,te)=>{A(null),y(null),(H==="metric"?f:h)(B=>{const ne=new Set(B);return ne.has(te)?ne.delete(te):ne.add(te),ne})},Y=(H,te)=>{var J;if(H==="metric"){const B=(J=T.get(te))==null?void 0:J.execution;return B&&B.status!=="ready"?{allowed:!1,reason:B.reason||"This metric requires semantic runtime setup."}:{allowed:!0}}return c.size===0?{allowed:!1,reason:"Select a metric first."}:g?g.has(te)?{allowed:!0}:{allowed:!1,reason:"This dimension has no governed join path to every selected metric."}:{allowed:!1,reason:"Checking compatibility…"}},P=new Set([...Array.from(c).map(H=>`metric:${H}`),...Array.from(p).map(H=>`dimension:${H}`)]),q=c.size>0&&x==="ready"&&!E,O=async()=>{if(c.size!==0){v(!0),y(null);try{const H=await N.previewSemanticBuilder({metrics:Array.from(c),dimensions:Array.from(p),executionTarget:M,limit:50});if("error"in H){A(null),y(H.error);return}A({sql:H.sql,rows:H.result.rowCount??H.result.rows.length,executionTarget:M,engine:H.engine})}catch(H){A(null),y(H instanceof bt?`${H.code?`${H.code}: `:""}${H.message}`:H instanceof Error?H.message:"The governed semantic preview could not run.")}finally{v(!1)}}},W=()=>{if(!q)return;const H=Array.from(c),te=Array.from(p);if(o){o(H,te),f(new Set),h(new Set),A(null),y(null);return}const J=yv(H,te),B=_s("dql",J);B.executionTarget=(w==null?void 0:w.executionTarget)??M,B.dqlArtifact={source:J,kind:"semantic_block",metrics:H,dimensions:te,persistence:"transient",trustState:"governed",reviewState:"draft",routeEvidence:[{route:"semantic",authoringState:w?"previewed":"selected",compatibilityState:x,...k?{compatibilityEngine:k}:{},...w?{engine:w.engine,executionTarget:w.executionTarget,previewRows:w.rows}:{}}],...w?{sql:w.sql,compiledSql:w.sql}:{}},l({type:"ADD_CELL",cell:B}),f(new Set),h(new Set),A(null),y(null)};return d&&!a?s.jsx(Ht,{text:"Loading semantic layer…",t:e}):!a||!I||(((se=a.children)==null?void 0:se.length)??0)===0?s.jsx(Ht,{text:"No semantic layer imported yet.",t:e}):s.jsxs("div",{children:[r&&s.jsxs("div",{style:{display:"grid",gap:7,padding:8,borderBottom:`1px solid ${e.headerBorder}`,background:"var(--bg-1)"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{flex:1,fontSize:10.5,color:e.textMuted},children:c.size===0?"Choose a business metric. Related dimensions appear next.":x==="loading"?"Checking governed dimensions…":x==="ready"?`${c.size>1?"Common governed dimensions":"Governed dimensions"} · ${(g==null?void 0:g.size)??0} available${k?` · ${k}`:""}`:`${c.size} metric${c.size===1?"":"s"} selected`}),s.jsx("button",{type:"button",onClick:()=>void O(),disabled:E||c.size===0,style:{border:`1px solid ${e.btnBorder}`,background:e.btnBg,color:e.textSecondary,borderRadius:5,padding:"4px 7px",fontSize:10,cursor:c.size?"pointer":"not-allowed",opacity:c.size?1:.5},children:E?"Running…":"Preview & run"}),s.jsx("button",{type:"button",onClick:W,disabled:!q,title:q?o?"Apply this governed selection to the Block Studio visual builder":w?"Add the previewed semantic query to the notebook":"Add the governed semantic selection now; preview is optional":"Select an executable metric and wait for governed compatibility",style:{border:"none",background:e.accent,color:"#fff",borderRadius:5,padding:"5px 7px",fontSize:10,fontWeight:700,cursor:q?"pointer":"not-allowed",opacity:q?1:.5},children:o?"Apply to block":"Add to cell"})]}),w&&s.jsxs("div",{style:{display:"grid",gap:4,padding:"6px 7px",borderRadius:6,border:"1px solid var(--status-success)",background:"var(--status-success-bg)",color:e.textSecondary,fontSize:10},children:[s.jsxs("span",{children:["Preview succeeded · ",w.rows," row",w.rows===1?"":"s"]}),s.jsx("code",{style:{display:"block",maxHeight:48,overflow:"hidden",whiteSpace:"pre-wrap",fontSize:9,color:e.textMuted},children:w.sql})]}),R&&s.jsxs("div",{role:"alert",style:{display:"flex",gap:7,alignItems:"center",padding:"6px 7px",borderRadius:6,border:`1px solid ${e.error}40`,background:`${e.error}10`,color:e.error,fontSize:10,lineHeight:1.35},children:[s.jsx("span",{style:{flex:1},children:R}),/semantic runtime|MetricFlow/i.test(R)?s.jsx("button",{type:"button",onClick:L,style:{border:"none",background:"transparent",color:e.accent,fontSize:9.5,fontWeight:700,cursor:"pointer",whiteSpace:"nowrap"},children:"Set up →"}):null]}),i.semanticLayer.metrics.some(H=>H.execution&&H.execution.status!=="ready")&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:9.5,color:e.textMuted},children:[s.jsx("span",{style:{flex:1},children:"Complex metrics are imported but need a full semantic runtime to execute."}),s.jsx("button",{type:"button",onClick:L,style:{border:"none",background:"transparent",color:e.accent,fontSize:9.5,fontWeight:700,cursor:"pointer",padding:0,whiteSpace:"nowrap"},children:"Set up runtime →"})]})]}),s.jsx($b,{tree:I,themeMode:i.themeMode,search:t,onInsert:n,selectionMode:r,selected:P,onToggleSelection:G,canSelect:Y})]})}function Iv({t:e,search:t,onInsert:n}){const{state:r}=xe(),[o,i]=u.useState(new Set),l=t.trim().toLowerCase(),a=(r.schemaTables??[]).filter(c=>!l||c.name.toLowerCase().includes(l)||c.columns.some(f=>f.name.toLowerCase().includes(l)));if(a.length===0)return s.jsx(Ht,{text:l?"No matches.":"Connect a database to browse tables.",t:e});const d=c=>i(f=>{const p=new Set(f);return p.has(c)?p.delete(c):p.add(c),p});return s.jsx("div",{children:a.map(c=>{const f=o.has(c.name);return s.jsxs("div",{children:[s.jsxs("div",{style:{...Br(e),justifyContent:"flex-start"},children:[s.jsx("button",{type:"button",onClick:()=>d(c.name),title:f?"Collapse":"Expand columns",style:{border:"none",background:"transparent",cursor:"pointer",color:e.textMuted,display:"flex",padding:0},children:f?s.jsx(Os,{size:13}):s.jsx(oo,{size:13})}),s.jsxs("button",{type:"button",onClick:()=>n(`SELECT * FROM ${c.path||c.name} LIMIT 100`),title:"Insert a SELECT for this table",style:{flex:1,minWidth:0,border:"none",background:"transparent",cursor:"pointer",color:e.textPrimary,textAlign:"left",display:"flex",alignItems:"center",gap:7,padding:0,fontFamily:e.font},children:[s.jsx(Tb,{table:c,colors:{accent:e.accent,success:e.success,warning:e.warning,muted:e.textMuted}}),s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontFamily:e.fontMono},children:c.name}),s.jsx("span",{style:{fontSize:8.5,color:e.textMuted,textTransform:"uppercase",letterSpacing:".04em",flexShrink:0},children:Hc(c).label}),s.jsx("span",{style:{fontSize:10,color:e.textMuted,flexShrink:0},children:c.columns.length})]})]}),f&&c.columns.map(p=>{const h=_v(p.name,c.name);return s.jsxs("button",{type:"button",onClick:()=>n(p.name),title:h==="pk"?`Primary key · insert ${p.name}`:h==="fk"?`Foreign key · insert ${p.name}`:`Insert column ${p.name}`,style:{...Br(e),paddingLeft:32,gap:7},children:[s.jsx("span",{style:{flexShrink:0,width:18,fontSize:8.5,fontWeight:700,fontFamily:e.fontMono,color:h==="pk"?"var(--pk)":h==="fk"?"var(--fk)":e.textMuted},children:h==="pk"?"PK":h==="fk"?"FK":""}),s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontFamily:e.fontMono,color:e.textSecondary},children:p.name}),s.jsx("span",{style:{fontSize:10,color:e.textMuted,flexShrink:0,fontFamily:e.fontMono},children:p.type})]},p.name)})]},c.path||c.name)})})}function Lv({t:e,search:t,domain:n,onDomainChange:r,onDeleteBlock:o,refreshKey:i}){const{state:l,dispatch:a}=xe(),[d,c]=u.useState([]),[f,p]=u.useState(!0),[h,g]=u.useState(new Set),S=l.files.filter(A=>A.type==="block").map(A=>A.path).sort().join("|");u.useEffect(()=>{let A=!0;return p(!0),N.getBlockLibrary().then(R=>{A&&c(R.blocks)}).finally(()=>{A&&p(!1)}),()=>{A=!1}},[S,i]);const x=Ob(d),b=n,k=b&&!x.includes(b)?[b,...x]:x,C=Pb(d,b,t),E=u.useMemo(()=>bv(C,b),[C,b]),v=b||"all domains",w=A=>{const R={name:A.path.split("/").pop()??A.name,path:A.path,type:"block",folder:"blocks"};l.files.some(y=>y.path===A.path)||a({type:"FILE_ADDED",file:R}),N.openBlockStudio(A.path).then(y=>a({type:"OPEN_BLOCK_STUDIO",file:R,payload:y}))};return f?s.jsx(Ht,{text:"Loading blocks…",t:e}):d.length===0?s.jsx(Ht,{text:"No blocks yet.",t:e}):s.jsxs("div",{children:[s.jsx(td,{id:"block-domain-filter",ariaLabel:"Block domain",value:b,options:k,onChange:A=>r==null?void 0:r(A),summary:s.jsxs(s.Fragment,{children:[C.length," block",C.length===1?"":"s"," · ",v]}),t:e}),C.length===0?s.jsx(Ht,{text:t?`No ${v} blocks match this search.`:b?`No blocks in ${b} yet.`:"No blocks yet.",t:e}):s.jsx(rd,{nodes:E,depth:0,expandAll:!!t.trim(),expandedFolders:h,onToggleFolder:A=>g(R=>{const y=new Set(R);return y.has(A)?y.delete(A):y.add(A),y}),onOpen:w,onDelete:o,t:e})]})}function rd({nodes:e,depth:t,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:l,t:a}){return s.jsx(s.Fragment,{children:e.map(d=>{if(d.kind==="block")return s.jsx(Nv,{block:d.block,depth:t,t:a,onOpen:()=>i(d.block),onDelete:l?()=>l(d.block):void 0},d.block.path);const c=n||r.has(d.path);return s.jsxs(Pe.Fragment,{children:[s.jsxs("button",{type:"button",onClick:()=>o(d.path),title:d.path,style:{...Br(a),paddingLeft:10+t*16,borderBottom:"none",fontWeight:650},children:[c?s.jsx(Os,{size:13,color:a.textMuted}):s.jsx(oo,{size:13,color:a.textMuted}),c?s.jsx(Ic,{size:14,color:a.accent}):s.jsx(Bn,{size:14,color:a.textMuted}),s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},children:d.name}),s.jsx("span",{style:{fontSize:10,color:a.textMuted},children:od(d.children)})]}),c?s.jsx(rd,{nodes:d.children,depth:t+1,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:l,t:a}):null]},`folder:${d.path}`)})})}function od(e){return e.reduce((t,n)=>t+(n.kind==="block"?1:od(n.children)),0)}function Nv({block:e,depth:t=0,t:n,onOpen:r,onDelete:o}){const i=String(e.status??"draft"),l=Tv[i]??n.warning;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,width:"100%",boxSizing:"border-box",padding:`7px 8px 7px ${10+t*16}px`,border:"none",borderRadius:7,margin:"1px 0",background:"transparent",cursor:"pointer",textAlign:"left",fontFamily:n.font},children:[s.jsxs("button",{type:"button",onClick:r,title:e.description||`${e.name} — open`,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,border:"none",background:"transparent",padding:0,cursor:"pointer",textAlign:"left",fontFamily:n.font},children:[s.jsx($s,{size:14,color:n.textMuted,strokeWidth:1.75,style:{flexShrink:0}}),s.jsxs("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:1},children:[s.jsx("span",{style:{fontSize:12,fontWeight:600,color:n.textPrimary,fontFamily:n.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),s.jsx("span",{style:{fontSize:10.5,color:n.textMuted,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.domain,i].filter(Boolean).join(" · ")})]})]}),s.jsx("span",{title:i,style:{flexShrink:0,width:7,height:7,borderRadius:999,background:l}}),o?s.jsx("button",{type:"button","aria-label":`Delete ${e.name}`,title:`Delete ${e.name}`,onClick:o,style:{width:24,height:24,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:6,background:"transparent",color:n.error,cursor:"pointer"},children:s.jsx(Nc,{size:13})}):null]})}const br=(e,t)=>`https://cdn.simpleicons.org/${e}/${t}`,Bv={duckdb:[br("duckdb","FFF000")],file:[br("duckdb","FFF000")],snowflake:[br("snowflake","29B5E8")],databricks:[br("databricks","FF3621")]},Fv={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"};function zv({size:e,color:t}){return s.jsx("span",{"aria-hidden":!0,style:{width:e,height:e,borderRadius:3,background:t,flexShrink:0,display:"inline-block"}})}function Dn({driver:e,size:t=16,fallbackColor:n}){const r=Bv[e]??[],o=n??Fv[e]??"#888",[i,l]=u.useState(0);return r.length===0||i>=r.length?s.jsx(zv,{size:t,color:o}):s.jsx("img",{src:r[i],alt:`${e} logo`,width:t,height:t,loading:"lazy",onError:()=>l(i+1),style:{flexShrink:0,display:"block",objectFit:"contain"}})}const vr="http://127.0.0.1:11434";function qv({t:e,onStatus:t}){const[n,r]=u.useState("hashed"),[o,i]=u.useState(vr),[l,a]=u.useState(""),[d,c]=u.useState(""),[f,p]=u.useState(!1),[h,g]=u.useState({ollama:[],openai:[]}),[S,x]=u.useState([]),[b,k]=u.useState(!1),[C,E]=u.useState({id:"",semantic:!1,reindexRequired:!1}),[v,w]=u.useState(null),[A,R]=u.useState(null),y=u.useCallback(async P=>{try{const q=await N.listEmbeddingModels(P);g(q.catalog),x(q.installed),k(q.ollamaReachable)}catch{}},[]);u.useEffect(()=>{(async()=>{try{const P=await N.getEmbeddingSettings();r(P.settings.provider),i(P.settings.endpoint||vr),a(P.settings.model),p(P.settings.apiKeySet),E({id:P.activeProviderId,semantic:P.semantic,reindexRequired:P.reindexRequired}),await y(P.settings.endpoint||vr)}catch(P){R(P instanceof Error?P.message:String(P))}})()},[y]);const M=async(P,q)=>{w(P),R(null);try{await q()}catch(O){R(O instanceof Error?O.message:String(O))}finally{w(null)}},$=(P,q)=>M("save",async()=>{const O=await N.saveEmbeddingSettings({provider:P,...P==="ollama"?{endpoint:o}:{},...q?{model:q}:{},...P==="openai"&&d?{apiKey:d}:{}});r(P),a(q),d&&(p(!0),c("")),E({id:O.activeProviderId,semantic:O.semantic,reindexRequired:O.reindexRequired}),t==null||t(O.semantic?"Semantic embeddings enabled. Re-index to apply them to your catalog.":"Using the offline hashed embedder — retrieval stays lexical.")}),T=n==="openai"?h.openai:h.ollama,L={border:`1px solid ${e.headerBorder}`,borderRadius:10,padding:14,background:e.cellBg,marginTop:14},I={fontSize:11,fontWeight:700,color:e.textMuted,textTransform:"uppercase",letterSpacing:"0.05em"},G={height:30,padding:"0 9px",borderRadius:6,border:`1px solid ${e.btnBorder}`,background:e.appBg,color:e.textPrimary,fontSize:12,fontFamily:e.font,width:"100%"},Y=P=>({display:"inline-flex",alignItems:"center",gap:6,height:28,padding:"0 11px",borderRadius:6,border:`1px solid ${P?e.accent:e.btnBorder}`,background:P?e.accent:e.btnBg,color:P?"#fff":e.textSecondary,fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:e.font});return s.jsxs("div",{style:L,children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13.5,fontWeight:700,color:e.textPrimary},children:"Embeddings"}),s.jsxs("div",{style:{fontSize:12,color:e.textSecondary,marginTop:4,lineHeight:1.5,maxWidth:620},children:["Decides whether a plain-English question can match a metric by ",s.jsx("em",{children:"meaning"}),' or only by shared words. The offline default is lexical — it cannot connect "drinks" to a ',s.jsx("code",{children:"beverage_revenue"})," metric."]})]}),s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,padding:"4px 9px",borderRadius:999,fontSize:11,fontWeight:650,background:C.semantic?"var(--status-success-bg)":"var(--status-warning-bg)",color:C.semantic?"var(--status-success)":"var(--status-warning)",border:`1px solid ${C.semantic?"var(--status-success-border)":"var(--status-warning-border)"}`},children:[C.semantic?s.jsx(hx,{size:11}):s.jsx(px,{size:11}),C.semantic?"Semantic":"Lexical only"]})]}),s.jsx("div",{style:{display:"flex",gap:6,marginTop:12,flexWrap:"wrap"},children:["hashed","ollama","openai"].map(P=>s.jsx("button",{type:"button",onClick:()=>{r(P),P==="hashed"&&$("hashed","")},style:{...Y(n===P),textTransform:"capitalize"},children:P==="hashed"?"Offline (default)":P==="ollama"?"Ollama (local)":"OpenAI"},P))}),n==="ollama"&&s.jsxs("div",{style:{marginTop:12},children:[s.jsx("div",{style:I,children:"Ollama endpoint"}),s.jsxs("div",{style:{display:"flex",gap:6,marginTop:4,alignItems:"center"},children:[s.jsx("input",{value:o,onChange:P=>i(P.target.value),onBlur:()=>void y(o),style:G,placeholder:vr}),s.jsx("span",{style:{fontSize:11,whiteSpace:"nowrap",color:b?"var(--status-success)":e.textMuted},children:b?"reachable":"not reachable"})]}),!b&&s.jsx("div",{style:{fontSize:11.5,color:e.textMuted,marginTop:6,lineHeight:1.5},children:"Start Ollama first — nothing leaves your machine with the local option."})]}),n==="openai"&&s.jsxs("div",{style:{marginTop:12},children:[s.jsxs("div",{style:I,children:["API key ",f?"(stored — leave blank to keep)":""]}),s.jsx("input",{type:"password",value:d,onChange:P=>c(P.target.value),style:{...G,marginTop:4},placeholder:f?"••••••••":"sk-…"}),s.jsx("div",{style:{fontSize:11.5,color:e.textMuted,marginTop:6,lineHeight:1.5},children:"Catalog text (metric names, descriptions, business context) is sent to this endpoint to be embedded. Your answer-model key is never reused for this."})]}),n!=="hashed"&&s.jsxs("div",{style:{marginTop:14},children:[s.jsx("div",{style:I,children:"Model"}),s.jsx("div",{style:{display:"grid",gap:6,marginTop:6},children:T.map(P=>{const q=n==="openai"||S.includes(P.model),O=l===P.model;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"9px 11px",borderRadius:8,border:`1px solid ${O?e.accent:e.btnBorder}`,background:O?`${e.accent}0f`:e.appBg},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:12.5,fontWeight:650,color:e.textPrimary,fontFamily:e.fontMono},children:P.model}),P.recommended&&s.jsx("span",{style:{fontSize:10,fontWeight:700,color:e.accent,background:`${e.accent}18`,borderRadius:999,padding:"1px 7px"},children:"Recommended"}),s.jsxs("span",{style:{fontSize:10.5,color:e.textMuted},children:[P.dimensions," dims · ",P.size]})]}),s.jsx("div",{style:{fontSize:11.5,color:e.textSecondary,marginTop:3,lineHeight:1.45},children:P.description})]}),q?s.jsx("button",{type:"button",onClick:()=>void $(n,P.model),disabled:v!==null,style:Y(O),children:O?s.jsxs(s.Fragment,{children:[s.jsx(Ug,{size:12})," In use"]}):"Use this"}):s.jsx("button",{type:"button",disabled:v!==null||!b,onClick:()=>void M(`install:${P.model}`,async()=>{await N.installEmbeddingModel(P.model,o),await y(o),await N.saveEmbeddingSettings({provider:"ollama",endpoint:o,model:P.model}),a(P.model);const W=await N.getEmbeddingSettings();E({id:W.activeProviderId,semantic:W.semantic,reindexRequired:W.reindexRequired}),t==null||t(`${P.model} installed and selected. Re-index to apply it.`)}),style:Y(!0),children:v===`install:${P.model}`?s.jsxs(s.Fragment,{children:[s.jsx(Fn,{size:12,className:"dql-spin"})," Installing…"]}):s.jsxs(s.Fragment,{children:[s.jsx(Pc,{size:12})," Install"]})})]},P.model)})})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:14,flexWrap:"wrap"},children:[s.jsxs("button",{type:"button",disabled:v!==null,onClick:()=>void M("test",async()=>{const P=await N.testEmbeddingProvider();t==null||t(`${P.providerId} responded in ${P.elapsedMs} ms (${P.dimensions} dims).`)}),style:Y(),children:[v==="test"?s.jsx(Fn,{size:12,className:"dql-spin"}):null," Test"]}),s.jsxs("button",{type:"button",disabled:v!==null,onClick:()=>void M("reindex",async()=>{const P=await N.reindexEmbeddings();E(q=>({...q,reindexRequired:!1})),t==null||t(P.upgraded?`Catalog re-embedded with ${P.providerId}.`:`No re-index needed — ${P.reason??"already current"}.`)}),style:Y(C.reindexRequired),children:[v==="reindex"?s.jsx(Fn,{size:12,className:"dql-spin"}):s.jsx(Ir,{size:12})," Re-index catalog"]}),s.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.fontMono},children:["active: ",C.id||"—"]})]}),C.reindexRequired&&s.jsx("div",{style:{fontSize:11.5,color:"var(--status-warning)",marginTop:8,lineHeight:1.5},children:"The catalog still holds vectors from the previous embedder. Re-index to search with the new one — until then the vector lane keeps using the old index."}),A&&s.jsx("div",{style:{fontSize:11.5,color:e.error,marginTop:8,lineHeight:1.5},children:A})]})}function Uv({values:e,onChange:t,placeholder:n,style:r,ariaLabel:o,title:i,disabled:l}){const a=e.join(", "),[d,c]=u.useState(a),f=u.useRef(!1);return u.useEffect(()=>{f.current||c(a)},[a]),s.jsx("input",{type:"text",value:d,disabled:l,"aria-label":o,title:i,placeholder:n,style:r,onFocus:()=>{f.current=!0},onBlur:()=>{f.current=!1,c(Yi(d).join(", "))},onChange:p=>{c(p.target.value),t(Yi(p.target.value))}})}function Yi(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Wv(e){var t;return((t=e.evaluation)==null?void 0:t.status)==="failed"?"Rerun checks & approve":"Run checks & approve"}function Kv(e){var t,n,r,o;return(t=e.exclusions)!=null&&t.some(i=>i.reason==="superseded")?"Superseded — excluded":(n=e.exclusions)!=null&&n.some(i=>i.reason==="conflict")?"Conflict — excluded":(r=e.inspection)!=null&&r.state&&e.inspection.state!=="current"?`${e.inspection.state} — excluded`:((o=e.evaluation)==null?void 0:o.status)==="failed"?"Evaluation failed":e.status==="approved"?"Current & applied":e.status}function Vv(e,t,n){const r=n.trim();return{...e,[t]:r||void 0}}async function Hv(e,t){try{return await e()}finally{await t()}}const Gv=["claude-code","codex","anthropic","openai","gemini","ollama","custom-openai"],Jv=["claude-code","codex"],Qv=["anthropic","openai","gemini","ollama","custom-openai"];function sd(e){switch(e){case"ollama":return"http://host.docker.internal:11434 or http://127.0.0.1:11434";case"anthropic":return"Base URL (optional) — e.g. https://api.anthropic.com or your gateway";case"gemini":return"Base URL (optional) — e.g. https://generativelanguage.googleapis.com/v1beta or your gateway";case"openai":return"Base URL (optional) — e.g. https://api.openai.com/v1 or your gateway";case"custom-openai":default:return"Base URL — e.g. https://your-gateway/v1"}}function jo({includeMemory:e=!0,embedded:t=!1,section:n,editorMode:r="settings",onProviderConfigured:o}){const{state:i}=xe(),l=Fe[i.themeMode],[a,d]=u.useState([]),[c,f]=u.useState([]),[p,h]=u.useState({}),[g,S]=u.useState({path:"",entries:[],warnings:[]}),[x,b]=u.useState([]),[k,C]=u.useState(!0),[E,v]=u.useState(null),w=async()=>{C(!0);try{const[y,M,$,T]=await Promise.all([N.getSettingsEnvStatus(),N.getProviderSettings(),N.getRemoteMcpSettings(),e?N.listAgentMemory():Promise.resolve({memories:[]})]);d(y.groups),f(M.providers),S($.settings),b(T.memories)}finally{C(!1)}};u.useEffect(()=>{w()},[]),u.useEffect(()=>{if(k)return;let y=!1;return N.getProviderCliStatus().then(M=>{y||h(M.status??{})}),()=>{y=!0}},[k]);const A=u.useMemo(()=>c.filter(y=>y.enabled&&y.configured).length,[c]),R=c.find(y=>y.active&&y.configured);return s.jsxs("div",{style:{padding:t?0:24,maxWidth:t?void 0:1180},children:[!n&&s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:18,fontWeight:700},children:"AI providers, memory & connections"}),s.jsxs("div",{style:{color:l.textSecondary,fontSize:13,marginTop:6,lineHeight:1.5,maxWidth:820},children:["Connect a model provider, manage the agent's learning & memory, and (optionally) attach MCP servers. Secrets stay under ",s.jsx("code",{children:".dql/"})," and are never returned raw."]})]}),s.jsx(nS,{configured:A,total:c.length||Gv.length,activeLabel:R==null?void 0:R.label,t:l})]}),E&&s.jsx("div",{style:{marginTop:14,border:`1px solid ${l.headerBorder}`,borderRadius:8,padding:"10px 12px",fontSize:12,color:l.textSecondary,background:l.cellBg},children:E}),k?s.jsx("div",{style:{marginTop:24,color:l.textSecondary},children:"Loading settings..."}):s.jsxs(s.Fragment,{children:[n==="providers"&&s.jsxs(s.Fragment,{children:[s.jsx(Zv,{providers:c,cliStatus:p,t:l,onSaved:y=>f(y),onStatus:v,editorMode:r,onProviderConfigured:o}),s.jsx(qv,{t:l,onStatus:v})]}),!n&&s.jsxs("section",{style:{marginTop:22},children:[s.jsx(an,{title:"Model providers",detail:"Connect at least one AI provider — it powers governed answers, block suggestions, and research. Sign in with a Claude or ChatGPT subscription, or use an API key / local model.",t:l}),s.jsx(Zi,{title:"Use your subscription",detail:"No API key — sign in with the provider's CLI. DQL runs each request through it using your plan.",t:l}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:Jv.map(y=>{const M=c.find($=>$.id===y);return M?s.jsx(na,{provider:M,cliStatus:p[y],t:l,onSaved:$=>f($),onStatus:v},y):null})}),s.jsx(Zi,{title:"API key & local providers",detail:"Paste an API key (or set the env var), point at a gateway, or run a local model with Ollama.",t:l}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:Qv.map(y=>{const M=c.find($=>$.id===y);return M?s.jsx(na,{provider:M,t:l,onSaved:$=>f($),onStatus:v},y):null})})]}),(!n||n==="memory")&&e&&s.jsxs("section",{style:{marginTop:n?0:22},children:[s.jsx(an,{title:"Agent learning & memory",detail:"Durable business context you add explicitly, plus a separate governed correction queue. Advisory context never overrides current certified metadata, dbt truth, or routing.",t:l}),s.jsx(tS,{memories:x,t:l,onChange:b,onStatus:v}),s.jsx(eS,{t:l,onStatus:v})]}),n==="advanced"&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsx(an,{title:"MCP servers and connectors",detail:"Remote MCP servers can be attached to OpenAI and Claude SDK chat. OpenAI hosted connectors are OpenAI-only.",t:l}),s.jsx(Xi,{settings:g,t:l,onChange:S,onStatus:v})]}),s.jsxs("section",{style:{marginTop:22},children:[s.jsx(an,{title:"Runtime status",detail:"Environment variables remain supported for Docker, CI, and shell-based setup.",t:l}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:a.map(y=>s.jsx(oa,{group:y,t:l},y.id))})]})]}),!n&&s.jsxs("details",{style:{marginTop:22,border:`1px solid ${l.headerBorder}`,borderRadius:10,background:l.cellBg,overflow:"hidden"},children:[s.jsxs("summary",{style:{cursor:"pointer",padding:"13px 16px",fontSize:13,fontWeight:650,listStyle:"none",color:l.textPrimary},children:["Advanced — MCP connections & runtime status",s.jsx("span",{style:{color:l.textMuted,fontWeight:400,marginLeft:8,fontSize:12},children:"optional for most users"})]}),s.jsxs("div",{style:{padding:"4px 16px 18px"},children:[s.jsxs("section",{style:{marginTop:14},children:[s.jsx(an,{title:"MCP servers and connectors",detail:"Remote MCP servers can be attached to OpenAI and Claude SDK chat. OpenAI hosted connectors are OpenAI-only.",t:l}),s.jsx(Xi,{settings:g,t:l,onChange:S,onStatus:v})]}),s.jsxs("section",{style:{marginTop:22},children:[s.jsx(an,{title:"Runtime status",detail:"Environment variables remain supported for Docker, CI, and shell-based setup.",t:l}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:a.map(y=>s.jsx(oa,{group:y,t:l},y.id))})]})]})]})]})]})}function Xi({settings:e,t,onChange:n,onStatus:r}){const[o,i]=u.useState(e.entries),[l,a]=u.useState("form"),[d,c]=u.useState(()=>An(e.entries)),[f,p]=u.useState(null),[h,g]=u.useState(!1);u.useEffect(()=>{i(e.entries),c(An(e.entries)),p(null)},[e]);const S=T=>{i(T),c(An(T)),p(null)},x=(T,L)=>{S(o.map((I,G)=>G===T?Yt({...I,...L}):I))},b=T=>{S(o.filter((L,I)=>I!==T))},k=()=>{S([...o,{kind:"server",name:"",url:"",enabled:!0,trusted:!1,providers:["openai","anthropic"]}])},C=()=>{S([...o,{kind:"connector",name:"",connectorId:"connector_googledrive",enabled:!0,trusted:!1,providers:["openai"]}])},E=T=>{T==="json"&&c(An(o)),p(null),a(T)},v=()=>{const T=sS(d);return i(T),c(An(T)),p(null),T},w=()=>{try{v()}catch(T){p(T instanceof Error?T.message:String(T))}},A=()=>{try{v(),a("form"),r("MCP JSON applied.")}catch(T){p(T instanceof Error?T.message:String(T))}},R=async()=>{g(!0);try{const T=l==="json"?v():o,L=await N.saveRemoteMcpSettings(T.map(G=>Yt(G)));n(L.settings);const I=L.settings.warnings.length?` ${L.settings.warnings.join(" ")}`:"";r(`MCP connections saved.${I}`)}catch(T){const L=T instanceof Error?T.message:String(T);l==="json"&&p(L),r(L)}finally{g(!1)}},y=o.filter(T=>T.enabled&&T.trusted).length,M=o.filter(T=>T.kind==="server").length,$=o.filter(T=>T.kind==="connector").length;return s.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,padding:14},children:[s.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"},children:[s.jsxs("div",{style:{flex:1,minWidth:240},children:[s.jsxs("div",{style:{fontSize:12,color:t.textSecondary},children:[y," trusted connection",y===1?"":"s"," available to SDK providers"]}),s.jsxs("div",{style:{fontSize:11,color:t.textMuted,marginTop:3},children:[M," remote server",M===1?"":"s"," / ",$," OpenAI connector",$===1?"":"s"]}),e.path&&s.jsx("div",{style:{fontSize:11,color:t.textMuted,marginTop:3,fontFamily:t.fontMono},children:e.path})]}),s.jsxs("div",{style:{display:"flex",border:`1px solid ${t.headerBorder}`,borderRadius:6,overflow:"hidden"},children:[s.jsx("button",{type:"button",onClick:()=>E("form"),style:sa(t,l==="form"),children:"Form"}),s.jsx("button",{type:"button",onClick:()=>E("json"),style:sa(t,l==="json"),children:"JSON import"})]}),s.jsx("button",{type:"button",onClick:k,style:ht(t,!1),children:"Add MCP server"}),s.jsx("button",{type:"button",onClick:C,style:ht(t,!1),children:"Add OpenAI connector"}),s.jsx("button",{type:"button",onClick:R,disabled:h,style:ht(t,!0),children:"Save MCP"})]}),s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:10,marginTop:12},children:[s.jsx(Co,{title:"Remote MCP server",detail:"Use URL-based MCP servers with OpenAI and Claude. Mark trusted when the server is approved for model tool use.",badge:"OpenAI + Claude",t}),s.jsx(Co,{title:"OpenAI connector",detail:"Use OpenAI hosted connectors such as Google Drive. These are skipped for Claude because Anthropic does not use connector IDs.",badge:"OpenAI only",t}),s.jsx(Co,{title:"JSON import",detail:"Paste DQL JSON, OpenAI Responses tools, or Claude mcp_servers. DQL saves the normalized project config.",badge:"DQL normalized",t})]}),e.warnings.length>0&&s.jsx("div",{style:{marginTop:10,color:"#9a5a00",fontSize:12,lineHeight:1.4},children:e.warnings.join(" ")}),l==="json"?s.jsxs("div",{style:{marginTop:14},children:[s.jsxs("div",{style:{color:t.textSecondary,fontSize:12,lineHeight:1.45,marginBottom:8},children:["Paste DQL MCP JSON, OpenAI Responses ",s.jsx("code",{children:"tools"}),", or Claude ",s.jsx("code",{children:"mcp_servers"}),". Existing stored tokens are preserved when ",s.jsx("code",{children:"authorizationToken"})," is omitted and the same kind/name is kept."]}),s.jsx("textarea",{value:d,onChange:T=>{c(T.target.value),p(null)},spellCheck:!1,rows:18,style:{..._e(t),width:"100%",minHeight:360,resize:"vertical",fontFamily:t.fontMono,fontSize:12,lineHeight:1.45}}),f&&s.jsx("div",{style:{color:"#b42318",fontSize:12,marginTop:8},children:f}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:10},children:[s.jsx("button",{type:"button",onClick:w,style:ht(t,!1),children:"Format JSON"}),s.jsx("button",{type:"button",onClick:A,style:ht(t,!1),children:"Apply to form"})]})]}):o.length===0?s.jsx("div",{style:{marginTop:14,color:t.textSecondary,fontSize:12},children:"No MCP connections configured."}):s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(340px, 1fr))",gap:12,marginTop:14},children:o.map((T,L)=>s.jsxs("div",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,padding:12,background:t.appBg},children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[s.jsxs("select",{value:T.kind,onChange:I=>x(L,{kind:I.target.value==="connector"?"connector":"server",providers:I.target.value==="connector"?["openai"]:T.providers}),style:{..._e(t),width:116},children:[s.jsx("option",{value:"server",children:"Server"}),s.jsx("option",{value:"connector",children:"Connector"})]}),s.jsx("input",{value:T.name,onChange:I=>x(L,{name:I.target.value}),placeholder:"Name",style:{..._e(t),flex:1}}),s.jsx("button",{type:"button",onClick:()=>b(L),style:ht(t,!1),children:"Remove"})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:10},children:[T.kind==="connector"?s.jsx("input",{value:T.connectorId??"",onChange:I=>x(L,{connectorId:I.target.value}),placeholder:"connector_googledrive",style:_e(t)}):s.jsx("input",{value:T.url??"",onChange:I=>x(L,{url:I.target.value}),placeholder:"https://example.com/mcp or /sse",style:_e(t)}),s.jsx("input",{value:T.description??"",onChange:I=>x(L,{description:I.target.value}),placeholder:"Description shown to the model",style:_e(t)}),s.jsx("input",{value:T.authorizationTokenEnv??"",onChange:I=>x(L,{authorizationTokenEnv:I.target.value}),placeholder:"Authorization token env var",style:_e(t)}),s.jsx("input",{value:T.authorizationToken??"",onChange:I=>x(L,{authorizationToken:I.target.value}),type:"password",placeholder:T.hasAuthorizationToken?`Leave blank to keep ${T.authorizationTokenPreview??"stored token"}`:"Optional OAuth token",style:_e(t)}),s.jsx(Uv,{values:T.allowedTools??[],onChange:I=>x(L,{allowedTools:I}),placeholder:"Allowed tools, comma separated",style:_e(t)})]}),s.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",marginTop:10},children:[s.jsxs("label",{style:En(t),children:[s.jsx("input",{type:"checkbox",checked:T.enabled,onChange:I=>x(L,{enabled:I.target.checked})})," Enabled"]}),s.jsxs("label",{style:En(t),children:[s.jsx("input",{type:"checkbox",checked:T.trusted,onChange:I=>x(L,{trusted:I.target.checked})})," Trusted"]}),s.jsxs("label",{style:En(t),children:[s.jsx("input",{type:"checkbox",checked:!!T.deferLoading,onChange:I=>x(L,{deferLoading:I.target.checked})})," Defer tools"]}),s.jsxs("label",{style:En(t),children:[s.jsx("input",{type:"checkbox",checked:(T.providers??[]).includes("openai"),onChange:I=>x(L,{providers:aa(T.providers,"openai",I.target.checked)})})," OpenAI"]}),s.jsxs("label",{style:En(t),children:[s.jsx("input",{type:"checkbox",checked:(T.providers??[]).includes("anthropic"),disabled:T.kind==="connector",onChange:I=>x(L,{providers:aa(T.providers,"anthropic",I.target.checked)})})," Anthropic"]})]})]},`${T.kind}-${T.name||L}`))})]})}function Co({title:e,detail:t,badge:n,t:r}){return s.jsxs("div",{style:{border:`1px solid ${r.headerBorder}`,borderRadius:8,background:r.appBg,padding:10},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("div",{style:{fontSize:12,fontWeight:700,color:r.textPrimary},children:e}),s.jsx("span",{style:{marginLeft:"auto",border:`1px solid ${r.accent}33`,borderRadius:999,padding:"2px 7px",color:r.accent,background:`${r.accent}12`,fontSize:10,fontWeight:800,whiteSpace:"nowrap"},children:n})]}),s.jsx("div",{style:{color:r.textSecondary,fontSize:11,lineHeight:1.45,marginTop:6},children:t})]})}function Yv({status:e,command:t,loginCmd:n,t:r}){let o=r.textMuted,i=r.textMuted,l="Checking for the CLI…";if(e)if(!e.installed)o=r.warning,i=r.warning,l=s.jsxs(s.Fragment,{children:[s.jsx("code",{children:t})," CLI not found on this machine — install it, then sign in."]});else if(!e.loggedIn)o=r.warning,i=r.warning,l=s.jsxs(s.Fragment,{children:["Installed but not signed in — run ",s.jsxs("code",{children:[t," ",n]}),"."]});else{o=r.success,i=r.success;const a=[e.email,e.subscriptionType?`${e.subscriptionType} plan`:e.authMethod].filter(Boolean).join(" · ");l=s.jsxs(s.Fragment,{children:["Signed in",a?s.jsxs(s.Fragment,{children:[" — ",a]}):"",". Ready to use."]})}return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:12,color:o},children:[s.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:i,flex:"0 0 auto"}}),s.jsx("span",{children:l})]})}function Zi({title:e,detail:t,t:n}){return s.jsxs("div",{style:{margin:"20px 0 10px"},children:[s.jsx("div",{style:{fontSize:12.5,fontWeight:750,color:n.textPrimary,letterSpacing:"-0.01em"},children:e}),s.jsx("div",{style:{fontSize:11.5,color:n.textSecondary,marginTop:2,lineHeight:1.45},children:t})]})}function id(e){return e==="codex"?"codex":"claude"}function ad({oauthProvider:e,label:t,model:n,setModel:r,cliStatus:o,command:i,loginCmd:l,t:a,onStatus:d,onConnected:c}){const[f,p]=u.useState(null),[h,g]=u.useState(!1),S=u.useRef(null),x=u.useRef(!0),b=e==="codex"?"ChatGPT":"Claude",k=u.useCallback(()=>{S.current!==null&&(window.clearInterval(S.current),S.current=null)},[]);u.useEffect(()=>(x.current=!0,N.getOAuthStatus(e).then(v=>{x.current&&p(v)}).catch(()=>{}),()=>{x.current=!1,k()}),[e,k]);const C=async()=>{g(!0);try{const v=await N.startOAuth(e);p(v),window.open(v.url,"_blank","noopener,noreferrer"),d(`Opened your browser to sign in to ${b}. Complete it there — this updates automatically.`);const w=Date.now();k(),S.current=window.setInterval(async()=>{const A=await N.getOAuthStatus(e).catch(()=>null);if(!x.current){k();return}A&&p(A),A!=null&&A.connected?(k(),g(!1),c(A.defaultModel)):Date.now()-w>300*1e3&&(k(),g(!1),d(`${b} sign-in timed out. Try again.`))},2500)}catch(v){g(!1),d(v instanceof Error?v.message:String(v))}},E=async()=>{g(!0),k();try{p(await N.signOutOAuth(e)),d(`Signed out of ${b}.`)}catch(v){d(v instanceof Error?v.message:String(v))}finally{g(!1)}};if(f!=null&&f.connected){const v=f.models.length>0?f.models:[f.defaultModel];return s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12.5},children:[s.jsxs("span",{style:{color:"#16a34a",fontWeight:700},children:["✓ Signed in to ",b]}),f.email?s.jsxs("span",{style:{color:a.textSecondary},children:["as ",f.email]}):null]}),s.jsx("label",{style:{fontSize:11,color:a.textSecondary,fontWeight:600},children:"Model"}),s.jsx("select",{value:n||f.defaultModel,onChange:w=>r(w.target.value),style:_e(a),children:v.map(w=>s.jsx("option",{value:w,children:w},w))}),s.jsx("div",{children:s.jsx("button",{type:"button",onClick:E,disabled:h,style:ht(a,!1),children:"Sign out"})})]})}return s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsx("button",{type:"button",onClick:C,disabled:h,style:ht(a,!0),children:h||f!=null&&f.pending?`Waiting for ${b}…`:`Sign in with ${b}`}),s.jsxs("div",{style:{fontSize:12,color:a.textSecondary,lineHeight:1.5},children:["No API key needed — signs in with your ",b," subscription in the browser."]}),s.jsxs("details",{children:[s.jsx("summary",{style:{fontSize:11.5,color:a.textSecondary,cursor:"pointer"},children:"Prefer the CLI?"}),s.jsxs("div",{style:{marginTop:6,display:"grid",gap:6},children:[s.jsx(Yv,{status:o,command:i,loginCmd:l,t:a}),s.jsxs("div",{style:{fontSize:11.5,color:a.textSecondary,lineHeight:1.5},children:["Or install the ",s.jsx("code",{children:i})," CLI and run ",s.jsxs("code",{children:[i," ",l]}),", then Enable + Save."]})]})]})]})}const Ar=[{key:"claude",label:"Anthropic Claude",modes:{subscription:"claude-code",api:"anthropic"}},{key:"openai",label:"OpenAI",modes:{subscription:"codex",api:"openai"}},{key:"gemini",label:"Google Gemini",modes:{api:"gemini"}},{key:"ollama",label:"Ollama — local",modes:{local:"ollama"}},{key:"gateway",label:"Custom OpenAI-compatible",modes:{api:"custom-openai"}}],ea={subscription:{label:"Subscription",hint:"Sign in — no API key"},api:{label:"API key",hint:"Paste a key or use env var"},local:{label:"Local",hint:"Runs on this machine"}};function Xv(e){if(!e)return"claude";const t=Ar.find(n=>Object.values(n.modes).includes(e));return(t==null?void 0:t.key)??"claude"}function Zv({providers:e,cliStatus:t,t:n,onSaved:r,onStatus:o,editorMode:i,onProviderConfigured:l}){var J;const a=e.find(B=>B.active&&B.configured),[d,c]=u.useState(()=>Xv(a==null?void 0:a.id)),f=Ar.find(B=>B.key===d)??Ar[0],p=Object.keys(f.modes),[h,g]=u.useState(()=>p.find(ne=>f.modes[ne]===(a==null?void 0:a.id))??p[0]),S=p.includes(h)?h:p[0],x=f.modes[S],b=e.find(B=>B.id===x),[k,C]=u.useState(""),[E,v]=u.useState((b==null?void 0:b.baseUrl)??""),[w,A]=u.useState((b==null?void 0:b.model)??""),[R,y]=u.useState((b==null?void 0:b.reasoningEffort)??"auto"),[M,$]=u.useState(!1),[T,L]=u.useState({state:"idle"}),[I,G]=u.useState({state:"idle"});u.useEffect(()=>{C(""),v((b==null?void 0:b.baseUrl)??""),A((b==null?void 0:b.model)??""),y((b==null?void 0:b.reasoningEffort)??"auto"),G({state:"idle"})},[x,b==null?void 0:b.baseUrl,b==null?void 0:b.model,b==null?void 0:b.reasoningEffort]);const Y=async()=>{if(!a)return;L({state:"testing"});const B=Date.now(),ne=await N.testProviderSettings(a.id,{}),ce=ne.ok!==!1;L({state:"done",ok:ce,message:ne.message,seconds:((Date.now()-B)/1e3).toFixed(1)})},P=()=>{var B;return x==="custom-openai"&&!E.trim()?"Custom OpenAI-compatible providers require a Base URL.":x==="custom-openai"&&!w.trim()?"Custom OpenAI-compatible providers require a model.":S==="api"&&x!=="custom-openai"&&!k.trim()&&!(b!=null&&b.hasApiKey)?`Add an API key${(B=b==null?void 0:b.envVars)!=null&&B[0]?` or set ${b.envVars[0]}`:""}.`:S==="local"&&!E.trim()&&!w.trim()&&!(b!=null&&b.configured)?"Set an Ollama endpoint or model before testing.":null},q=async()=>{const B=P();if(B)return G({state:"done",ok:!1,message:B}),!1;G({state:"testing"});const ne=await N.testProviderSettings(x,{apiKey:k||void 0,baseUrl:E||void 0,model:w||void 0});return G({state:"done",ok:ne.ok,message:ne.message}),ne.ok},O=async()=>{$(!0);try{if(!await q()){o("Test failed. Your existing provider configuration was not changed.");return}const ne=await N.saveProviderSettings({id:x,enabled:!0,apiKey:k||void 0,baseUrl:E,model:w,reasoningEffort:R});r(ne.providers);const ce=ne.providers.find(re=>re.id===x);ce&&(l==null||l(ce)),o(`${f.label} passed its test and is now the active provider.`)}catch(B){o(B instanceof Error?B.message:String(B))}finally{$(!1)}},W=async B=>{const ne=w||B;A(ne);try{const ce=await N.saveProviderSettings({id:x,enabled:!0,model:ne});r(ce.providers);const re=ce.providers.find(ge=>ge.id===x);re&&(l==null||l(re)),o(`${f.label} subscription configured and activated. Run Test to verify the next governed request.`)}catch(ce){o(ce instanceof Error?ce.message:String(ce))}},se={fontSize:11,fontWeight:650,color:n.textSecondary},H={..._e(n),borderRadius:8},te=S==="subscription"?"Uses your existing plan through the provider’s sign-in — nothing billed per token.":S==="local"?"Everything runs on this machine — no data leaves your network.":"Keys stay in .dql/ and are never returned raw.";return s.jsxs("div",{style:{width:"min(680px, 100%)",display:"flex",flexDirection:"column",gap:16},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:17,fontWeight:700,color:n.textPrimary},children:"AI provider"}),s.jsxs("div",{style:{fontSize:12.5,color:n.textMuted,marginTop:3,lineHeight:1.5},children:["AI is optional. Without it, deterministic queries, dbt metadata, connections, and governed non-AI paths remain available. Keys stay in ",s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:11.5},children:".dql/"})," and are never returned raw."]})]}),a?s.jsxs("div",{style:{border:"1px solid var(--status-success-border)",borderRadius:12,background:n.cellBg,padding:"16px 18px",display:"flex",alignItems:"center",gap:12},children:[s.jsx("span",{style:{width:36,height:36,borderRadius:9,background:"var(--status-success-bg)",color:"var(--status-success)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx(Lc,{size:17,strokeWidth:1.75})}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{fontSize:13,fontWeight:700,color:n.textPrimary},children:["Active · ",a.label,a.model?` — ${a.model}`:""]}),s.jsx("div",{style:{fontSize:11.5,color:T.state==="done"&&T.ok===!1?"var(--status-error)":"var(--status-success)",marginTop:2},children:T.state==="testing"?"Testing…":T.state==="done"?T.ok?`Test passed · ${T.seconds}s`:T.message||"Test failed":a.source==="env"?"Configured from environment — run Test to verify":"Configured — run Test to verify reachability"})]}),s.jsx("button",{type:"button",onClick:()=>void Y(),disabled:T.state==="testing",style:{display:"inline-flex",alignItems:"center",gap:6,height:30,padding:"0 13px",borderRadius:8,border:`1px solid ${n.headerBorder}`,background:n.cellBg,color:n.textSecondary,fontSize:12,fontWeight:650,cursor:"pointer",fontFamily:n.font,flexShrink:0},children:T.state==="testing"?"Testing…":"Test"})]}):null,s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:n.cellBg,padding:18,display:"flex",flexDirection:"column",gap:14},children:[s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:12},children:s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:se,children:"Provider"}),s.jsx("select",{value:f.key,onChange:B=>{c(B.target.value),g("subscription")},style:H,children:Ar.map(B=>s.jsx("option",{value:B.key,children:B.label},B.key))})]})}),s.jsxs("div",{children:[s.jsx("span",{style:{...se,display:"block",marginBottom:6},children:"How do you want to connect?"}),s.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:p.map(B=>{const ne=B===S;return s.jsxs("button",{type:"button",onClick:()=>g(B),style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 13px",borderRadius:9,border:`1.5px solid ${ne?n.accent:n.headerBorder}`,background:ne?"var(--accent-dim)":n.cellBg,cursor:"pointer",fontFamily:n.font,textAlign:"left"},children:[s.jsx("span",{style:{width:13,height:13,borderRadius:999,border:`1.5px solid ${ne?n.accent:"var(--border-strong)"}`,background:ne?n.accent:n.cellBg,boxShadow:ne?`inset 0 0 0 2.5px ${n.cellBg}`:"none",flexShrink:0}}),s.jsxs("span",{style:{display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{fontSize:12,fontWeight:650,color:n.textPrimary},children:ea[B].label}),s.jsx("span",{style:{fontSize:10,color:n.textMuted},children:ea[B].hint})]})]},B)})})]}),S==="subscription"&&b?s.jsx("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:9,background:"var(--bg-1)",padding:"11px 13px"},children:s.jsx(ad,{oauthProvider:id(x),label:b.label,model:w,setModel:A,cliStatus:t[x],command:b.command,loginCmd:x==="claude-code"?"/login":"login",t:n,onStatus:o,onConnected:W})}):null,S==="api"?s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:8,alignItems:"end"},children:[s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:se,children:"API key"}),s.jsx("input",{type:"password",value:k,onChange:B=>C(B.target.value),placeholder:b!=null&&b.hasApiKey?"Leave blank to keep existing key":"API key",style:{...H,fontFamily:n.fontMono}})]}),(J=b==null?void 0:b.envVars)!=null&&J[0]?s.jsxs("span",{style:{fontSize:10.5,color:n.textMuted,paddingBottom:9},children:["or set ",s.jsx("span",{style:{fontFamily:n.fontMono},children:b.envVars[0]})]}):null]}):null,S==="local"?s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:se,children:"Host"}),s.jsx("input",{value:E,onChange:B=>v(B.target.value),placeholder:"http://localhost:11434",style:{...H,fontFamily:n.fontMono}})]}),s.jsx("div",{style:{display:"flex",alignItems:"flex-end",paddingBottom:2},children:s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:11.5,color:b!=null&&b.enabled?"var(--status-success)":n.textMuted},children:[s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:b!=null&&b.enabled?"var(--status-success)":"var(--border-strong)"}}),b!=null&&b.enabled?"Ollama configured":"Point at your Ollama host"]})})]}):null,i==="setup"?s.jsxs("details",{style:{borderTop:"1px solid var(--border-subtle)",paddingTop:10},children:[s.jsx("summary",{style:{fontSize:11.5,fontWeight:650,color:n.textSecondary,cursor:"pointer"},children:"Advanced enterprise routing"}),s.jsx("div",{style:{display:"grid",gap:10,marginTop:10},children:s.jsx(ta,{providerId:x,provider:b,mode:S,baseUrl:E,setBaseUrl:v,model:w,setModel:A,reasoningEffort:R,setReasoningEffort:y,t:n,input:H,fieldLabel:se})})]}):s.jsx("div",{style:{display:"grid",gap:10},children:s.jsx(ta,{providerId:x,provider:b,mode:S,baseUrl:E,setBaseUrl:v,model:w,setModel:A,reasoningEffort:R,setReasoningEffort:y,t:n,input:H,fieldLabel:se})}),I.state!=="idle"?s.jsx("div",{role:I.ok===!1?"alert":"status",style:{fontSize:11.5,lineHeight:1.5,color:I.state==="testing"?n.textMuted:I.ok?"var(--status-success)":"var(--status-error)"},children:I.state==="testing"?"Testing these unsaved values through the governed runtime…":I.message}):null,s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,paddingTop:4,borderTop:"1px solid var(--border-subtle)"},children:[s.jsx("span",{style:{fontSize:10.5,color:n.textMuted,flex:1},children:te}),s.jsx("button",{type:"button",onClick:()=>void q(),disabled:M||I.state==="testing",style:{height:30,padding:"0 13px",borderRadius:8,border:`1px solid ${n.headerBorder}`,background:n.cellBg,color:n.textSecondary,fontSize:12,fontWeight:650,cursor:"pointer",fontFamily:n.font},children:I.state==="testing"?"Testing…":"Test unsaved values"}),s.jsx("button",{type:"button",onClick:()=>void O(),disabled:M,style:{height:30,padding:"0 15px",borderRadius:8,border:"none",background:n.accent,color:"#fff",fontSize:12,fontWeight:650,cursor:"pointer",fontFamily:n.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)",opacity:M?.7:1},children:M?"Testing…":"Test, save & activate"})]})]})]})}function ta({providerId:e,provider:t,mode:n,baseUrl:r,setBaseUrl:o,model:i,setModel:l,reasoningEffort:a,setReasoningEffort:d,t:c,input:f,fieldLabel:p}){return s.jsxs(s.Fragment,{children:[n!=="subscription"&&n!=="local"?s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:p,children:e==="custom-openai"?"Base URL (required)":"Base URL (optional)"}),s.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:sd(e),style:{...f,fontFamily:c.fontMono}})]}):null,s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:p,children:e==="custom-openai"?"Model (required)":"Model (optional)"}),s.jsx("input",{value:i,onChange:h=>l(h.target.value),placeholder:(t==null?void 0:t.model)||"Provider default",style:f})]}),t!=null&&t.supportsReasoningEffort&&n==="api"?s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:p,children:"Reasoning effort"}),s.jsxs("select",{value:a,onChange:h=>d(h.target.value),style:f,children:[s.jsx("option",{value:"auto",children:"Auto — pick per task (up to High)"}),s.jsx("option",{value:"low",children:"Low — fastest, cheapest"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High — deepest reasoning"})]})]}):null]})}function na({provider:e,cliStatus:t,t:n,onSaved:r,onStatus:o}){const[i,l]=u.useState(e.enabled),[a,d]=u.useState(""),[c,f]=u.useState(e.baseUrl??""),[p,h]=u.useState(e.model??""),[g,S]=u.useState(e.reasoningEffort??"auto"),[x,b]=u.useState(!1),[k,C]=u.useState(!1),[E,v]=u.useState(null),w=e.authMode==="subscription_cli",A=e.id==="claude-code"?"/login":"login",R=e.supportsReasoningEffort===!0&&!w&&e.id!=="ollama";u.useEffect(()=>{l(e.enabled),f(e.baseUrl??""),h(e.model??""),S(e.reasoningEffort??"auto"),d(""),v(null)},[e.id,e.enabled,e.baseUrl,e.model,e.reasoningEffort]);const y=async()=>{b(!0);try{const T=await N.saveProviderSettings({id:e.id,enabled:i,apiKey:a||void 0,baseUrl:c,model:p,reasoningEffort:g});r(T.providers),o(`${e.label} settings saved.`)}catch(T){o(T instanceof Error?T.message:String(T))}finally{b(!1)}},M=async()=>{C(!0),v(null);const T=await N.testProviderSettings(e.id,{apiKey:a||void 0,baseUrl:c||void 0,model:p||void 0}),L=T.ok!==!1;v({ok:L,message:T.message||(L?`${e.label} is reachable.`:`${e.label} test failed.`)}),C(!1)},$=async T=>{const L=p||T;h(L),l(!0);try{const I=await N.saveProviderSettings({id:e.id,enabled:!0,model:L});r(I.providers),o(`${e.label} connected and activated.`)}catch(I){o(I instanceof Error?I.message:String(I))}};return s.jsxs("section",{style:{border:`1px solid ${n.headerBorder}`,borderRadius:8,background:n.cellBg,padding:14},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("div",{style:{fontSize:14,fontWeight:700},children:e.label}),e.active?s.jsx("span",{style:oS(n),children:"Active"}):null]}),s.jsxs("div",{style:{fontSize:11,color:n.textSecondary,marginTop:3},children:[e.source==="local"?"Project local":e.source==="env"?"Environment":"Not configured",e.apiKeyPreview?` · ${e.apiKeyPreview}`:""]})]}),s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,color:n.textSecondary},children:[s.jsx("input",{type:"checkbox",checked:i,onChange:T=>l(T.target.checked)}),"Enabled"]})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:12},children:[w?s.jsx(ad,{oauthProvider:id(e.id),label:e.label,model:p,setModel:h,cliStatus:t,command:e.command,loginCmd:A,t:n,onStatus:o,onConnected:$}):s.jsxs(s.Fragment,{children:[e.id!=="ollama"&&s.jsx("input",{value:a,onChange:T=>d(T.target.value),type:"password",placeholder:e.hasApiKey?"Leave blank to keep existing key":"API key",style:_e(n)}),s.jsx("input",{value:c,onChange:T=>f(T.target.value),placeholder:sd(e.id),style:_e(n)})]}),!w&&s.jsx("input",{value:p,onChange:T=>h(T.target.value),placeholder:"Default model",style:_e(n)}),R&&s.jsxs("div",{style:{display:"grid",gap:4},children:[s.jsx("label",{style:{fontSize:11,color:n.textSecondary,fontWeight:600},children:"Reasoning effort"}),s.jsxs("select",{value:g,onChange:T=>S(T.target.value),style:_e(n),children:[s.jsx("option",{value:"auto",children:"Auto — pick per task (up to High)"}),s.jsx("option",{value:"low",children:"Low — fastest, cheapest"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High — deepest reasoning"})]}),s.jsx("div",{style:{fontSize:11,color:n.textSecondary,lineHeight:1.4},children:g==="auto"?"The agent spends more reasoning on SQL generation, gates, and repairs, and less on chat.":`Caps every request at ${g} reasoning.`})]})]}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[s.jsx("button",{type:"button",onClick:y,disabled:x||k,style:ht(n,!0),children:e.active?"Save active provider":"Save and use"}),s.jsx("button",{type:"button",onClick:M,disabled:x||k,style:ht(n,!1),children:k?"Testing…":"Test"})]}),E&&s.jsxs("div",{role:"status",style:{marginTop:10,display:"flex",alignItems:"flex-start",gap:7,fontSize:12,lineHeight:1.45,padding:"8px 10px",borderRadius:7,color:E.ok?n.success:n.error,background:`${E.ok?n.success:n.error}12`,border:`1px solid ${E.ok?n.success:n.error}40`},children:[s.jsx("span",{style:{flexShrink:0,fontWeight:700},children:E.ok?"✓":"✗"}),s.jsx("span",{children:E.message})]}),e.envVars.length>0&&s.jsxs("div",{style:{marginTop:10,color:n.textSecondary,fontSize:11,lineHeight:1.4},children:["Env: ",e.envVars.join(", ")]})]})}function We(e){var t;return e.lesson??{version:1,category:"semantic_rule",rule:e.guidance,intentExamples:(t=e.trace)!=null&&t.question?[e.trace.question]:[],avoid:[]}}function ra(e){return[...new Map(e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean).map(t=>[t.toLowerCase(),t])).values()].slice(0,8)}function eS({t:e,onStatus:t}){const[n,r]=u.useState([]),[o,i]=u.useState({candidate:0,approved:0,rejected:0,retired:0}),[l,a]=u.useState(null),[d,c]=u.useState(!1),[f,p]=u.useState({}),[h,g]=u.useState(null),S=u.useCallback(async()=>{try{const y=await N.listAgentHints();r(y.hints??[]),i(y.counts??{candidate:0,approved:0,rejected:0,retired:0})}catch{r([])}finally{c(!0)}},[]);u.useEffect(()=>{S()},[S]);const x=async(y,M)=>{var $;a(y.id),t(null);try{const T=($=f[y.id])==null?void 0:$.trim(),L=await Hv(()=>N.reviewAgentHint(y.id,M,T),S);L.ok?t(M==="approved"?`Approved. DQL will apply "${y.title}" to matching questions.`:`Rejected. "${y.title}" will not be used.`):t(L.error??`Could not ${M==="approved"?"approve":"reject"} this correction.`)}catch(T){t(T instanceof Error?T.message:String(T))}finally{a(null)}},b=async(y,M,$)=>{var T;a(y.id),t(null);try{const L=await N.transitionAgentHint(y.id,{action:M,targetHintId:$,note:((T=f[y.id])==null?void 0:T.trim())||void 0});t(L.ok?M==="retire"?`Retired "${y.title}". It is excluded from future answers.`:M==="reopen"?`Reopened "${y.title}" as a candidate.`:`Resolved the conflict. "${y.title}" is authoritative.`:L.error??`Could not ${M} this hint.`),await S()}catch(L){t(L instanceof Error?L.message:String(L))}finally{a(null)}},k=async()=>{if(h){a(h.id),t(null);try{const y=await N.updateAgentHint(h.id,{title:h.title,guidance:h.guidance,lesson:{...We(h),rule:h.guidance},correctedSql:h.correctedSql,scope:h.scope});y.ok?(t(`Updated "${h.title}" and refreshed its current dependencies.`),g(null)):t(y.error??"Could not update this candidate."),await S()}catch(y){t(y instanceof Error?y.message:String(y))}finally{a(null)}}},C=async y=>{var M;if(!((M=y.trace)!=null&&M.question)||!y.correctedSql){t("This hint is missing the question or SQL required for an analyst certification request.");return}a(y.id);try{const $=await N.requestCertification({question:y.trace.question,generatedSql:y.correctedSql,domain:y.scope.domain,context:{source:"governed_hint_review",hintId:y.id,evaluationId:y.evaluationId,snapshotId:y.snapshotId}});t($.ok?`Certification research requested for "${y.title}". Approval of a hint did not certify an asset.`:$.error??"Could not request certification.")}catch($){t($ instanceof Error?$.message:String($))}finally{a(null)}},E=n.filter(y=>y.status==="candidate"),v=n.filter(y=>y.status==="approved"),w=n.filter(y=>y.status==="rejected"||y.status==="retired");if(!d)return null;const A=y=>{var M,$,T,L,I,G,Y,P,q;return s.jsxs("details",{style:{fontSize:10.5,color:e.textMuted},children:[s.jsx("summary",{style:{cursor:"pointer"},children:"Evidence, provenance & exclusions"}),s.jsxs("div",{style:{display:"grid",gap:5,paddingTop:6},children:[(M=y.trace)!=null&&M.question?s.jsxs("div",{children:[s.jsx("b",{children:"Question:"})," ",y.trace.question]}):null,($=y.trace)!=null&&$.wrongAnswer?s.jsxs("div",{children:[s.jsx("b",{children:"Previous answer:"})," ",y.trace.wrongAnswer]}):null,(T=y.trace)!=null&&T.rationale?s.jsxs("div",{children:[s.jsx("b",{children:"Why the correction is right:"})," ",y.trace.rationale]}):null,s.jsxs("div",{children:[s.jsx("b",{children:"Snapshot:"})," ",y.snapshotId??"missing",(L=y.inspection)!=null&&L.currentSnapshotId?` · current ${y.inspection.currentSnapshotId}`:""]}),s.jsxs("div",{children:[s.jsx("b",{children:"Dependencies:"})," ",((I=y.dependencies)==null?void 0:I.map(O=>`${O.kind}:${O.id}@${O.fingerprint.slice(0,10)}`).join(", "))||"none recorded"]}),s.jsxs("div",{children:[s.jsx("b",{children:"Graph connections:"})," ",(G=y.graphEdges)!=null&&G.length?y.graphEdges.map(O=>`${O.kind.replace(/_/g," ")} → ${O.targetName}`).join(" · "):"none materialized"]}),(Y=y.lifecycleErrors)==null?void 0:Y.map(O=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:[O.code,":"]})," ",O.message]},`${O.code}-${O.at}`)),y.evaluation?s.jsxs("div",{children:[s.jsxs("b",{children:["Evaluation ",y.evaluation.status,":"]}),y.evaluation.checks.map(O=>s.jsxs("div",{style:{color:O.passed?e.success:e.error},children:[O.passed?"✓":"✕"," ",O.name," — ",O.evidence]},O.name))]}):s.jsxs("div",{children:[s.jsx("b",{children:"Evaluation:"})," not run"]}),(P=y.inspection)==null?void 0:P.checks.map(O=>s.jsxs("div",{style:{color:O.passed?e.success:e.error},children:[O.passed?"✓":"✕"," live ",O.name," — ",O.evidence]},`live-${O.name}`)),(q=y.exclusions)==null?void 0:q.map((O,W)=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:["Excluded: ",O.reason]})," — ",O.detail]},`${O.reason}-${W}`))]})]})},R=y=>{var L,I,G,Y,P,q;const M=((L=y.exclusions)==null?void 0:L.filter(O=>O.reason==="conflict"&&O.relatedHintId))??[],$=(h==null?void 0:h.id)===y.id,T=y.status==="approved"&&((I=y.evaluation)==null?void 0:I.status)==="passed"&&((G=y.inspection)==null?void 0:G.state)==="current"&&(((Y=y.exclusions)==null?void 0:Y.length)??0)===0;return s.jsxs("div",{style:{border:`1px solid ${e.btnBorder}`,borderRadius:8,padding:"10px 12px",background:e.btnBg,display:"grid",gap:7},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:8},children:[s.jsx("div",{style:{fontSize:12.5,fontWeight:600,color:e.textPrimary},children:y.title}),s.jsx("span",{style:{fontSize:10,color:(P=y.exclusions)!=null&&P.length||((q=y.evaluation)==null?void 0:q.status)==="failed"?e.error:e.success},children:Kv(y)})]}),$?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:h.title,onChange:O=>g({...h,title:O.target.value}),placeholder:"Hint title",style:ke(e,{size:"sm"})}),s.jsx("textarea",{value:h.guidance,onChange:O=>g({...h,guidance:O.target.value}),placeholder:"Guidance for matching questions",rows:3,style:{...ke(e,{size:"sm"}),resize:"vertical"}}),s.jsxs("details",{style:{border:`1px solid ${e.cellBorder}`,borderRadius:7,padding:"7px 8px"},children:[s.jsx("summary",{style:{cursor:"pointer",fontSize:10.5,color:e.textSecondary,fontWeight:650},children:"Structured lesson"}),s.jsxs("div",{style:{display:"grid",gap:7,paddingTop:7},children:[s.jsxs("select",{value:We(h).category,onChange:O=>g({...h,lesson:{...We(h),category:O.target.value}}),style:ke(e,{size:"sm"}),children:[s.jsx("option",{value:"semantic_rule",children:"Business definition"}),s.jsx("option",{value:"filter_rule",children:"Filter rule"}),s.jsx("option",{value:"join_rule",children:"Join rule"}),s.jsx("option",{value:"aggregation_rule",children:"Aggregation rule"}),s.jsx("option",{value:"grain_rule",children:"Grain rule"}),s.jsx("option",{value:"time_rule",children:"Time rule"}),s.jsx("option",{value:"relation_rule",children:"Table or column rule"}),s.jsx("option",{value:"dialect_rule",children:"SQL dialect rule"})]}),s.jsx("textarea",{value:We(h).intentExamples.join(`
446
- `),onChange:O=>g({...h,lesson:{...We(h),intentExamples:O.target.value.split(/\r?\n/)}}),onBlur:()=>g({...h,lesson:{...We(h),intentExamples:ra(We(h).intentExamples.join(`
447
- `))}}),placeholder:"Similar questions, one per line",rows:3,style:{...ke(e,{size:"sm"}),resize:"vertical"}}),s.jsx("textarea",{value:We(h).avoid.join(`
448
- `),onChange:O=>g({...h,lesson:{...We(h),avoid:O.target.value.split(/\r?\n/)}}),onBlur:()=>g({...h,lesson:{...We(h),avoid:ra(We(h).avoid.join(`
449
- `))}}),placeholder:"Known mistakes to avoid, one per line",rows:2,style:{...ke(e,{size:"sm"}),resize:"vertical"}}),s.jsx("input",{value:We(h).expectedOutcome??"",onChange:O=>g({...h,lesson:{...We(h),expectedOutcome:O.target.value||void 0}}),placeholder:"Expected outcome or result shape",style:ke(e,{size:"sm"})})]})]}),s.jsx("textarea",{value:h.correctedSql??"",onChange:O=>g({...h,correctedSql:O.target.value}),placeholder:"Read-only corrected SQL",rows:5,style:{...ke(e,{size:"sm"}),resize:"vertical",fontFamily:e.fontMono}}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(150px, 1fr))",gap:7},children:[["dbtModel","dbt model"],["metric","metric"],["domain","domain"],["dialect","dialect"],["term","business term"],["block","block"]].map(([O,W])=>s.jsxs("label",{style:{display:"grid",gap:3,fontSize:10,color:e.textMuted},children:[W,s.jsx("input",{value:h.scope[O]??"",onChange:se=>g({...h,scope:Vv(h.scope,O,se.target.value)}),placeholder:`Optional ${W}`,style:ke(e,{size:"sm"})})]},O))}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void k(),style:ke(e,{variant:"primary",size:"sm",disabled:l===y.id}),children:"Save & recheck"}),s.jsx("button",{type:"button",onClick:()=>g(null),style:ke(e,{variant:"ghost",size:"sm"}),children:"Cancel"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:11.5,color:e.textSecondary,lineHeight:1.5},children:y.guidance}),y.lesson?s.jsxs("div",{style:{display:"grid",gap:3,padding:"7px 8px",borderRadius:6,background:e.btnBg,fontSize:10.5,color:e.textMuted},children:[s.jsxs("div",{children:[s.jsx("b",{children:"Lesson type:"})," ",y.lesson.category.replace(/_/g," ")]}),y.lesson.intentExamples.length?s.jsxs("div",{children:[s.jsx("b",{children:"Similar questions:"})," ",y.lesson.intentExamples.join(" · ")]}):null,y.lesson.avoid.length?s.jsxs("div",{children:[s.jsx("b",{children:"Avoid:"})," ",y.lesson.avoid.join(" · ")]}):null,y.lesson.expectedOutcome?s.jsxs("div",{children:[s.jsx("b",{children:"Expected:"})," ",y.lesson.expectedOutcome]}):null]}):null,y.correctedSql?s.jsx("pre",{style:{margin:0,fontSize:10.5,fontFamily:e.fontMono,color:e.textMuted,whiteSpace:"pre-wrap",maxHeight:120,overflow:"auto"},children:y.correctedSql}):null,A(y),s.jsx("textarea",{value:f[y.id]??"",onChange:O=>p({...f,[y.id]:O.target.value}),placeholder:"Reviewer note or result assertion (required evidence when this surface cannot execute)",rows:2,style:{...ke(e,{size:"sm"}),resize:"vertical"}}),s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[y.status==="candidate"?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void x(y,"approved"),style:ke(e,{variant:"primary",size:"sm",disabled:l===y.id}),children:l===y.id?"Checking…":Wv(y)}),s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>g({...y,lesson:We(y)}),style:ke(e,{size:"sm",disabled:l===y.id}),children:"Edit candidate"}),s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void x(y,"rejected"),style:ke(e,{variant:"danger",size:"sm",disabled:l===y.id}),children:"Reject"})]}):null,y.status==="approved"?s.jsxs(s.Fragment,{children:[T?s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void C(y),style:ke(e,{variant:"primary",size:"sm",disabled:l===y.id}),children:"Request certification"}):null,s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void b(y,"reopen"),style:ke(e,{size:"sm",disabled:l===y.id}),children:"Reopen & edit"}),s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void b(y,"retire"),style:ke(e,{variant:"danger",size:"sm",disabled:l===y.id}),children:"Retire"}),M.map(O=>s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void b(y,"supersede",O.relatedHintId),style:ke(e,{size:"sm",disabled:l===y.id}),children:"Keep this; supersede conflict"},O.relatedHintId))]}):null,y.status==="retired"?s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void b(y,"reopen"),style:ke(e,{size:"sm",disabled:l===y.id}),children:"Reopen as candidate"}):null,s.jsx("span",{style:{fontSize:10.5,color:e.textMuted},children:[y.scope.dbtModel,y.scope.metric,y.scope.domain].filter(Boolean).join(" · ")||"project-wide"})]})]})]},y.id)};return s.jsxs("div",{style:{marginTop:18},children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:8},children:[s.jsx("span",{style:{fontSize:12.5,fontWeight:650,color:e.textPrimary},children:"Corrections awaiting review"}),s.jsxs("span",{style:{fontSize:11,color:e.textMuted},children:[o.candidate," pending · ",o.approved," approved",o.rejected?` · ${o.rejected} rejected`:"",o.retired?` · ${o.retired} retired`:""]})]}),E.length===0?s.jsx("div",{style:{fontSize:11.5,color:e.textMuted,lineHeight:1.5},children:"Nothing pending. A candidate appears only after you explicitly choose Teach DQL on an AI draft that you changed and ran successfully."}):s.jsx("div",{style:{display:"grid",gap:8},children:E.map(R)}),v.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{margin:"16px 0 8px",fontSize:12.5,fontWeight:650,color:e.textPrimary},children:"Approved learning"}),s.jsx("div",{style:{display:"grid",gap:8},children:v.map(R)})]}):null,w.length>0?s.jsxs("details",{style:{marginTop:16},children:[s.jsxs("summary",{style:{cursor:"pointer",fontSize:12,color:e.textSecondary},children:["Rejected & retired history (",w.length,")"]}),s.jsx("div",{style:{display:"grid",gap:8,marginTop:8},children:w.map(R)})]}):null]})}function tS({memories:e,t,onChange:n,onStatus:r}){const[o,i]=u.useState("project"),[l,a]=u.useState(""),[d,c]=u.useState(""),[f,p]=u.useState(""),h=async()=>{const $=await N.listAgentMemory();n($.memories)},g=async $=>{await N.deleteAgentMemory($),await h(),r("Memory deleted.")},[S,x]=u.useState(!1),[b,k]=u.useState("all"),[C,E]=u.useState(null),v=$=>$==="project"?{label:"project",bg:"var(--accent-dim)",color:t.accent}:$==="user"?{label:"just me",bg:`${t.textMuted}1f`,color:t.textMuted}:{label:$,bg:"var(--status-success-bg)",color:"var(--status-success)"},w=e.filter($=>b==="all"?!0:b==="project"?$.scope==="project":$.scope==="user"),A=$=>{E($.id),i($.scope),a($.title),c($.content),p($.tags.join(", ")),x(!0)},R=()=>{x(!1),E(null),a(""),c(""),p("")},y=async()=>{if(!d.trim())return;l.trim()||a(d.trim().slice(0,60));const $=l.trim()||d.trim().slice(0,60);await N.saveAgentMemory({scope:o,title:$,content:d,tags:f.split(",").map(T=>T.trim()).filter(Boolean),source:"settings-ui",confidence:.8,importance:o==="project"?.7:.5,enabled:!0}),C&&await N.deleteAgentMemory(C).catch(()=>{}),R(),await h(),r(C?"Memory updated.":"Memory saved.")},M=($,T)=>s.jsx("button",{type:"button",onClick:()=>k($),style:{border:"none",borderRadius:5,padding:"4px 11px",fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:t.font,background:b===$?"var(--accent-dim)":"transparent",color:b===$?t.accent:t.textMuted},children:T},$);return s.jsxs("div",{style:{width:"min(640px, 100%)",display:"flex",flexDirection:"column",gap:14},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:2,padding:2,border:`1px solid ${t.headerBorder}`,borderRadius:7,background:t.cellBg},children:[M("all","All"),M("project","Project"),M("me","Just me")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{type:"button",onClick:()=>S?R():x(!0),style:{display:"inline-flex",alignItems:"center",gap:6,height:30,padding:"0 13px",borderRadius:8,border:"none",background:t.accent,color:"#fff",fontSize:12,fontWeight:650,cursor:"pointer",fontFamily:t.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)"},children:"+ Add memory"})]}),S?s.jsxs("div",{style:{border:`1px solid ${t.accent}4d`,borderRadius:12,background:t.cellBg,padding:"15px 17px",display:"flex",flexDirection:"column",gap:10},children:[s.jsx("textarea",{rows:2,value:d,onChange:$=>c($.target.value),placeholder:"e.g. Fiscal quarters start in February. 'Sales' means recognized revenue unless someone says bookings.",style:{..._e(t),borderRadius:8,resize:"vertical",lineHeight:1.55}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[s.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:11.5,color:t.textSecondary},children:["Scope",s.jsxs("select",{value:o,onChange:$=>i($.target.value),style:{..._e(t),width:"auto",borderRadius:7,padding:"5px 7px"},children:[s.jsx("option",{value:"project",children:"Project"}),s.jsx("option",{value:"user",children:"Just me"}),s.jsx("option",{value:"artifact",children:"Artifact note"}),s.jsx("option",{value:"notebook",children:"Notebook context"}),s.jsx("option",{value:"thread",children:"Thread summary"})]})]}),s.jsx("input",{value:f,onChange:$=>p($.target.value),placeholder:"Tags (optional)",style:{..._e(t),width:160,borderRadius:7,padding:"5px 8px"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{type:"button",onClick:R,style:{height:28,padding:"0 12px",borderRadius:7,border:`1px solid ${t.headerBorder}`,background:t.cellBg,color:t.textSecondary,fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:t.font},children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void y(),disabled:!d.trim(),style:{height:28,padding:"0 13px",borderRadius:7,border:"none",background:t.accent,color:"#fff",fontSize:11.5,fontWeight:650,cursor:"pointer",fontFamily:t.font,opacity:d.trim()?1:.6},children:C?"Update memory":"Save memory"})]})]}):null,s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:w.length===0?s.jsx("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:11,background:t.cellBg,padding:"13px 15px",fontSize:12,color:t.textSecondary,lineHeight:1.5},children:"No advisory memory yet. Add business context explicitly here. Edited SQL corrections use the separate governed review queue and are never promoted into memory automatically."}):w.slice(0,30).map($=>{const T=!["settings-ui","manual",""].includes($.source),L=v($.scope),I=T?`Saved from ${$.source}${typeof $.confidence=="number"?` · ${Math.round($.confidence*100)}% confidence`:""}`:`Added by hand${$.tags.length?` · ${$.tags.join(", ")}`:""}`;return s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:11,background:t.cellBg,padding:"13px 15px",display:"flex",gap:11,alignItems:"flex-start"},children:[s.jsx("span",{style:{flexShrink:0,fontSize:9,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.04em",padding:"2.5px 7px",borderRadius:5,marginTop:1,background:L.bg,color:L.color},children:L.label}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:12.5,color:t.textPrimary,lineHeight:1.55,whiteSpace:"pre-wrap"},children:$.content||$.title}),s.jsx("div",{style:{fontSize:10.5,color:t.textMuted,marginTop:4},children:I})]}),s.jsx("button",{type:"button",title:"Edit",onClick:()=>A($),style:{flexShrink:0,width:25,height:25,borderRadius:6,border:"1px solid var(--border-subtle)",background:"var(--bg-1)",color:t.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:11},children:"✎"}),s.jsx("button",{type:"button",title:"Stop using",onClick:()=>void g($.id),style:{flexShrink:0,width:25,height:25,borderRadius:6,border:"1px solid var(--border-subtle)",background:"var(--bg-1)",color:t.textMuted,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:11},children:"🗑"})]},$.id)})}),s.jsx("div",{style:{display:"flex",gap:9,alignItems:"flex-start",border:"1px solid var(--border-subtle)",background:t.cellBg,borderRadius:10,padding:"11px 13px"},children:s.jsxs("span",{style:{fontSize:11.5,color:t.textMuted,lineHeight:1.55},children:["Entries added here are local advisory records under ",s.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10.5},children:".dql/cache/"}),". Put shared agent guidance in Git under ",s.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10.5},children:"skills/"})," or ",s.jsx("span",{style:{fontFamily:t.fontMono,fontSize:10.5},children:"domains/<domain>/skills/"}),". Advisory memory and skills never approve or certify a governed hint."]})})]})}function oa({group:e,t}){return s.jsxs("section",{style:{border:`1px solid ${t.headerBorder}`,borderRadius:8,background:t.cellBg,overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"14px 14px 10px",borderBottom:`1px solid ${t.headerBorder}`},children:[s.jsx("div",{style:{fontSize:14,fontWeight:700},children:e.title}),s.jsx("div",{style:{color:t.textSecondary,fontSize:12,lineHeight:1.45,marginTop:4},children:e.description})]}),e.vars.map(n=>s.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:10,padding:"11px 14px",borderBottom:`1px solid ${t.headerBorder}`},children:[s.jsxs("div",{style:{minWidth:0},children:[s.jsx("code",{style:{fontSize:12,color:t.textPrimary},children:n.key}),s.jsx("div",{style:{color:t.textSecondary,fontSize:12,lineHeight:1.4,marginTop:4},children:n.description})]}),s.jsx(rS,{present:n.present})]},n.key))]})}function an({title:e,detail:t,t:n}){return s.jsxs("div",{style:{marginBottom:10},children:[s.jsx("div",{style:{fontSize:14,fontWeight:700},children:e}),s.jsx("div",{style:{fontSize:12,color:n.textSecondary,marginTop:3},children:t})]})}function nS({configured:e,total:t,activeLabel:n,t:r}){return s.jsxs("div",{style:{border:`1px solid ${r.headerBorder}`,borderRadius:8,padding:"10px 12px",minWidth:160,textAlign:"right",background:r.cellBg},children:[s.jsxs("div",{style:{fontSize:20,fontWeight:700},children:[e,"/",t]}),s.jsx("div",{style:{fontSize:12,color:r.textSecondary},children:"providers configured"}),s.jsx("div",{style:{fontSize:11,color:n?r.accent:r.textMuted,marginTop:4},children:n?`${n} active`:"No active provider"})]})}function rS({present:e}){return s.jsx("span",{style:{alignSelf:"start",fontSize:11,fontWeight:700,borderRadius:999,padding:"3px 8px",color:e?"#12613a":"#7a4a00",background:e?"#d9f8e6":"#fff0cc",whiteSpace:"nowrap"},children:e?"Set":"Optional"})}function _e(e){return{minHeight:32,border:`1px solid ${e.headerBorder}`,borderRadius:6,background:e.appBg,color:e.textPrimary,padding:"7px 9px",fontSize:12,fontFamily:e.font}}function ht(e,t){return{height:30,border:`1px solid ${t?e.accent:e.headerBorder}`,background:t?`${e.accent}24`:e.appBg,color:t?e.accent:e.textPrimary,borderRadius:6,padding:"0 10px",cursor:"pointer",fontSize:12}}function sa(e,t){return{height:28,border:0,borderRight:`1px solid ${e.headerBorder}`,background:t?`${e.accent}18`:e.appBg,color:t?e.accent:e.textSecondary,padding:"0 10px",cursor:"pointer",fontSize:12,fontWeight:t?700:500}}function oS(e){return{border:`1px solid ${e.accent}44`,background:`${e.accent}16`,color:e.accent,borderRadius:999,padding:"2px 7px",fontSize:10,fontWeight:800,textTransform:"uppercase",letterSpacing:0}}function En(e){return{display:"flex",alignItems:"center",gap:5,fontSize:12,color:e.textSecondary}}function An(e){const t=e.filter(r=>r.kind!=="connector").map(r=>ia({name:r.name,url:r.url,description:r.description,authorizationToken:r.authorizationToken,authorizationTokenEnv:r.authorizationTokenEnv,allowedTools:r.allowedTools,enabled:r.enabled,trusted:r.trusted,deferLoading:r.deferLoading,providers:Yt(r).providers})),n=e.filter(r=>r.kind==="connector").map(r=>ia({name:r.name,connectorId:r.connectorId,description:r.description,authorizationToken:r.authorizationToken,authorizationTokenEnv:r.authorizationTokenEnv,allowedTools:r.allowedTools,enabled:r.enabled,trusted:r.trusted,deferLoading:r.deferLoading,providers:["openai"]}));return JSON.stringify({version:1,servers:t,connectors:n},null,2)}function sS(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON: ${r instanceof Error?r.message:String(r)}`)}if(!Qt(t))throw new Error("MCP config must be a JSON object.");const n=[];return Array.isArray(t.servers)&&n.push(...t.servers.map((r,o)=>Fr(r,"server",`servers[${o}]`))),Array.isArray(t.connectors)&&n.push(...t.connectors.map((r,o)=>Fr(r,"connector",`connectors[${o}]`))),Array.isArray(t.tools)&&n.push(...iS(t.tools)),Array.isArray(t.mcp_servers)&&n.push(...aS(t.mcp_servers)),Qt(t.mcpServers)&&n.push(...lS(t.mcpServers)),n.map(Yt)}function iS(e){return e.flatMap((t,n)=>{if(!Qt(t)||t.type!=="mcp")return[];const r=He(t,["connectorId","connector_id"]),o=He(t,["authorization"]);return r?[Yt({kind:"connector",name:He(t,["name","server_label","serverLabel"])??r,connectorId:r,authorizationToken:o,allowedTools:Hn(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]})]:[Fr({...t,name:He(t,["name","server_label","serverLabel"]),url:He(t,["url","server_url","serverUrl"]),authorizationToken:o??Bs(t.headers),allowedTools:Hn(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]},"server",`tools[${n}]`)]})}function aS(e){return e.map((t,n)=>{const r=Fr(t,"server",`mcp_servers[${n}]`);return Yt({...r,authorizationToken:r.authorizationToken??(Qt(t)?He(t,["authorization_token"]):void 0),providers:["anthropic"]})})}function lS(e){return Object.entries(e).map(([t,n])=>{if(!Qt(n))throw new Error(`mcpServers.${t} must be an object.`);const r=He(n,["url","server_url","serverUrl"]);if(!r)throw new Error(`mcpServers.${t} is not a remote HTTP MCP server. App chat SDK config only supports URL-based MCP servers.`);return Yt({kind:"server",name:t,url:r,authorizationToken:Bs(n.headers),enabled:n.enabled!==!1,trusted:n.trusted===!0,allowedTools:Hn(n,["allowedTools","allowed_tools"]),providers:ld(n,["providers"])??["openai","anthropic"]})})}function Fr(e,t,n){if(!Qt(e))throw new Error(`${n} must be an object.`);const r=He(e,["name","server_label","serverLabel"]);if(!r)throw new Error(`${n} needs a name.`);const o=He(e,["url","server_url","serverUrl"]),i=He(e,["connectorId","connector_id"]);if(t==="server"&&!o)throw new Error(`${n} needs a url.`);if(t==="connector"&&!i)throw new Error(`${n} needs a connectorId.`);return{kind:t,name:r,url:o,connectorId:i,description:He(e,["description","server_description","serverDescription"]),authorizationToken:He(e,["authorizationToken","authorization","authorization_token"])??Bs(e.headers),authorizationTokenEnv:He(e,["authorizationTokenEnv","authorizationEnv","authorization_token_env"]),allowedTools:Hn(e,["allowedTools","allowed_tools"]),enabled:e.enabled!==!1,trusted:e.trusted===!0,deferLoading:e.deferLoading===!0||e.defer_loading===!0,providers:ld(e,["providers"])}}function ia(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>!(t==null||t===""||Array.isArray(t)&&t.length===0)))}function Qt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function He(e,t){for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function Hn(e,t){for(const n of t){const r=e[n];if(Array.isArray(r)){const o=r.map(i=>typeof i=="string"?i.trim():"").filter(Boolean);return o.length?Array.from(new Set(o)):void 0}}}function ld(e,t){const n=Hn(e,t);if(!n)return;const r=n.filter(o=>o==="openai"||o==="anthropic");return r.length?r:void 0}function Bs(e){if(!Qt(e))return;const t=He(e,["Authorization","authorization"]);return(t==null?void 0:t.replace(/^Bearer\s+/i,"").trim())||void 0}function aa(e,t,n){const r=new Set(e??[]);return n?r.add(t):r.delete(t),Array.from(r)}function Yt(e){var n,r;const t=e.kind==="connector"?["openai"]:(n=e.providers)!=null&&n.length?e.providers:["openai","anthropic"];return{...e,providers:t,allowedTools:(r=e.allowedTools)==null?void 0:r.filter(Boolean)}}function Eo(e){if(!e)return null;if("job"in e&&e.job)return e.job;const t=e.id??("jobId"in e?e.jobId:void 0);return t?{id:t,kind:e.kind,status:e.status??"running",stage:e.stage,progress:e.progress,message:e.message,phases:e.phases,result:e.result,error:e.error}:null}function cS(e){return/^(?:https?:\/\/|ssh:\/\/|git@|file:\/\/)/i.test(e.trim())}function dS(e){const t=e.trim();return t?cS(t)?{repoUrl:t}:{projectDir:t}:{}}const Ao={auto:"Auto",native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function uS({compact:e=!1,reapplyRequired:t=!1,onConfigured:n}){var Et,Bt,Ft,zt,qt,Ut;const{state:r,dispatch:o}=xe(),i=Fe[r.themeMode],[l,a]=u.useState(null),[d,c]=u.useState(!1),[f,p]=u.useState(""),[h,g]=u.useState(null),[S,x]=u.useState(null),[b,k]=u.useState("loading"),[C,E]=u.useState(null),[v,w]=u.useState(null),[A,R]=u.useState(""),[y,M]=u.useState(""),[$,T]=u.useState(""),[L,I]=u.useState(null),[G,Y]=u.useState(null),[P,q]=u.useState(null),[O,W]=u.useState(""),[se,H]=u.useState(!1),te=u.useCallback(async()=>{const F=await N.getSemanticRuntimeSettings();return w(F),R(F.dbtCloud.host??""),M(F.dbtCloud.environmentId??""),T(""),F},[]),J=u.useCallback(async()=>{const F=await N.getMetricFlowInstallerStatus();return q(F),W(ee=>ee||F.recommendedAdapter||F.supportedAdapters[0]||""),F},[]),B=u.useCallback(async()=>{var Q,K,Se;const[F,ee]=await Promise.all([N.getOnboardingStatus(),N.getBlockStudioDbtStatus().catch(()=>null)]);a(F),x(F.preparation??null);const Te=((Q=F.dbt)==null?void 0:Q.configured)===!0||!!(ee!=null&&ee.configured&&ee.artifacts.manifest.exists);c(Te);const de=((K=F.dbt)==null?void 0:K.repoUrl)||((Se=F.dbt)==null?void 0:Se.projectDir)||(ee==null?void 0:ee.projectPath)||"";return p(Te?de:""),F},[]);u.useEffect(()=>{let F=!0;return B().catch(ee=>F&&E({ok:!1,text:ee instanceof Error?ee.message:String(ee)})).finally(()=>F&&k(null)),()=>{F=!1}},[B]),u.useEffect(()=>{let F=!0;return Promise.all([te(),J()]).catch(ee=>{F&&Y({ok:!1,text:ee instanceof Error?ee.message:String(ee)})}),()=>{F=!1}},[J,te]),u.useEffect(()=>{const F=P==null?void 0:P.job;if(!F||F.state!=="queued"&&F.state!=="running")return;let ee=!0;const Te=window.setTimeout(()=>{J().then(async de=>{var K;if(!ee||((K=de.job)==null?void 0:K.state)!=="completed")return;await te();const Q=await N.getSemanticLayer();ee&&o({type:"SET_SEMANTIC_LAYER",layer:Q})}).catch(de=>{ee&&Y({ok:!1,text:de instanceof Error?de.message:String(de)})})},700);return()=>{ee=!1,window.clearTimeout(Te)}},[o,J,te,(Et=P==null?void 0:P.job)==null?void 0:Et.id,(Bt=P==null?void 0:P.job)==null?void 0:Bt.state,(Ft=P==null?void 0:P.job)==null?void 0:Ft.updatedAt]),u.useEffect(()=>{if(!S||S.status!=="queued"&&S.status!=="running")return;let F=!0,ee;const Te=async()=>{try{const de=await N.getOnboardingJob(S.id);if(!F)return;const Q=Eo(de);if(!Q)return;x(Q),Q.status==="completed"?(await B(),F&&E({ok:!0,text:Q.message||"dbt metadata and governed search indexes are ready."})):Q.status==="failed"||Q.status==="cancelled"?E({ok:!1,text:Q.error||Q.message||`dbt preparation ${Q.status}.`}):ee=window.setTimeout(()=>void Te(),650)}catch(de){F&&E({ok:!1,text:de instanceof Error?de.message:String(de)})}};return ee=window.setTimeout(()=>void Te(),350),()=>{F=!1,ee!==void 0&&window.clearTimeout(ee)}},[B,S==null?void 0:S.id,S==null?void 0:S.status]);const ne=async()=>{k("preview"),E(null);try{const F=await N.previewDbtOnboarding(dS(f));g(F),E({ok:!0,text:`Preview ready: ${F.counts.models??0} models, ${F.counts.sources??0} sources, ${F.counts.metrics??0} metrics. Nothing has changed yet.`})}catch(F){g(null),E({ok:!1,text:F instanceof Error?F.message:String(F)})}finally{k(null)}},ce=async()=>{if(h){k("apply"),E(null);try{const F=await N.applyDbtOnboarding({...h.repoUrl?{repoUrl:h.repoUrl,branch:h.branch,subPath:h.subPath}:{projectDir:h.projectDir},manifestPath:h.manifestPath,profilesDir:h.profilesDir,expectedFingerprint:h.fingerprint}),ee=Eo(F);ee&&x(ee);const Te=await B();await J();const de=Te.preparation??ee,Q=`${h.counts.models??0} models · ${h.counts.sources??0} sources · ${h.counts.metrics??0} metrics`;E({ok:!0,text:(de==null?void 0:de.status)==="completed"?de.message||`Connected ${h.projectName||h.projectDir}. Governed search is ready.`:de?`Connected ${h.projectName||h.projectDir}. DQL is preparing ${Q} for fast governed search in the background.`:`Applied ${h.projectName||h.projectDir}. ${Q}.`}),n==null||n({name:h.projectName||"dbt project",path:h.projectDir,summary:Q,readiness:(de==null?void 0:de.status)==="completed"?"ready":"preparing",readinessDetail:de==null?void 0:de.message}),g(null)}catch(F){E({ok:!1,text:F instanceof Error?F.message:String(F)})}finally{k(null)}}},re=async()=>{k("refresh"),E(null);try{const F=await N.previewDbtOnboarding({}),ee=await N.refreshDbtOnboarding({expectedFingerprint:F.fingerprint}),Te=Eo(ee);Te&&x(Te);const Q=(await B()).preparation??Te;E({ok:!0,text:(Q==null?void 0:Q.status)==="completed"?Q.message||"dbt artifacts and governed search indexes are ready.":Q?"dbt artifacts refreshed. Governed search indexes are updating in the background.":"dbt artifacts refreshed from the configured project."})}catch(F){E({ok:!1,text:F instanceof Error?F.message:String(F)})}finally{k(null)}},ge=()=>({preference:(v==null?void 0:v.preference)??"auto",dbtCloud:{host:A,environmentId:y,serviceToken:$}}),ye=async F=>{I("apply"),Y(null);try{const ee=await N.setSemanticRuntimePreference(F);w(ee),Y({ok:!0,text:`Preferred runtime set to ${Ao[F]??F}.`})}catch(ee){Y({ok:!1,text:ee instanceof Error?ee.message:String(ee)})}finally{I(null)}},Ae=async()=>{I("test"),Y(null);try{const F=await N.testDbtCloudSemanticRuntime(ge());Y({ok:F.ok,text:F.message||F.error||"dbt Cloud Semantic Layer test failed."})}finally{I(null)}},ze=async()=>{I("apply"),Y(null);try{const F=await N.applyDbtCloudSemanticRuntime(ge());w(F),T(""),Y({ok:!0,text:`${F.dbtCloud.testMessage||"dbt Cloud Semantic Layer tested."} Compilation is now bound to the active warehouse target.`})}catch(F){Y({ok:!1,text:F instanceof Error?F.message:String(F)})}finally{I(null)}},Ie=async()=>{if(!O){Y({ok:!1,text:"Choose the warehouse adapter used by this dbt project."});return}H(!0),Y(null);try{const F=await N.installMetricFlow(O);q(ee=>ee?{...ee,job:F.job}:{job:F.job,recommendedAdapter:O,supportedAdapters:[O],projectConfigured:!0,semanticManifestFound:!1})}catch(F){Y({ok:!1,text:F instanceof Error?F.message:String(F)})}finally{H(!1)}},be=d,ue=(P==null?void 0:P.job)??null,Le=se||(ue==null?void 0:ue.state)==="queued"||(ue==null?void 0:ue.state)==="running",qe=(ue==null?void 0:ue.state)==="failed",$e=(S==null?void 0:S.status)==="queued"||(S==null?void 0:S.status)==="running",De=(S==null?void 0:S.status)==="failed"||(S==null?void 0:S.status)==="cancelled",Ze=t?"Reapply required after DQL update":De?"dbt project needs attention":$e?"Preparing governed search":be?"dbt project ready":"dbt project missing",ft=t?"Review the prefilled project, choose Preview, then Reapply project.":(S==null?void 0:S.message)??(be?((zt=l==null?void 0:l.dbt)==null?void 0:zt.repoUrl)||((qt=l==null?void 0:l.dbt)==null?void 0:qt.projectDir)||"Configured dbt project.":"Choose a local path or Git repository."),st={width:"100%",boxSizing:"border-box",height:36,borderRadius:8,border:`1px solid ${i.inputBorder}`,background:i.inputBg,color:i.textPrimary,padding:"0 11px",fontFamily:i.fontMono,fontSize:12,outline:"none"},et={height:32,padding:"0 13px",borderRadius:8,border:`1px solid ${i.headerBorder}`,background:i.cellBg,color:i.textSecondary,fontFamily:i.font,fontSize:12,fontWeight:650,cursor:b?"wait":"pointer",opacity:b?.7:1};return s.jsxs("div",{style:{width:"min(680px, 100%)",display:"flex",flexDirection:"column",gap:14},children:[e?null:s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:17,fontWeight:700,color:i.textPrimary},children:"Project & dbt"}),s.jsx("div",{style:{fontSize:12.5,color:i.textMuted,marginTop:3,lineHeight:1.5},children:"Preview a local project or Git repository before DQL replaces the active dbt configuration."})]}),s.jsxs("div",{style:{border:`1px solid ${t?"var(--status-warning-border)":De?"var(--status-error-border)":$e?"var(--status-info-border)":be?"var(--status-success-border)":"var(--border-subtle)"}`,borderRadius:12,background:i.cellBg,padding:"14px 16px",display:"flex",gap:11,alignItems:"center"},children:[s.jsx("span",{style:{width:34,height:34,borderRadius:9,display:"inline-flex",alignItems:"center",justifyContent:"center",color:t?"var(--status-warning)":De?"var(--status-error)":$e?"var(--status-info)":be?"var(--status-success)":"var(--status-warning)",background:t?"var(--status-warning-bg)":De?"var(--status-error-bg)":$e?"var(--status-info-bg)":be?"var(--status-success-bg)":"var(--status-warning-bg)"},children:t?s.jsx(Ir,{size:17}):De?s.jsx(Yg,{size:17}):$e?s.jsx(Fn,{className:"dql-dbt-preparing-icon",size:17}):be?s.jsx(Oc,{size:17}):s.jsx(Sn,{size:17})}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:i.textPrimary},children:Ze}),s.jsx("div",{style:{fontSize:11.5,color:De?"var(--status-error)":i.textMuted,marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ft}),$e?s.jsx("div",{"aria-label":"dbt preparation progress",style:{width:"min(360px, 100%)",height:3,borderRadius:999,background:"var(--border-subtle)",marginTop:7,overflow:"hidden"},children:s.jsx("span",{style:{display:"block",width:`${Math.max(8,(S==null?void 0:S.progress)??8)}%`,height:"100%",borderRadius:999,background:i.accent,transition:"width 180ms ease"}})}):null]}),be&&!t?s.jsxs("button",{type:"button",onClick:()=>void re(),disabled:!!b,style:et,children:[s.jsx(Ir,{size:12,style:{verticalAlign:-2,marginRight:6}}),b==="refresh"?"Refreshing…":"Refresh"]}):null]}),s.jsx("style",{children:"@keyframes dql-dbt-preparing-spin { to { transform: rotate(360deg); } } .dql-dbt-preparing-icon { animation: dql-dbt-preparing-spin 1s linear infinite; } @media (prefers-reduced-motion: reduce) { .dql-dbt-preparing-icon { animation: none; } }"}),s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:i.cellBg,padding:16,display:"grid",gap:10},children:[s.jsxs("label",{style:{display:"grid",gap:5},children:[s.jsx("span",{style:{fontSize:11,fontWeight:650,color:i.textSecondary},children:"Local dbt project path or Git repository URL"}),s.jsx("input",{value:f,onChange:F=>{p(F.target.value),g(null)},placeholder:". or https://github.com/org/analytics.git",style:st})]}),h?s.jsxs("div",{style:{border:`1px solid ${i.headerBorder}`,borderRadius:8,padding:"10px 11px",color:i.textSecondary,fontSize:11.5,lineHeight:1.5},children:[s.jsx("strong",{style:{color:i.textPrimary},children:h.projectName||h.projectDir}),s.jsx("br",{}),h.counts.models??0," models · ",h.counts.sources??0," sources · ",h.counts.metrics??0," metrics",s.jsx("br",{}),s.jsx("span",{style:{fontFamily:i.fontMono},children:h.manifestPath})]}):null,C?s.jsx("div",{role:C.ok?"status":"alert",style:{fontSize:11.5,lineHeight:1.5,color:C.ok?"var(--status-success)":"var(--status-error)"},children:C.text}):null,s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void ne(),disabled:!!b,style:et,children:b==="preview"?"Inspecting…":"Preview"}),h?s.jsx("button",{type:"button",onClick:()=>void ce(),disabled:!!b,style:{...et,border:"none",background:i.accent,color:"#fff"},children:b==="apply"?"Applying…":t?"Reapply project":"Apply project"}):null]})]}),s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:i.cellBg,padding:16,display:"grid",gap:12},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:i.textPrimary},children:"Semantic execution adapters"}),s.jsx("div",{style:{fontSize:11.5,color:i.textMuted,marginTop:3,lineHeight:1.5},children:"Adapter code is included with DQL. Auto selects one ready adapter in priority order: dbt Cloud, local MetricFlow, then native for simple metrics. Once selected, an adapter failure is shown directly and never silently downgraded."}),v!=null&&v.dbtCloud.configured?s.jsxs("div",{style:{fontSize:10.5,color:v.dbtCloud.targetBindingState==="bound"&&v.dbtCloud.metricInventoryState==="complete"?"var(--status-success)":"var(--status-warning)",marginTop:6,lineHeight:1.5},children:["dbt Cloud target: ",v.dbtCloud.targetBindingState==="bound"?`bound · ${(Ut=v.dbtCloud.executionTargetFingerprint)==null?void 0:Ut.slice(0,12)}`:"reapply required before execution",s.jsx("br",{}),"Metric inventory: ",v.dbtCloud.metricInventoryState,v.dbtCloud.semanticCatalogFingerprint?` · ${v.dbtCloud.semanticCatalogFingerprint.slice(0,12)}`:" · reapply required"]}):null,s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:10,flexWrap:"wrap"},children:[s.jsx("label",{style:{fontSize:11,fontWeight:700,color:i.textSecondary},children:"Preferred runtime"}),s.jsxs("select",{value:(v==null?void 0:v.preference)??"auto",onChange:F=>{ye(F.target.value)},disabled:L==="apply",style:{fontSize:11.5,padding:"4px 8px",borderRadius:7,border:"1px solid var(--border-subtle)",background:i.cellBg,color:i.textPrimary,fontFamily:i.font},children:[s.jsx("option",{value:"auto",children:"Auto (recommended)"}),s.jsx("option",{value:"dbt-cloud",children:"dbt Cloud"}),s.jsx("option",{value:"metricflow-cli",children:"Local MetricFlow"}),s.jsx("option",{value:"native",children:"Native (DQL)"})]}),v!=null&&v.runtime.active?s.jsxs("span",{style:{fontSize:10.5,color:i.textMuted},children:["Active: ",s.jsx("strong",{style:{color:i.textSecondary},children:Ao[v.runtime.active]??v.runtime.active}),v.preference&&v.preference!=="auto"&&v.preference!==v.runtime.active?` (preferred ${Ao[v.preference]??v.preference} is not ready)`:""]}):null]})]}),s.jsx("div",{style:{display:"grid",gap:7},children:((v==null?void 0:v.runtime.adapters)??[]).map(F=>s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:9,padding:"9px 10px",display:"grid",gap:F.id==="metricflow-cli"?10:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:9},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:999,marginTop:4,background:F.ready?"var(--status-success)":F.configured?"var(--status-warning)":"var(--text-muted)"}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{fontSize:11.5,fontWeight:700,color:i.textPrimary},children:F.label}),(v==null?void 0:v.runtime.active)===F.id?s.jsx("span",{style:{fontSize:9,fontWeight:700,color:i.accent},children:"ACTIVE"}):null]}),s.jsx("div",{style:{fontSize:10.5,color:i.textMuted,marginTop:2,lineHeight:1.4},children:F.detail})]}),s.jsx("span",{style:{fontSize:9.5,color:F.ready?"var(--status-success)":i.textMuted},children:F.ready?"Ready":F.configured?"Configured":"Setup required"})]}),F.id==="metricflow-cli"&&(!F.ready||ue)?s.jsxs("div",{style:{marginLeft:17,paddingTop:9,borderTop:"1px solid var(--border-subtle)",display:"grid",gap:8},children:[F.ready?null:s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{fontSize:10.5,color:i.textSecondary,lineHeight:1.45},children:["Install into an isolated ",s.jsx("code",{style:{fontFamily:i.fontMono},children:".dql/runtimes/metricflow"})," environment. DQL never uses sudo or changes system Python."]}),s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[s.jsx("select",{"aria-label":"MetricFlow warehouse adapter",value:O,onChange:ee=>W(ee.target.value),disabled:Le,style:{...st,width:160,height:32,fontFamily:i.font},children:((P==null?void 0:P.supportedAdapters)??[]).map(ee=>s.jsx("option",{value:ee,children:ee==="postgres"?"PostgreSQL":ee.charAt(0).toUpperCase()+ee.slice(1)},ee))}),s.jsxs("button",{type:"button",onClick:()=>void Ie(),disabled:!be||Le||!O,style:{...et,border:"none",background:i.accent,color:"#fff",opacity:!be||Le||!O?.55:1,cursor:!be||Le?"not-allowed":"pointer"},children:[Le?s.jsx(Fn,{className:"dql-dbt-preparing-icon",size:12,style:{verticalAlign:-2,marginRight:6}}):s.jsx(Pc,{size:12,style:{verticalAlign:-2,marginRight:6}}),Le?"Installing…":"Install local MetricFlow"]})]}),be?null:s.jsx("div",{style:{fontSize:9.5,color:i.textMuted},children:"Connect the dbt project first, then install its matching runtime."})]}),ue?s.jsxs("div",{style:{display:"grid",gap:6},children:[s.jsx("div",{role:qe?"alert":"status",style:{fontSize:10.5,color:qe?"var(--status-error)":ue.state==="completed"?"var(--status-success)":i.textSecondary,lineHeight:1.45},children:ue.message}),ue.state==="queued"||ue.state==="running"?s.jsx("div",{"aria-label":"MetricFlow installation progress",style:{height:3,borderRadius:999,background:"var(--border-subtle)",overflow:"hidden"},children:s.jsx("span",{style:{display:"block",height:"100%",width:`${Math.max(4,ue.progress)}%`,background:i.accent,transition:"width 180ms ease"}})}):null,ue.error||ue.logs.length>0?s.jsxs("details",{children:[s.jsx("summary",{style:{cursor:"pointer",fontSize:9.5,color:i.textMuted},children:qe?"View error and manual details":"View installation details"}),s.jsx("pre",{style:{margin:"7px 0 0",maxHeight:130,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:i.fontMono,fontSize:9,lineHeight:1.45,color:qe?"var(--status-error)":i.textMuted},children:[...ue.logs.slice(-30),...ue.error?[ue.error]:[]].join(`
450
- `)})]}):null]}):null]}):null]},F.id))}),s.jsxs("details",{children:[s.jsx("summary",{style:{cursor:"pointer",fontSize:11.5,fontWeight:700,color:i.textSecondary},children:"dbt Cloud Semantic Layer"}),s.jsxs("div",{style:{display:"grid",gap:9,marginTop:11},children:[s.jsxs("label",{style:{display:"grid",gap:5},children:[s.jsx("span",{style:{fontSize:10.5,fontWeight:650,color:i.textSecondary},children:"Host"}),s.jsx("input",{value:A,onChange:F=>R(F.target.value),placeholder:"semantic-layer.cloud.getdbt.com",style:st})]}),s.jsxs("label",{style:{display:"grid",gap:5},children:[s.jsx("span",{style:{fontSize:10.5,fontWeight:650,color:i.textSecondary},children:"Environment ID"}),s.jsx("input",{value:y,onChange:F=>M(F.target.value),placeholder:"123456",style:st})]}),s.jsxs("label",{style:{display:"grid",gap:5},children:[s.jsx("span",{style:{fontSize:10.5,fontWeight:650,color:i.textSecondary},children:"Service token"}),s.jsx("input",{type:"password",value:$,onChange:F=>T(F.target.value),placeholder:(v==null?void 0:v.dbtCloud.serviceTokenPreview)||"Semantic Layer service token",autoComplete:"off",style:st}),s.jsx("span",{style:{fontSize:9.5,color:i.textMuted},children:"Requires Semantic Layer and Metadata permissions. Leave blank to preserve the stored token."})]}),G?s.jsx("div",{role:G.ok?"status":"alert",style:{fontSize:11,color:G.ok?"var(--status-success)":"var(--status-error)"},children:G.text}):null,s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void Ae(),disabled:!!L,style:et,children:L==="test"?"Testing…":"Test draft"}),s.jsx("button",{type:"button",onClick:()=>void ze(),disabled:!!L,style:{...et,border:"none",background:i.accent,color:"#fff"},children:L==="apply"?"Testing & binding…":"Test, bind & save"})]})]})]})]})]})}function Sr(e){return e.map(t=>`${t.catalogOrDatabase}: ${t.schemas.join(", ")}`).join(`
451
- `)}function To(e){const t=new Map;for(const n of e.split(/\r?\n/)){const r=n.indexOf(":");if(r<1)continue;const o=n.slice(0,r).trim(),i=n.slice(r+1).split(",").map(d=>d.trim()).filter(Boolean);if(!o||i.length===0)continue;const l=o.toLowerCase(),a=t.get(l)??{catalogOrDatabase:o,schemas:new Set};for(const d of i)a.schemas.add(d);t.set(l,a)}return Array.from(t.values()).map(n=>({catalogOrDatabase:n.catalogOrDatabase,schemas:Array.from(n.schemas)}))}function pS(e,t,n){return e.some(r=>r.catalogOrDatabase.toLowerCase()===t.toLowerCase()&&r.schemas.some(o=>o.toLowerCase()===n.toLowerCase()))}function fS(e,t,n,r){const o=new Map(e.map(a=>[a.catalogOrDatabase.toLowerCase(),{catalogOrDatabase:a.catalogOrDatabase,schemas:new Map(a.schemas.map(d=>[d.toLowerCase(),d]))}])),i=t.toLowerCase(),l=o.get(i)??{catalogOrDatabase:t,schemas:new Map};return r?l.schemas.set(n.toLowerCase(),n):l.schemas.delete(n.toLowerCase()),l.schemas.size>0?o.set(i,l):o.delete(i),Array.from(o.values()).map(a=>({catalogOrDatabase:a.catalogOrDatabase,schemas:Array.from(a.schemas.values())}))}function hS(e){return e.scopes.reduce((t,n)=>t+n.schemas.filter(r=>!r.inDbtProject).length,0)}const Ro={duckdb:"DuckDB",file:"Local File / DuckDB",snowflake:"Snowflake",databricks:"Databricks"},Tr={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"},mS={duckdb:"In-process analytical database",file:"Local CSV / Parquet via DuckDB",snowflake:"Cloud data platform",databricks:"Lakehouse platform"},io=[{driver:"duckdb",label:"DuckDB",fields:[{key:"filepath",label:"DuckDB file path",type:"text",placeholder:"./local/dev.duckdb",required:!0}]},{driver:"snowflake",label:"Snowflake",fields:[{key:"account",label:"Account",type:"text",required:!0},{key:"warehouse",label:"Warehouse",type:"text",required:!0},{key:"database",label:"Database",type:"text",required:!0},{key:"schema",label:"Schema",type:"text",required:!0},{key:"username",label:"Username",type:"text",required:!0},{key:"authMethod",label:"Authentication",type:"select",options:[{value:"password",label:"Password"},{value:"mfa",label:"Password + MFA"},{value:"key_pair",label:"Key pair / private key"},{value:"external_browser",label:"SSO / external browser"},{value:"oauth",label:"OAuth token"},{value:"oauth_authorization_code",label:"OAuth authorization code"},{value:"oauth_client_credentials",label:"OAuth client credentials"},{value:"programmatic_access_token",label:"Programmatic access token"},{value:"workload_identity",label:"Workload identity"}]},{key:"password",label:"Password",type:"password"},{key:"token",label:"Token",type:"password",helpText:"OAuth, programmatic access token, or OIDC workload identity token."},{key:"privateKeyPath",label:"Private key file path",type:"text",placeholder:"~/.ssh/snowflake_key.p8"},{key:"privateKey",label:"Private key PEM",type:"textarea",helpText:"Paste PEM only when a key file cannot be referenced."},{key:"privateKeyPassphrase",label:"Private key passphrase",type:"password"},{key:"authenticator",label:"Authenticator override",type:"text",placeholder:"EXTERNALBROWSER, OAUTH, WORKLOAD_IDENTITY, or Okta URL"},{key:"role",label:"Role",type:"text"},{key:"accessUrl",label:"Access URL",type:"text"},{key:"application",label:"Application name",type:"text",placeholder:"DQL"},{key:"queryTag",label:"Query tag",type:"text",placeholder:"team=analytics;app=dql"},{key:"passcode",label:"MFA passcode",type:"password"},{key:"passcodeInPassword",label:"MFA passcode is appended to password",type:"checkbox"},{key:"clientRequestMFAToken",label:"Reuse cached MFA token",type:"checkbox"},{key:"clientStoreTemporaryCredential",label:"Cache SSO token locally",type:"checkbox"},{key:"clientSessionKeepAlive",label:"Keep session alive",type:"checkbox"},{key:"clientSessionKeepAliveHeartbeatFrequency",label:"Keep-alive heartbeat seconds",type:"number",placeholder:"3600"},{key:"credentialCacheDir",label:"Credential cache directory",type:"text"},{key:"browserActionTimeout",label:"Browser SSO timeout ms",type:"number",placeholder:"120000"},{key:"keepAlive",label:"Socket keep-alive",type:"checkbox"},{key:"timeout",label:"Connection timeout ms",type:"number",placeholder:"60000"},{key:"proxyHost",label:"Proxy host",type:"text"},{key:"proxyPort",label:"Proxy port",type:"number"},{key:"proxyProtocol",label:"Proxy protocol",type:"text",placeholder:"https"},{key:"proxyUser",label:"Proxy user",type:"text"},{key:"proxyPassword",label:"Proxy password",type:"password"},{key:"noProxy",label:"No proxy hosts",type:"text",placeholder:"*.amazonaws.com|*.internal"},{key:"oauthClientId",label:"OAuth client ID",type:"text"},{key:"oauthClientSecret",label:"OAuth client secret",type:"password"},{key:"oauthAuthorizationUrl",label:"OAuth authorization URL",type:"text"},{key:"oauthTokenRequestUrl",label:"OAuth token request URL",type:"text"},{key:"oauthScope",label:"OAuth scope",type:"text"},{key:"oauthRedirectUri",label:"OAuth redirect URI",type:"text"},{key:"workloadIdentityProvider",label:"Workload identity provider",type:"text",placeholder:"AWS, AZURE, GCP, or OIDC"},{key:"workloadIdentityAzureClientId",label:"Azure client ID",type:"text"}]},{driver:"databricks",label:"Databricks SQL",fields:[{key:"host",label:"Workspace URL",type:"text",required:!0,placeholder:"https://adb-123.cloud.databricks.com"},{key:"database",label:"Catalog / database",type:"text"},{key:"schema",label:"Schema",type:"text"},{key:"warehouse",label:"Warehouse ID",type:"text",helpText:"Use the SQL warehouse ID when you have it."},{key:"httpPath",label:"SQL warehouse ID or path",type:"text",placeholder:"/sql/1.0/warehouses/abc123",helpText:"Paste the warehouse ID or its JDBC/HTTP path."},{key:"authMethod",label:"Authentication",type:"select",options:[{value:"token",label:"Access token"},{value:"oauth",label:"OAuth bearer token"}]},{key:"token",label:"Bearer token",type:"password",required:!0,helpText:"Use an OAuth token for automation when possible, or a service-principal PAT."},{key:"waitTimeout",label:"Statement wait timeout",type:"text",placeholder:"50s"},{key:"byteLimit",label:"Inline byte limit",type:"number",placeholder:"25000000"}]}],Fs=Object.fromEntries(io.map(e=>[e.driver,e])),gS=[{name:"default",label:"Local DuckDB",description:"In-memory DuckDB — no configuration needed",config:{driver:"duckdb",filepath:":memory:"}},{name:"snowflake",label:"Snowflake",description:"Connect to your Snowflake data warehouse",config:{driver:"snowflake",account:"",warehouse:"",database:"",schema:"PUBLIC",username:"",password:""}},{name:"databricks",label:"Databricks SQL",description:"Connect to a Databricks SQL warehouse",config:{driver:"databricks",host:"",warehouse:"",schema:"default",token:""}}];function Mn(e){return e==="postgres"?"postgresql":e}function Xo(e){return{dbname:"database",dataset:"schema",access_url:"accessUrl",auth_method:"authMethod",auth_type:"authMethod",browser_action_timeout:"browserActionTimeout",byte_limit:"byteLimit",client_request_mfa_token:"clientRequestMFAToken",client_session_keep_alive:"clientSessionKeepAlive",client_session_keep_alive_heartbeat_frequency:"clientSessionKeepAliveHeartbeatFrequency",client_store_temporary_credential:"clientStoreTemporaryCredential",credential_cache_dir:"credentialCacheDir",http_path:"httpPath",keep_alive:"keepAlive",keyFile:"keyFilename",keyFileName:"keyFilename",no_proxy:"noProxy",oauth_authorization_url:"oauthAuthorizationUrl",oauth_client_id:"oauthClientId",oauth_client_secret:"oauthClientSecret",oauth_redirect_uri:"oauthRedirectUri",oauth_scope:"oauthScope",oauth_token_request_url:"oauthTokenRequestUrl",passcode_in_password:"passcodeInPassword",private_key:"privateKey",private_key_path:"privateKeyPath",private_key_passphrase:"privateKeyPassphrase",proxy_host:"proxyHost",proxy_password:"proxyPassword",proxy_port:"proxyPort",proxy_protocol:"proxyProtocol",proxy_user:"proxyUser",query_tag:"queryTag",path:"filepath",project:"projectId",server:"host",server_hostname:"host",user:"username",wait_timeout:"waitTimeout",workload_identity_azure_client_id:"workloadIdentityAzureClientId",workload_identity_provider:"workloadIdentityProvider"}[e]??e}function yS(e){return`${e.profileName}_${e.targetName}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"dbt_profile"}function xS(e){const t={};return Object.entries(e.connection??{}).forEach(([n,r])=>{n!=="driver"&&r!==void 0&&r!==null&&(t[Xo(n)]=String(r))}),t}function bS(e){const n=e.indexOf("/.dbt/");return n>=0?`~${e.slice(n)}`:e.split("/").slice(-3).join("/")}function vS(e){const t=e.toLowerCase();return t.includes("password")||t.includes("token")||t.includes("passphrase")||t.includes("privatekey")||t.includes("serviceaccountjson")||t.includes("secretaccesskey")||t.includes("clientsecret")}function la(e,t){return e.startsWith("Error")||e.toLowerCase().includes("failed")?t.error:e.toLowerCase().includes("testing")?t.warning:t.success}function Gn(e){const t=Mn(String((e==null?void 0:e.driver)??(e==null?void 0:e.type)??""));if(t!=="duckdb"&&t!=="file")return!1;const n=(e==null?void 0:e.filepath)??(e==null?void 0:e.path);return!n||n===":memory:"}function SS(e,t,n,r){const o=r!==null&&r===t,i=!!(t&&e[t]),l=e[n];return r===null||o||!i||t==="default"&&Gn(e.default)&&!Gn(l)?n:t}function kS(e){const t=Object.keys(e);return t.find(n=>!Gn(e[n]))??t[0]}function cd({variant:e="panel",onConfigured:t}={}){var Qs,Ys,Xs,Zs;const{state:n,dispatch:r}=xe(),o=Fe[n.themeMode],i=e==="page",l=e==="setup",[a,d]=u.useState(null),[c,f]=u.useState(!1),[p,h]=u.useState(null),[g,S]=u.useState(null),[x,b]=u.useState(!1),[k,C]=u.useState(!1),[E,v]=u.useState(null),[w,A]=u.useState(null),[R,y]=u.useState(""),[M,$]=u.useState(!1),[T,L]=u.useState(null),[I,G]=u.useState([]),[Y,P]=u.useState(!1),[q,O]=u.useState(null),[W,se]=u.useState("dbt_relations"),[H,te]=u.useState(""),[J,B]=u.useState(!1),[ne,ce]=u.useState(null),[re,ge]=u.useState(null),[ye,Ae]=u.useState(!1),[ze,Ie]=u.useState(""),[be,ue]=u.useState("duckdb"),[Le,qe]=u.useState({}),[$e,De]=u.useState("duckdb"),[Ze,ft]=u.useState({}),st=u.useRef(null);u.useEffect(()=>{N.getConnections().then(_=>{d(_),_.metadataScope&&(se(_.metadataScope.mode),te(Sr(_.metadataScope.selectedScopes??_.metadataScope.scopes))),Object.values(_.connections).some(z=>!Gn(z))&&N.testConnection().then(h)})},[]),u.useEffect(()=>{if(!i)return;let _=!0;return Promise.all([N.getProviderSettings(),N.getOnboardingStatus(),N.getBlockStudioDbtStatus().catch(()=>null)]).then(([z,oe,Z])=>{var ae;_&&(G(z.providers),P(((ae=oe.dbt)==null?void 0:ae.configured)===!0||!!(Z!=null&&Z.configured&&Z.artifacts.manifest.exists)),O(oe.preparation??null))}).catch(()=>{}),()=>{_=!1}},[i]),u.useEffect(()=>{if(!i||!q||q.status!=="queued"&&q.status!=="running")return;let _=!0,z;const oe=async()=>{var Z,ae,he;try{const Me=await N.getOnboardingStatus();if(!_)return;O(Me.preparation??null),P(((Z=Me.dbt)==null?void 0:Z.configured)===!0),(((ae=Me.preparation)==null?void 0:ae.status)==="queued"||((he=Me.preparation)==null?void 0:he.status)==="running")&&(z=window.setTimeout(()=>void oe(),700))}catch{}};return z=window.setTimeout(()=>void oe(),500),()=>{_=!1,z!==void 0&&window.clearTimeout(z)}},[q==null?void 0:q.id,q==null?void 0:q.status,i]),u.useEffect(()=>{var Z;if(!a)return;const _=a.default,z=_?(Z=a.connections)==null?void 0:Z[_]:void 0,oe=z?`${_}::${JSON.stringify(z)}`:"::none";if(st.current!==oe)if(st.current=oe,z){De(Mn(String(z.driver??z.type??"duckdb")));const ae={};Object.entries(z).forEach(([he,Me])=>{he!=="driver"&&he!=="type"&&(ae[Xo(he)]=String(Me??""))}),ft(ae)}else De("duckdb"),ft({})},[a]);const et=async()=>{if(!a||Object.keys(a.connections??{}).length===0){h({ok:!1,message:"Add or import a connection before testing."});return}f(!0),h(null);const _=await N.testConnection();h(_),_.ok&&(t==null||t(_.message)),f(!1)},Et=_=>{d(z=>z&&{...z,metadataScope:_.scope,metadataStatus:_.status}),se(_.scope.mode),te(Sr(_.scope.selectedScopes??_.scope.scopes))},Bt=async()=>{if(!(!(a!=null&&a.default)||!(p!=null&&p.ok))){Ae(!0),ce("Finding databases/catalogs and schemas visible to this connection…");try{const _=await N.discoverConnectionMetadataScopes(a.default);ge(_),ce(_.message)}catch(_){ge(null),ce(_ instanceof Error?_.message:String(_))}finally{Ae(!1)}}},Ft=(_,z,oe)=>{const Z=fS(To(H),_,z,oe);te(Sr(Z)),se(((re==null?void 0:re.dbtScopes.length)??0)>0?"dbt_plus_selected":"selected_scopes")},zt=async()=>{if(!(a!=null&&a.default))return;const _=To(H);if(W==="selected_scopes"&&_.length===0){ce("Add at least one line such as ANALYTICS_PROD: SALES, FINANCE.");return}B(!0),ce("Synchronizing selected metadata into local SQLite…");try{const z=await N.applyConnectionMetadataScope(a.default,{mode:W,...W==="dbt_relations"?{}:{scopes:_}});Et(z),ce(`Ready · ${z.status.relationCount.toLocaleString()} relations · ${z.status.columnCount.toLocaleString()} columns · ${z.status.queryCount??0} metadata queries`)}catch(z){ce(z instanceof Error?z.message:String(z))}finally{B(!1)}},qt=async()=>{if(a!=null&&a.default){B(!0),ce("Refreshing the applied metadata scope…");try{const _=await N.refreshConnectionMetadata(a.default);Et(_),ce(`Refreshed · ${_.status.relationCount.toLocaleString()} relations · ${_.status.columnCount.toLocaleString()} columns`)}catch(_){ce(_ instanceof Error?_.message:String(_))}finally{B(!1)}}},Ut=(_,z)=>{S(_),b(!1),Ie(_),ue(Mn((z==null?void 0:z.driver)??(z==null?void 0:z.type)??"duckdb"));const oe={};Object.entries(z??{}).forEach(([Z,ae])=>{Z!=="driver"&&Z!=="type"&&(oe[Xo(Z)]=String(ae??""))}),qe(oe)},F=()=>{b(!0),S(null),Ie(""),ue("duckdb"),qe({})},ee=()=>{S(null),b(!1)},Te=async _=>{A(_),v(null);try{const z=await N.installConnector(_);if(z.connectorStatus&&a)d({...a,connectorStatus:z.connectorStatus});else{const oe=await N.getConnections();d(oe)}v(z.ok?"Connector installed":`Error: ${z.error??"Install failed"}`)}catch(z){v(`Error: ${(z==null?void 0:z.message)??"Install failed"}`)}finally{A(null)}},de=async _=>{if(!a)return!1;C(!0),v(null);const z=_.name.trim()||(_.previousName??"default"),oe={driver:_.driver},Z=Fs[_.driver],ae=new Map(((Z==null?void 0:Z.fields)??[]).map(Ne=>[Ne.key,Ne]));Object.entries(_.fields).forEach(([Ne,Ue])=>{const at=ae.get(Ne);if((at==null?void 0:at.type)==="checkbox"){Ue!==""&&(oe[Ne]=Ue==="true");return}const ar=Ue.trim();ar&&((at==null?void 0:at.type)==="number"&&!isNaN(Number(ar))?oe[Ne]=Number(ar):oe[Ne]=ar)});const he={...a.connections},Me=a.default,tn={...a.connections};_.previousName&&_.previousName!==z&&delete tn[_.previousName],tn[z]=oe;const Md=SS(tn,a.default,z,_.previousName);let ei=!1;try{await N.saveConnections(tn,Md);const Ne=await N.getConnections();d(Ne),Ne.metadataScope&&(se(Ne.metadataScope.mode),te(Sr(Ne.metadataScope.selectedScopes??Ne.metadataScope.scopes))),ge(null),v("Saved. Testing connection..."),S(null),b(!1);try{f(!0);const Ue=await N.testConnection();if(h(Ue),ei=Ue.ok,Ue.ok)v("Test passed. Connection saved and activated."),t==null||t(Ue.message),setTimeout(()=>v(null),2e3);else{await N.saveConnections(he,Me||void 0);const at=await N.getConnections();d(at),v(`Test failed. Previous connection preserved: ${Ue.message}`)}}catch(Ue){await N.saveConnections(he,Me||void 0).catch(()=>{});const at=await N.getConnections().catch(()=>null);at&&d(at),v(`Test failed. Previous connection preserved: ${Ue.message??"Connection failed"}`)}finally{f(!1)}}catch(Ne){await N.saveConnections(he,Me||void 0).catch(()=>{});const Ue=await N.getConnections().catch(()=>null);Ue&&d(Ue),v(`Test or save failed. Previous connection preserved: ${Ne.message}`)}finally{C(!1)}return ei},Q=_=>{const z=Mn(String(_.connection.driver??_.adapter??"duckdb")),oe=xS(_);h(null),(i||l)&&(De(z),ft(oe)),b(!1),S(null),de({name:yS(_),driver:z,fields:oe,previousName:null})},K=async()=>{const _=R.trim();if(!_){L("Enter a profiles.yml file or folder path.");return}$(!0),L(null);try{const z=await N.previewDbtProfiles(_);d(oe=>{if(!oe)return oe;const Z=new Map((oe.dbtProfiles??[]).map(ae=>[ae.id,ae]));return z.dbtProfiles.forEach(ae=>Z.set(ae.id,ae)),{...oe,dbtProfiles:[...Z.values()]}})}catch(z){L(z instanceof Error?z.message:"Could not read that profiles.yml path.")}finally{$(!1)}},Se=()=>de({name:ze,driver:be,fields:Le,previousName:g}),wn=()=>de({name:(a==null?void 0:a.default)||"default",driver:$e,fields:Ze,previousName:(a==null?void 0:a.default)||null}),en=_=>{De(_),ft({}),h(null)},nr=async _=>{if(!a)return;const z={...a.connections};delete z[_];const oe=_===a.default?kS(z):a.default;C(!0);try{await N.saveConnections(z,oe);const Z=await N.getConnections();d(Z),S(null)}finally{C(!1)}},Cd=async _=>{if(!a)return;const z=a.default;C(!0),v(null);try{await N.saveConnections(a.connections,_);const oe=await N.getConnections();d(oe),v("Default updated. Testing connection..."),f(!0);const Z=await N.testConnection();if(h(Z),Z.ok)v("Test passed. Default connection updated."),t==null||t(Z.message),setTimeout(()=>v(null),2e3);else{await N.saveConnections(a.connections,z||void 0);const ae=await N.getConnections();d(ae),v(`Test failed. Previous default preserved: ${Z.message}`)}}catch(oe){await N.saveConnections(a.connections,z||void 0).catch(()=>{});const Z=await N.getConnections().catch(()=>null);Z&&d(Z),v(`Test or save failed. Previous default preserved: ${oe.message}`)}finally{f(!1),C(!1)}},rr={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:o.textMuted,fontFamily:o.font,marginBottom:6},or={background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},sr=(a==null?void 0:a.connections)??{},Ed=(a==null?void 0:a.default)??"",Ws=(a==null?void 0:a.dbtProfiles)??[],Ks=Object.fromEntries(((a==null?void 0:a.connectorStatus)??[]).map(_=>[_.driver,_])),Vs=Object.keys(sr).length,ir=Vs>0,Ad=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:rr,children:"Connections"}),a===null?s.jsx("div",{style:{fontSize:12,color:o.textMuted,fontFamily:o.font},children:"Loading…"}):Object.entries(sr).map(([_,z])=>{const oe=(z==null?void 0:z.driver)??(z==null?void 0:z.type)??"unknown",Z=_===Ed,ae=Tr[oe]??o.accent;return g===_?s.jsx(ca,{t:o,editName:ze,setEditName:Ie,editDriver:be,setEditDriver:ue,editFields:Le,setEditFields:qe,onSave:Se,onCancel:ee,onDelete:()=>nr(_),saving:k,isNew:!1},_):s.jsxs("div",{style:{...or,borderLeft:Z?`3px solid ${ae}`:`1px solid ${o.cellBorder}`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[s.jsx(Dn,{driver:oe,size:18,fallbackColor:ae}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:Ro[oe]??oe}),s.jsx("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted},children:_}),Z&&(p==null?void 0:p.ok)&&s.jsx("span",{title:"Connected","aria-label":"Connected",style:{width:7,height:7,borderRadius:"50%",background:o.success,flexShrink:0,boxShadow:`0 0 0 2px ${o.success}25`}}),Z&&p&&!p.ok&&s.jsx("span",{title:p.message,"aria-label":"Disconnected",style:{width:7,height:7,borderRadius:"50%",background:o.error,flexShrink:0,boxShadow:`0 0 0 2px ${o.error}25`}}),Z&&s.jsx("span",{style:{fontSize:9,color:o.accent,fontFamily:o.font,fontWeight:600,letterSpacing:"0.05em"},children:"DEFAULT"}),s.jsx("div",{style:{flex:1}}),!Z&&s.jsx("button",{onClick:()=>Cd(_),disabled:k,style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:3,cursor:k?"not-allowed":"pointer",color:o.textMuted,fontSize:10,fontFamily:o.font,padding:"1px 6px",transition:"all 0.15s"},children:"Use"}),s.jsx("button",{onClick:()=>Ut(_,z),style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:3,cursor:"pointer",color:o.textMuted,fontSize:10,fontFamily:o.font,padding:"1px 6px",transition:"all 0.15s"},children:"Edit"})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:3},children:Object.entries(z??{}).filter(([he])=>he!=="driver"&&he!=="type").map(([he,Me])=>s.jsxs("div",{style:{display:"flex",gap:6,alignItems:"baseline"},children:[s.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.fontMono,minWidth:70,flexShrink:0},children:he}),s.jsx("span",{style:{fontSize:11,color:o.textSecondary,fontFamily:o.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:vS(he)?"••••••••":String(Me)})]},he))})]},_)}),a!==null&&Vs===0&&s.jsx("div",{style:{...or,color:o.textMuted,fontSize:12,fontFamily:o.font,lineHeight:1.45},children:"No saved connections yet. Import a dbt profile target or add one manually."})]}),Hs=s.jsxs("div",{style:{...or,marginBottom:12},children:[s.jsx("div",{style:{fontSize:12,fontWeight:650,color:o.textPrimary,fontFamily:o.font},children:"Import dbt profiles.yml"}),s.jsx("div",{style:{marginTop:3,fontSize:10.5,color:o.textMuted,lineHeight:1.45,fontFamily:o.font},children:"Load a profiles.yml, profiles.yaml, profile.yml, or profile.yaml file. DuckDB, Snowflake, and Databricks targets are supported."}),s.jsxs("div",{style:{display:"flex",gap:7,marginTop:9},children:[s.jsx("input",{"aria-label":"dbt profile file or folder path",value:R,onChange:_=>y(_.target.value),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),K())},placeholder:"~/.dbt/profiles.yml or /path/to/profile.yaml",style:{flex:1,minWidth:0,border:`1px solid ${o.inputBorder}`,borderRadius:6,background:o.inputBg,color:o.textPrimary,padding:"7px 9px",fontSize:11.5,fontFamily:o.fontMono,outline:"none"}}),s.jsx("button",{type:"button",onClick:()=>void K(),disabled:M,style:{border:`1px solid ${o.btnBorder}`,borderRadius:6,background:o.btnBg,color:o.textSecondary,padding:"0 11px",fontSize:11,fontWeight:650,fontFamily:o.font,cursor:M?"wait":"pointer"},children:M?"Reading…":"Find profiles"})]}),T?s.jsx("div",{role:"alert",style:{marginTop:6,color:o.error,fontSize:10.5,fontFamily:o.font},children:T}):null]}),Gs=s.jsx(s.Fragment,{children:!x&&!g&&Ws.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...rr,marginTop:8},children:"dbt profiles"}),s.jsx("div",{style:{display:"grid",gap:8,marginBottom:12},children:Ws.map(_=>{var he;const z=Mn(String(_.connection.driver??_.adapter)),oe=Tr[z]??o.accent,Z=_.missingFields.length===0,ae=((he=a==null?void 0:a.activeConnection)==null?void 0:he.source)==="dbt_profile"&&a.activeConnection.profileId===_.id;return s.jsxs("div",{style:{...or,marginBottom:0,display:"flex",alignItems:"center",gap:10},children:[s.jsx(Dn,{driver:z,size:18,fallbackColor:oe}),s.jsxs("div",{style:{minWidth:0,flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[s.jsx("span",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:_.profileName}),s.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.fontMono},children:_.targetName})]}),s.jsxs("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[Ro[z]??_.adapter," from ",bS(_.path)]}),s.jsx("div",{style:{fontSize:10,color:Z?o.success:o.warning,fontFamily:o.font,marginTop:2},children:Z?ae?"Active runtime connection · import to save":"Ready to import and test":`Imports now · needs ${_.missingFields.join(", ")}`})]}),s.jsx("button",{onClick:()=>Q(_),disabled:k,title:_.warnings.join(" ")||void 0,style:{background:o.btnBg,border:`1px solid ${o.btnBorder}`,borderRadius:4,cursor:k?"wait":"pointer",color:o.textSecondary,fontSize:11,fontFamily:o.font,padding:"4px 8px",flexShrink:0},children:"Import & test"})]},_.id)})})]})}),Td=s.jsx(s.Fragment,{children:!x&&!g&&Object.keys(sr).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...rr,marginTop:8},children:"Quick Connect"}),s.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:gS.map(_=>s.jsxs("button",{onClick:async()=>{C(!0);try{const z={...sr,[_.name]:_.config};await N.saveConnections(z,_.name);const oe=await N.getConnections();d(oe),f(!0);const Z=await N.testConnection();h(Z),f(!1)}finally{C(!1)}},disabled:k,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:7,cursor:k?"not-allowed":"pointer",textAlign:"left",transition:"border-color 0.15s"},children:[s.jsx(Dn,{driver:_.config.driver,size:18}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:_.label}),s.jsx("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:_.description})]})]},_.name))})]})}),Rd=s.jsx(s.Fragment,{children:x?s.jsx(ca,{t:o,editName:ze,setEditName:Ie,editDriver:be,setEditDriver:ue,editFields:Le,setEditFields:qe,onSave:Se,onCancel:ee,saving:k,isNew:!0}):s.jsxs("button",{onClick:F,style:{width:"100%",padding:"7px 0",borderRadius:6,border:`1px dashed ${o.cellBorder}`,background:"transparent",color:o.textSecondary,fontSize:12,fontFamily:o.font,fontWeight:500,cursor:"pointer",marginBottom:12,display:"flex",alignItems:"center",justifyContent:"center",gap:6,transition:"border-color 0.15s, color 0.15s"},children:[s.jsx("span",{style:{fontSize:16,lineHeight:1},children:"+"}),"Add Connection"]})}),_d=s.jsx(s.Fragment,{children:E&&s.jsx("div",{style:{fontSize:11,fontFamily:o.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:la(E,o),background:`${la(E,o)}12`},children:E})}),$d=s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:et,disabled:c||!ir,style:{width:"100%",padding:"7px 0",borderRadius:6,border:`1px solid ${o.btnBorder}`,background:o.btnBg,color:o.textSecondary,fontSize:12,fontFamily:o.font,fontWeight:500,cursor:c||!ir?"not-allowed":"pointer",marginBottom:8,opacity:c||!ir?.7:1,transition:"all 0.15s"},children:c?"Testing...":ir?"Test Connection":"Add connection to test"}),p&&s.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:p.ok?o.success:o.error,background:p.ok?`${o.success}12`:`${o.error}12`,border:`1px solid ${p.ok?o.success:o.error}40`,borderRadius:6,padding:"7px 10px",marginBottom:12},children:[p.ok?"✓ ":"✗ ",p.message]})]}),Od=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...rr,marginTop:4},children:"Catalog"}),s.jsx("div",{className:i?"dql-connection-catalog-grid":void 0,style:{display:"grid",gridTemplateColumns:i?"repeat(auto-fit, minmax(180px, 1fr))":"repeat(auto-fill, minmax(160px, 1fr))",gap:8,marginBottom:12},children:io.map(({driver:_,label:z})=>{const oe=Tr[_]??o.accent,Z=mS[_]??"",ae=Ks[_],he=(ae==null?void 0:ae.installed)??!0,Me=(ae==null?void 0:ae.builtIn)??!1,tn=w===_;return s.jsxs("div",{style:{background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:8,padding:"10px 12px",display:"flex",flexDirection:"column",gap:4,minHeight:76,position:"relative",transition:"border-color 0.15s"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx(Dn,{driver:_,size:18,fallbackColor:oe}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:z})]}),s.jsx("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font,lineHeight:1.35},children:Z}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,marginTop:"auto"},children:[s.jsx("span",{style:{fontSize:9,fontFamily:o.font,fontWeight:600,color:he?o.success:o.warning,letterSpacing:"0.05em",textTransform:"uppercase"},children:Me?"Built in":he?"Installed":"Install required"}),!he&&s.jsx("button",{onClick:()=>Te(_),disabled:!!w,title:ae==null?void 0:ae.installCommand,style:{border:`1px solid ${o.btnBorder}`,background:o.btnBg,color:o.textSecondary,borderRadius:4,padding:"2px 7px",fontSize:10,fontFamily:o.font,cursor:w?"not-allowed":"pointer",whiteSpace:"nowrap"},children:tn?"Installing...":"Install"})]}),s.jsx("code",{style:{fontSize:9,color:o.textMuted,fontFamily:o.fontMono},children:_})]},_)})})]}),it=!!(a&&Object.values(a.connections??{}).some(_=>!Gn(_))),Re=a==null?void 0:a.metadataStatus,Pd=To(H),Dd=it?s.jsxs("div",{style:{maxWidth:640,border:`1px solid ${o.cellBorder}`,borderRadius:12,background:o.cellBg,padding:"16px 18px",display:"flex",flexDirection:"column",gap:12},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:14,fontWeight:700,color:o.textPrimary,fontFamily:o.font},children:"Metadata scope"}),s.jsx("div",{style:{fontSize:11.5,color:o.textMuted,marginTop:3,lineHeight:1.5,fontFamily:o.font},children:"DQL synchronizes this authorized scope into local SQLite. Warm Ask, Notebook, and Block Studio searches use that index instead of scanning the warehouse."})]}),s.jsxs("div",{style:{border:`1px solid ${o.cellBorder}`,borderRadius:9,padding:"11px 12px",background:o.editorBg,display:"flex",flexDirection:"column",gap:9},children:[s.jsxs("div",{style:{fontSize:11.5,lineHeight:1.5,color:o.textSecondary,fontFamily:o.font},children:[s.jsx("strong",{style:{color:o.textPrimary},children:"Only add schemas outside the configured dbt project."})," ","Relations already present in the current dbt manifest are indexed automatically and should not be selected again."]}),s.jsx("div",{children:s.jsx("button",{type:"button",onClick:()=>void Bt(),disabled:ye||J||!(p!=null&&p.ok),style:{height:31,padding:"0 12px",borderRadius:8,border:`1px solid ${o.cellBorder}`,background:o.cellBg,color:o.textSecondary,fontSize:11.5,fontWeight:650,cursor:ye||J||!(p!=null&&p.ok)?"not-allowed":"pointer",opacity:p!=null&&p.ok?1:.55,fontFamily:o.font},children:ye?"Finding available schemas…":"Find available databases & schemas"})}),re?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10.5,color:o.textMuted,fontFamily:o.font},children:[re.dbtScopes.reduce((_,z)=>_+z.schemas.length,0).toLocaleString()," dbt-covered schema(s)"," · ",hS(re).toLocaleString()," additional schema(s) available"," · ",re.queryCount.toLocaleString()," discovery query(s)"]}),re.scopes.map(_=>s.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`,paddingTop:7},children:[s.jsx("div",{style:{fontSize:10.5,fontWeight:700,color:o.textPrimary,fontFamily:o.fontMono,marginBottom:5},children:_.catalogOrDatabase}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:5},children:_.schemas.map(z=>{const oe=pS(Pd,_.catalogOrDatabase,z.name);return s.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:7,fontSize:11,lineHeight:1.35,color:z.inDbtProject?o.textMuted:o.textSecondary,fontFamily:o.font,cursor:z.inDbtProject?"default":"pointer"},children:[s.jsx("input",{type:"checkbox",checked:z.inDbtProject||oe,disabled:z.inDbtProject||J,onChange:Z=>Ft(_.catalogOrDatabase,z.name,Z.target.checked),style:{marginTop:1}}),s.jsxs("span",{children:[s.jsx("span",{style:{fontFamily:o.fontMono},children:z.name}),z.inDbtProject?` · in dbt (${z.dbtRelationCount} relation${z.dbtRelationCount===1?"":"s"}), included automatically`:" · outside dbt, select only if reporting needs it"]})]},`${_.catalogOrDatabase}.${z.name}`)})})]},_.catalogOrDatabase)),re.truncated?s.jsx("div",{style:{fontSize:10.5,color:"var(--status-warning)",fontFamily:o.font},children:"Discovery reached its safety limit. Narrow the connection role or enter another known database/schema manually."}):null]}):null]}),s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:5,fontFamily:o.font},children:[s.jsx("span",{style:{fontSize:11.5,fontWeight:650,color:o.textSecondary},children:"Index mode"}),s.jsxs("select",{value:W,onChange:_=>se(_.target.value),disabled:J,style:{height:34,borderRadius:7,border:`1px solid ${o.cellBorder}`,background:o.cellBg,color:o.textPrimary,padding:"0 10px",fontFamily:o.font},children:[s.jsx("option",{value:"dbt_relations",children:"Use exact dbt project relations (recommended)"}),s.jsx("option",{value:"dbt_plus_selected",children:"dbt relations plus selected schemas"}),s.jsx("option",{value:"selected_scopes",children:"Selected databases/catalogs and schemas"})]})]}),W!=="dbt_relations"?s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:5,fontFamily:o.font},children:[s.jsx("span",{style:{fontSize:11.5,fontWeight:650,color:o.textSecondary},children:"Databases/catalogs and schemas"}),s.jsx("textarea",{value:H,onChange:_=>te(_.target.value),disabled:J,placeholder:`ANALYTICS_PROD: SALES, FINANCE
452
- REFERENCE_DATA: SHARED`,rows:4,style:{resize:"vertical",borderRadius:7,border:`1px solid ${o.cellBorder}`,background:o.cellBg,color:o.textPrimary,padding:"8px 10px",fontFamily:o.fontMono,fontSize:11.5,lineHeight:1.5}}),s.jsx("span",{style:{fontSize:10.5,color:o.textMuted},children:"Only additional schemas outside dbt belong here. Discovery is explicit and setup-only; Ask AI never scans the warehouse for available schemas."})]}):null,Re?s.jsxs("div",{style:{fontSize:11.5,color:Re.state==="ready"?"var(--status-success)":"var(--status-warning)",fontFamily:o.font},children:[Re.state==="ready"?"Ready":Re.state==="stale"?"Refresh required":"Not synchronized"," · ",Re.relationCount.toLocaleString()," relations"," · ",Re.columnCount.toLocaleString()," columns",Re.capturedAt?` · ${new Date(Re.capturedAt).toLocaleString()}`:""]}):null,Re!=null&&Re.observedTarget?s.jsx("div",{style:{fontSize:10.5,color:o.textMuted,fontFamily:o.fontMono},children:[Re.observedTarget.accountOrWorkspace,Re.observedTarget.role,Re.observedTarget.warehouse,Re.observedTarget.defaultCatalogOrDatabase,Re.observedTarget.defaultSchema].filter(Boolean).join(" · ")}):null,ne?s.jsx("div",{style:{fontSize:11.5,color:ne.toLowerCase().includes("failed")||ne.toLowerCase().includes("error")?"var(--status-error)":o.textSecondary,fontFamily:o.font},children:ne}):null,s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void zt(),disabled:J||!(p!=null&&p.ok),style:{height:32,padding:"0 13px",borderRadius:8,border:"none",background:o.accent,color:"var(--accent-fg)",fontSize:12,fontWeight:700,cursor:J||!(p!=null&&p.ok)?"not-allowed":"pointer",opacity:J||!(p!=null&&p.ok)?.55:1,fontFamily:o.font},children:J?"Synchronizing…":"Apply and synchronize"}),s.jsx("button",{type:"button",onClick:()=>void qt(),disabled:J||(Re==null?void 0:Re.state)==="missing",style:{height:32,padding:"0 13px",borderRadius:8,border:`1px solid ${o.cellBorder}`,background:o.cellBg,color:o.textSecondary,fontSize:12,fontWeight:650,cursor:J?"not-allowed":"pointer",fontFamily:o.font},children:"Refresh metadata"})]}),p!=null&&p.ok?null:s.jsx("div",{style:{fontSize:10.5,color:o.textMuted,fontFamily:o.font},children:"Test the active connection before applying its metadata scope."})]}):null,Js=s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:17,fontWeight:700,color:o.textPrimary,fontFamily:o.font},children:"Database connection"}),s.jsx("div",{style:{fontSize:12.5,color:o.textMuted,marginTop:3,lineHeight:1.5,fontFamily:o.font},children:"Import a dbt profile or configure the warehouse directly. The candidate is tested before it replaces the active connection."})]}),s.jsxs("div",{style:{border:`1px solid ${p!=null&&p.ok?"var(--status-success-border)":"var(--border-subtle)"}`,borderRadius:12,background:o.cellBg,padding:"16px 18px",display:"flex",alignItems:"center",gap:12,maxWidth:640},children:[s.jsx("span",{style:{width:36,height:36,borderRadius:9,background:it?"var(--status-success-bg)":"var(--status-warning-bg)",color:it?"var(--status-success)":"var(--status-warning)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx(tr,{size:17,strokeWidth:1.75})}),s.jsxs("div",{style:{flex:1,minWidth:0,fontFamily:o.font},children:[s.jsxs("div",{style:{fontSize:13,fontWeight:700,color:o.textPrimary},children:[Ro[String(((Ys=(Qs=a==null?void 0:a.connections)==null?void 0:Qs[(a==null?void 0:a.default)??""])==null?void 0:Ys.driver)??"")]??((Zs=(Xs=a==null?void 0:a.connections)==null?void 0:Xs[(a==null?void 0:a.default)??""])==null?void 0:Zs.driver)??"No connection yet",it?" · configured":""]}),s.jsx("div",{style:{fontSize:11.5,marginTop:2,color:c?o.textMuted:p?p.ok?"var(--status-success)":"var(--status-error)":o.textMuted},children:c?"Testing…":p?p.ok?`Test passed · ${p.message}`:`Test failed · ${p.message}`:it?"Configured — run Test connection to verify.":"Add a connection below to get started."})]}),s.jsx("button",{type:"button",onClick:()=>void et(),disabled:c||!it,style:{display:"inline-flex",alignItems:"center",gap:6,height:30,padding:"0 13px",borderRadius:8,border:`1px solid ${o.cellBorder}`,background:o.cellBg,color:o.textSecondary,fontSize:12,fontWeight:650,cursor:it?"pointer":"not-allowed",fontFamily:o.font,flexShrink:0,opacity:it?1:.55},children:c?"Testing…":"Test connection"})]}),s.jsxs("div",{style:{maxWidth:640},children:[Hs,Gs]}),s.jsx(ES,{t:o,driver:$e,fields:Ze,onDriverChange:en,onFieldsChange:ft,onSave:()=>void wn(),saving:k,saveMessage:E,connectorStatus:Ks[$e],installing:w===$e,onInstall:()=>void Te($e)}),Dd]});if(l)return Js;if(i){const _=n.settingsTab,z=I.some(Z=>Z.configured&&Z.enabled),oe=(Z,ae,he,Me)=>s.jsxs("button",{type:"button",onClick:he,style:{display:"flex",alignItems:"center",gap:9,padding:"8px 10px",borderRadius:7,border:"none",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:600,fontFamily:o.font,width:"100%",background:Z?"var(--accent-dim)":"transparent",color:Z?o.accent:o.textSecondary},children:[s.jsx("span",{style:{flex:1},children:ae}),Me]},ae);return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:jS}),s.jsxs("div",{style:{display:"flex",gap:0,alignItems:"stretch",minHeight:0},children:[s.jsxs("nav",{"aria-label":"Settings sections",style:{width:"clamp(190px, 17vw, 240px)",flexShrink:0,borderRight:`1px solid ${o.cellBorder}`,padding:"10px 10px 10px 0",display:"flex",flexDirection:"column",gap:2,alignSelf:"flex-start",position:"sticky",top:0},children:[oe(_==="overview","Overview",()=>r({type:"SET_SETTINGS_TAB",tab:"overview"})),oe(_==="project","Project & dbt",()=>r({type:"SET_SETTINGS_TAB",tab:"project"}),s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:(q==null?void 0:q.status)==="failed"?"var(--status-error)":(q==null?void 0:q.status)==="running"||(q==null?void 0:q.status)==="queued"?"var(--status-info)":Y?"var(--status-success)":"var(--status-warning)"},title:(q==null?void 0:q.status)==="failed"?"Needs attention":(q==null?void 0:q.status)==="running"||(q==null?void 0:q.status)==="queued"?"Preparing":Y?"Ready":"Missing"})),oe(_==="database","Database",()=>r({type:"SET_SETTINGS_TAB",tab:"database"}),s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:it?"var(--status-success)":"var(--status-warning)"},title:it?"Configured":"Missing"})),oe(_==="ai","AI provider",()=>r({type:"SET_SETTINGS_TAB",tab:"ai"}),s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:z?"var(--status-success)":"var(--status-warning)"},title:z?"Configured":"Optional · missing"})),oe(_==="memory","Agent memory",()=>r({type:"SET_SETTINGS_TAB",tab:"memory"})),s.jsx("div",{style:{height:1,background:o.cellBorder,margin:"10px 10px 10px 0"}}),oe(_==="advanced","Advanced",()=>r({type:"SET_SETTINGS_TAB",tab:"advanced"}),s.jsx("span",{style:{fontSize:10,color:o.textMuted},children:"Advanced"}))]}),s.jsx("div",{style:{flex:1,minWidth:0,padding:"0 0 24px 20px"},children:_==="overview"?s.jsx(wS,{dbtConfigured:Y,dbtPreparation:q,databaseConfigured:it,databaseTest:p,providers:I}):_==="project"?s.jsx(uS,{onConfigured:()=>{P(!0),N.getOnboardingStatus().then(Z=>O(Z.preparation??null)).catch(()=>{})}}):_==="advanced"?s.jsx(jo,{embedded:!0,section:"advanced"}):_==="database"?Js:_==="ai"?s.jsx(jo,{embedded:!0,section:"providers",onProviderConfigured:Z=>G(ae=>ae.map(he=>he.id===Z.id?Z:{...he,active:!1}))}):s.jsx(jo,{embedded:!0,section:"memory"})})]})]})}return s.jsxs(Ts,{title:"Connections",bodyPadding:12,children:[Ad,Hs,Gs,Td,Rd,_d,$d,Od]})}function wS({dbtConfigured:e,dbtPreparation:t,databaseConfigured:n,databaseTest:r,providers:o}){const{state:i,dispatch:l}=xe(),a=Fe[i.themeMode],d=o.find(p=>p.active&&p.configured)??o.find(p=>p.enabled&&p.configured),c=[{title:"Project & dbt",detail:(t==null?void 0:t.message)??(e?"Project configuration, dbt artifacts, and governed search indexes are ready.":"Choose a local dbt project or Git repository."),state:(t==null?void 0:t.status)==="failed"||(t==null?void 0:t.status)==="cancelled"?"failed":(t==null?void 0:t.status)==="running"||(t==null?void 0:t.status)==="queued"?"preparing":e?"configured":"missing",tab:"project",icon:s.jsx(Sn,{size:18})},{title:"Database",detail:r!=null&&r.ok||r?r.message:n?"Credentials are configured. Run Test to verify reachability.":"Import a dbt profile or enter warehouse credentials.",state:r?r.ok?"passed":"failed":n?"configured":"missing",tab:"database",icon:s.jsx(tr,{size:18})},{title:"AI provider",detail:d?`${d.label}${d.model?` · ${d.model}`:""}. Run Test to verify reachability.`:"Optional. Deterministic and non-AI workflows remain available.",state:d?"configured":"missing",tab:"ai",icon:s.jsx(Lc,{size:18}),optional:!0}],f={missing:"Missing",configured:"Configured",preparing:"Preparing",passed:"Test passed",failed:"Test failed"};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:820},children:[s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:16},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:20,fontWeight:750,color:a.textPrimary},children:"Settings overview"}),s.jsx("div",{style:{fontSize:12.5,color:a.textMuted,marginTop:4,lineHeight:1.5},children:"One place for project, data, AI, memory, and advanced runtime configuration."})]}),s.jsxs("button",{type:"button",onClick:()=>l({type:"OPEN_SETUP"}),style:{display:"inline-flex",alignItems:"center",gap:7,height:34,padding:"0 15px",borderRadius:8,border:"none",background:a.accent,color:"#fff",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:a.font,whiteSpace:"nowrap"},children:[s.jsx(lx,{size:14})," Guided Setup"]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:12},children:c.map(p=>{const h=p.state==="configured"||p.state==="passed",g=p.state==="preparing",S=p.state==="failed",x=S?"var(--status-error)":g?"var(--status-info)":h?"var(--status-success)":"var(--status-warning)",b=S?"var(--status-error-bg)":g?"var(--status-info-bg)":h?"var(--status-success-bg)":"var(--status-warning-bg)";return s.jsxs("button",{type:"button",onClick:()=>l({type:"SET_SETTINGS_TAB",tab:p.tab}),style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:a.cellBg,padding:16,textAlign:"left",cursor:"pointer",fontFamily:a.font,minHeight:158,display:"flex",flexDirection:"column"},children:[s.jsx("span",{style:{width:36,height:36,borderRadius:9,display:"inline-flex",alignItems:"center",justifyContent:"center",color:x,background:b},children:h?s.jsx(Oc,{size:18}):p.icon}),s.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:a.textPrimary,marginTop:12},children:p.title}),s.jsxs("span",{style:{fontSize:11,fontWeight:700,color:x,marginTop:4},children:[f[p.state],p.optional?" · optional":""]}),s.jsx("span",{style:{fontSize:11.5,color:a.textMuted,lineHeight:1.45,marginTop:7},children:p.detail})]},p.title)})}),d?null:s.jsx("div",{style:{border:"1px solid var(--status-info-border)",background:"var(--status-info-bg)",color:a.textSecondary,borderRadius:10,padding:"11px 13px",fontSize:11.5,lineHeight:1.5},children:"Limited-AI mode is active: SQL execution, dbt metadata, lineage, deterministic helpers, and other non-AI paths continue to work. Configure a provider when you want governed Ask and AI-assisted authoring."})]})}const jS=`
453
- .dql-connection-page-stack {
454
- display: grid;
455
- gap: 16px;
456
- }
457
-
458
- .dql-connection-page-grid {
459
- display: grid;
460
- grid-template-columns: minmax(0, 1.18fr) minmax(320px, 0.82fr);
461
- gap: 16px;
462
- align-items: start;
463
- }
464
-
465
- @media (max-width: 920px) {
466
- .dql-connection-page-grid {
467
- grid-template-columns: minmax(0, 1fr);
468
- }
469
- }
470
-
471
- @keyframes dql-connector-shimmer {
472
- 0% { opacity: 1; }
473
- 50% { opacity: 0.45; }
474
- 100% { opacity: 1; }
475
- }
476
-
477
- .dql-connector-installing {
478
- animation: dql-connector-shimmer 1.4s ease-in-out infinite;
479
- }
480
- `;function ca({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:i,setEditFields:l,onSave:a,onCancel:d,onDelete:c,saving:f,isNew:p}){const h=Fs[r],g=(h==null?void 0:h.fields)??[],S={background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:4,color:e.textPrimary,fontSize:11,fontFamily:e.fontMono,padding:"4px 8px",outline:"none",width:"100%"},x={fontSize:9,fontWeight:600,color:e.textMuted,fontFamily:e.font,letterSpacing:"0.05em",textTransform:"uppercase",marginBottom:2};return s.jsxs("div",{style:{background:e.cellBg,border:`1px solid ${e.accent}40`,borderRadius:7,padding:"10px 12px",marginBottom:10},children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:e.accent,fontFamily:e.font,marginBottom:8},children:p?"New Connection":"Edit Connection"}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:x,children:"Name"}),s.jsx("input",{style:S,value:t,onChange:b=>n(b.target.value),placeholder:"e.g. production"})]}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:x,children:"Driver"}),s.jsx("select",{style:{...S,fontFamily:e.font},value:r,onChange:b=>{o(b.target.value),l({})},children:io.map(b=>s.jsx("option",{value:b.driver,children:b.label},b.driver))})]}),g.map(b=>s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("div",{style:x,children:[b.label,b.required?" *":""]}),b.type==="select"?s.jsxs("select",{style:{...S,fontFamily:e.font},value:i[b.key]??"",onChange:k=>l({...i,[b.key]:k.target.value}),children:[s.jsx("option",{value:"",children:"Default"}),(b.options??[]).map(k=>s.jsx("option",{value:k.value,children:k.label},k.value))]}):b.type==="checkbox"?s.jsxs("label",{style:{display:"flex",alignItems:"center",gap:7,fontSize:11,color:e.textSecondary,fontFamily:e.font},children:[s.jsx("input",{type:"checkbox",checked:i[b.key]==="true",onChange:k=>l({...i,[b.key]:k.target.checked?"true":"false"})}),"Enabled"]}):b.type==="textarea"?s.jsx("textarea",{style:{...S,minHeight:72,resize:"vertical"},value:i[b.key]??"",placeholder:b.placeholder??"",onChange:k=>l({...i,[b.key]:k.target.value})}):s.jsx("input",{style:S,type:b.type==="password"?"password":b.type==="number"?"number":"text",value:i[b.key]??"",placeholder:b.placeholder??"",onChange:k=>l({...i,[b.key]:k.target.value})}),b.helpText&&s.jsx("div",{style:{fontSize:10,color:e.textMuted,fontFamily:e.font,marginTop:3,lineHeight:1.35},children:b.helpText})]},b.key)),s.jsxs("div",{style:{display:"flex",gap:6,marginTop:8},children:[s.jsx("button",{onClick:a,disabled:f,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:f?"not-allowed":"pointer",opacity:f?.6:1},children:f?"Saving…":"Save"}),s.jsx("button",{onClick:d,style:{padding:"5px 12px",borderRadius:5,border:`1px solid ${e.btnBorder}`,background:"transparent",color:e.textSecondary,fontSize:11,fontFamily:e.font,cursor:"pointer"},children:"Cancel"}),c&&!p&&s.jsx("button",{onClick:c,style:{padding:"5px 12px",borderRadius:5,border:`1px solid ${e.error}40`,background:"transparent",color:e.error,fontSize:11,fontFamily:e.font,cursor:"pointer"},children:"Delete"})]})]})}function CS(e,t){if(e==="duckdb")return["filepath"];if(e==="databricks")return["host","httpPath","database","schema","authMethod","token"];if(e!=="snowflake")return[];const n=["account","warehouse","database","schema","username","authMethod"];switch(t.authMethod||"password"){case"key_pair":return[...n,"privateKeyPath","privateKey","privateKeyPassphrase"];case"external_browser":return n;case"oauth":case"programmatic_access_token":return[...n,"token"];case"oauth_authorization_code":return[...n,"oauthClientId","oauthClientSecret"];case"oauth_client_credentials":return[...n,"oauthClientId","oauthClientSecret","oauthTokenRequestUrl"];case"workload_identity":return[...n,"workloadIdentityProvider","token"];case"mfa":return[...n,"password","passcode"];default:return[...n,"password"]}}const da=new Set(["filepath","httpPath","accessUrl"]);function ES({t:e,driver:t,fields:n,onDriverChange:r,onFieldsChange:o,onSave:i,saving:l,saveMessage:a,connectorStatus:d,installing:c,onInstall:f}){const[p,h]=u.useState(!1),g=Fs[t],S=(g==null?void 0:g.fields)??[],x=CS(t,n),b=new Set(x),k=S.filter(v=>b.has(v.key)),C=S.filter(v=>!b.has(v.key)),E=(v,w)=>o({...n,[v]:w});return s.jsxs("div",{style:{border:`1px solid ${e.cellBorder}`,borderRadius:12,background:e.cellBg,padding:18,display:"flex",flexDirection:"column",gap:13,maxWidth:640},children:[s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4,maxWidth:280},children:[s.jsx("span",{style:{fontSize:11,fontWeight:650,color:e.textSecondary,fontFamily:e.font},children:"Warehouse"}),s.jsx("select",{value:t,onChange:v=>r(v.target.value),style:{border:`1px solid ${e.cellBorder}`,background:e.cellBg,borderRadius:8,padding:"8px 9px",fontSize:12.5,fontFamily:e.font,color:e.textPrimary,outline:"none"},children:io.map(({driver:v,label:w})=>s.jsx("option",{value:v,children:w},v))})]}),s.jsx(AS,{t:e,driver:t,label:(g==null?void 0:g.label)??t,status:d,installing:c,onInstall:f}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:k.map(v=>s.jsx(ua,{t:e,field:v,value:n[v.key]??"",onChange:w=>E(v.key,w),fullWidth:da.has(v.key)},v.key))}),C.length>0&&s.jsxs("details",{open:p,onToggle:v=>h(v.target.open),style:{borderTop:`1px solid ${e.headerBorder}`,paddingTop:12},children:[s.jsxs("summary",{style:{cursor:"pointer",listStyle:"none",display:"flex",alignItems:"center",gap:7,fontSize:11.5,fontWeight:650,color:e.textSecondary,fontFamily:e.font},children:[s.jsx("span",{style:{color:e.textMuted,fontSize:10,transform:p?"rotate(90deg)":"none",transition:"transform 0.15s",display:"inline-block"},children:"▶"}),"Advanced options",s.jsxs("span",{style:{fontWeight:400,color:e.textMuted,fontSize:10.5},children:[C.length," more"]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginTop:12},children:C.map(v=>s.jsx(ua,{t:e,field:v,value:n[v.key]??"",onChange:w=>E(v.key,w),fullWidth:da.has(v.key)||v.type==="textarea"},v.key))})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,paddingTop:4,borderTop:`1px solid ${e.headerBorder}`},children:[s.jsx("span",{style:{fontSize:10.5,color:e.textMuted,flex:1,fontFamily:e.font},children:a??"Changes apply after a successful test."}),s.jsx("button",{type:"button",onClick:i,disabled:l,style:{height:30,padding:"0 15px",borderRadius:8,border:"none",background:e.accent,color:"#fff",fontSize:12,fontWeight:650,cursor:l?"not-allowed":"pointer",fontFamily:e.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)",opacity:l?.7:1},children:l?"Saving…":"Save connection"})]})]})}function AS({t:e,driver:t,label:n,status:r,installing:o,onInstall:i}){const l=(r==null?void 0:r.builtIn)??!0,a=(r==null?void 0:r.installed)??!0,d=!a&&!l,c=o||d?e.warning:e.success,f=o||d?"var(--status-warning-bg)":"var(--status-success-bg)",p=o||d?"var(--status-warning-border)":"var(--status-success-border)",h=o?"Installing connector package…":l?"Built in — no installation needed":a?"Connector installed and ready":"Connector package required before you can connect";return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,border:`1px solid ${p}`,borderRadius:9,background:f,padding:"10px 12px"},children:[s.jsx(Dn,{driver:t,size:18,fallbackColor:Tr[t]??e.accent}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{fontSize:12,fontWeight:650,color:e.textPrimary,fontFamily:e.font},children:[n," connector"]}),s.jsx("div",{className:o?"dql-connector-installing":void 0,style:{fontSize:11,color:c,fontFamily:e.font,marginTop:1},children:h})]}),d||o?s.jsx("button",{type:"button",onClick:i,disabled:o,title:r==null?void 0:r.installCommand,style:{flexShrink:0,height:28,padding:"0 12px",borderRadius:8,border:`1px solid ${e.accent}`,background:"var(--accent-dim)",color:e.accent,fontSize:11.5,fontWeight:650,cursor:o?"not-allowed":"pointer",fontFamily:e.font,opacity:o?.75:1},children:o?"Installing…":"Install connector"}):s.jsxs("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",gap:5,fontSize:11,fontWeight:650,color:c,fontFamily:e.font},children:[s.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.4,strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M20 6 9 17l-5-5"})}),l?"Ready":"Installed"]})]})}function ua({t:e,field:t,value:n,onChange:r,fullWidth:o}){const[i,l]=u.useState(!1),d={border:`1px solid ${i?e.accent:e.cellBorder}`,background:e.cellBg,borderRadius:8,padding:"8px 10px",fontSize:12,fontFamily:e.fontMono,color:e.textPrimary,outline:"none",width:"100%",boxSizing:"border-box"},c={display:"flex",flexDirection:"column",gap:4,gridColumn:o?"1 / -1":void 0},f=s.jsxs("span",{style:{fontSize:11,fontWeight:650,color:e.textSecondary,fontFamily:e.font},children:[t.label,t.required?" *":""]});return t.type==="checkbox"?s.jsxs("label",{style:{...c,flexDirection:"row",alignItems:"center",gap:8},children:[s.jsx("input",{type:"checkbox",checked:n==="true",onChange:p=>r(p.target.checked?"true":"false")}),f]}):s.jsxs("label",{style:c,children:[f,t.type==="select"?s.jsxs("select",{value:n,onChange:p=>r(p.target.value),onFocus:()=>l(!0),onBlur:()=>l(!1),style:{...d,fontFamily:e.font,fontSize:12.5,padding:"8px 9px"},children:[s.jsx("option",{value:"",children:"Default"}),(t.options??[]).map(p=>s.jsx("option",{value:p.value,children:p.label},p.value))]}):t.type==="textarea"?s.jsx("textarea",{value:n,placeholder:t.placeholder??"",onChange:p=>r(p.target.value),onFocus:()=>l(!0),onBlur:()=>l(!1),style:{...d,minHeight:72,resize:"vertical"}}):s.jsx("input",{type:t.type==="password"?"password":t.type==="number"?"number":"text",value:n,placeholder:t.placeholder??"",onChange:p=>r(p.target.value),onFocus:()=>l(!0),onBlur:()=>l(!1),style:d}),t.helpText&&s.jsx("span",{style:{fontSize:10,color:e.textMuted,fontFamily:e.font,lineHeight:1.35},children:t.helpText})]})}const TS=Object.freeze(Object.defineProperty({__proto__:null,ConnectionPanel:cd},Symbol.toStringTag,{value:"Module"}));function RS({type:e}){const t=rb[e]??"#8b949e";return s.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:qc[e]??e,children:ob[e]??e.slice(0,4).toUpperCase()})}function _S({value:e,onChange:t,placeholder:n,t:r}){return s.jsx("input",{value:e,onChange:o=>t(o.target.value),placeholder:n,style:{width:"100%",padding:"7px 9px",borderRadius:6,border:`1px solid ${r.headerBorder}`,background:r.sidebarBg,color:r.textPrimary,fontSize:12,outline:"none"}})}function dd({node:e,t,onClick:n,secondary:r}){return s.jsxs("button",{onClick:n,style:{width:"100%",textAlign:"left",background:"transparent",border:"none",borderRadius:6,padding:"6px 8px",cursor:"pointer",color:t.textPrimary},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx(RS,{type:e.type}),s.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},title:e.name,children:e.name})]}),(r||e.domain)&&s.jsx("div",{style:{marginLeft:40,marginTop:2,color:t.textMuted,fontSize:11},children:r??e.domain})]})}const $S=30,_o=200;function Qe(e){const t=e.metadata??{},n=[];return e.domain&&n.push(e.domain),e.type==="term"&&typeof t.termType=="string"&&n.push(t.termType),e.owner&&n.push(e.owner),e.status&&n.push(e.status),e.type==="business_view"&&typeof t.description=="string"&&n.push(t.description),n.length>0?n.join(" · "):void 0}function $o({Icon:e,label:t,value:n,detail:r,t:o}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,border:`1px solid ${o.headerBorder}`,borderRadius:6,padding:"7px 9px",background:o.inputBg,minWidth:0},title:r,children:[s.jsx(e,{size:14,strokeWidth:1.8,color:o.accent,style:{flexShrink:0}}),s.jsx("div",{style:{color:o.textMuted,fontSize:10,fontWeight:800,textTransform:"uppercase",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:t}),s.jsx("div",{style:{marginLeft:"auto",color:o.textPrimary,fontSize:15,fontWeight:800,lineHeight:1,flexShrink:0},children:n})]})}function Ke({title:e,nodes:t,t:n,onSelect:r,secondaryFor:o}){const i=t.length>$S,[l,a]=u.useState(!i),[d,c]=u.useState(_o);if(t.length===0)return null;const f=l?Math.min(d,t.length):0,p=Math.max(0,t.length-f);return s.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[s.jsxs("button",{onClick:()=>a(h=>!h),"aria-expanded":l,style:{width:"100%",display:"flex",alignItems:"center",gap:6,padding:"0 8px 6px",color:n.textMuted,fontSize:11,fontWeight:700,textTransform:"uppercase",background:"transparent",border:"none",cursor:"pointer",textAlign:"left"},children:[s.jsx("span",{style:{display:"inline-block",width:10},children:l?"▾":"▸"}),s.jsx("span",{children:e}),s.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),l&&t.slice(0,f).map(h=>s.jsx(dd,{node:h,t:n,onClick:()=>r(h),secondary:o==null?void 0:o(h)},h.id)),l&&p>0&&s.jsxs("button",{onClick:()=>c(h=>h+_o),style:{width:"100%",margin:"4px 0 0",padding:"6px 8px",background:"transparent",border:"none",color:n.textMuted,fontSize:11,cursor:"pointer",textAlign:"left"},children:["Show ",Math.min(_o,p)," more (",p," hidden)"]})]})}function OS({variant:e="sidebar"}){const{state:t,dispatch:n}=xe(),r=Fe[t.themeMode],o=e==="page",[i,l]=u.useState(()=>typeof window<"u"?window.innerWidth<700:!1),[a,d]=u.useState(!0),[c,f]=u.useState([]),[p,h]=u.useState([]),[g,S]=u.useState(""),[x,b]=u.useState([]),k=u.useCallback(async()=>{d(!0);const y=await N.fetchLineage();f(y.nodes??[]),h(y.edges??[]),d(!1)},[]);u.useEffect(()=>{k()},[k]),u.useEffect(()=>{if(!o)return;const y=()=>l(window.innerWidth<700);return y(),window.addEventListener("resize",y),()=>window.removeEventListener("resize",y)},[o]),u.useEffect(()=>{let y=!1;if(g.trim().length<2){b([]);return}return N.searchLineage(g.trim()).then(M=>{y||b(M.matches??[])}),()=>{y=!0}},[g]);const C=u.useCallback(y=>{n({type:"OPEN_LINEAGE_DETAIL",nodeId:y.id})},[n]),[E,v]=u.useState("type"),w=u.useMemo(()=>({terms:c.filter(y=>y.type==="term"),businessViews:c.filter(y=>y.type==="business_view"),dashboards:c.filter(y=>y.type==="dashboard"),notebooks:c.filter(y=>y.type==="notebook"),apps:c.filter(y=>y.type==="app"),charts:c.filter(y=>y.type==="chart"),blocks:c.filter(y=>y.type==="block"),metrics:c.filter(y=>y.type==="metric"),dimensions:c.filter(y=>y.type==="dimension"),dbtModels:c.filter(y=>y.type==="dbt_model"),dbtSources:c.filter(y=>y.type==="dbt_source"),tables:c.filter(y=>y.type==="source_table"),domains:c.filter(y=>y.type==="domain")}),[c]),A=u.useMemo(()=>({businessNodes:w.terms.length+w.businessViews.length,businessEdges:p.filter(y=>y.type==="defines"||y.type==="composes").length,technicalNodes:w.tables.length+w.dbtSources.length+w.dbtModels.length+w.metrics.length+w.dimensions.length+w.blocks.length,consumptionNodes:w.charts.length+w.notebooks.length+w.dashboards.length+w.apps.length}),[p,w]),R=u.useMemo(()=>{const y={source:[],transform:[],answer:[],consumption:[]};for(const M of c){const $=ab(M);y[$].push(M)}return y},[c]);return a?s.jsx("div",{style:{padding:16,color:r.textMuted,fontSize:12},children:"Loading lineage..."}):c.length===0?s.jsx("div",{style:{height:"100%",background:o?r.sidebarBg:"transparent",border:o?`1px solid ${r.headerBorder}`:"none",borderRadius:o?8:0},children:s.jsx(Nn,{title:"No lineage data",description:"Run `dql compile` or add notebooks/blocks first."})}):s.jsxs("div",{style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column",background:o?r.sidebarBg:"transparent",border:o?`1px solid ${r.headerBorder}`:"none",borderRadius:o?8:0,overflow:"hidden"},children:[s.jsx("div",{style:{padding:"10px 12px 8px",borderBottom:`1px solid ${r.headerBorder}`},children:s.jsx(_S,{value:g,onChange:S,placeholder:"Search lineage...",t:r})}),s.jsxs("div",{style:{flex:1,overflow:"auto"},children:[g.trim().length>=2&&x.length>0&&s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${r.headerBorder}`},children:[s.jsx("div",{style:{color:r.textMuted,fontSize:11,fontWeight:700,textTransform:"uppercase",marginBottom:6},children:"Search Results"}),x.slice(0,8).map(y=>s.jsx(dd,{node:y.node,t:r,onClick:()=>C(y.node),secondary:y.node.domain},y.node.id))]}),s.jsxs("div",{style:{padding:"8px 12px",display:"grid",gridTemplateColumns:o&&!i?"repeat(3, minmax(0, 1fr))":"1fr",gap:6,borderBottom:`1px solid ${r.headerBorder}`},children:[s.jsx($o,{Icon:zg,label:"Business",value:A.businessNodes,detail:`${w.terms.length} terms · ${w.businessViews.length} views · ${A.businessEdges} edges`,t:r}),s.jsx($o,{Icon:tr,label:"Technical",value:A.technicalNodes,detail:`${w.tables.length} tables · ${w.dbtModels.length+w.dbtSources.length} dbt · ${w.blocks.length} blocks`,t:r}),s.jsx($o,{Icon:Wy,label:"Consumption",value:A.consumptionNodes,detail:`${w.dashboards.length} dashboards · ${w.notebooks.length} notebooks · ${w.apps.length} apps`,t:r})]}),s.jsxs("div",{style:{padding:"6px 12px",display:"flex",alignItems:"center",gap:7,flexWrap:"wrap",borderBottom:`1px solid ${r.headerBorder}`},children:[zi.map(y=>{const M=R[y].length;return M===0?null:s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,color:r.textMuted},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:2,background:sb[y],display:"inline-block"}}),Fi[y],": ",M]},y)}),s.jsx("span",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",borderRadius:4,border:`1px solid ${r.headerBorder}`,overflow:"hidden"},children:[s.jsx("button",{onClick:()=>v("type"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",background:E==="type"?`${r.headerBorder}`:"transparent",color:E==="type"?r.textPrimary:r.textMuted},children:"Type"}),s.jsx("button",{onClick:()=>v("layer"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",borderLeft:`1px solid ${r.headerBorder}`,background:E==="layer"?`${r.headerBorder}`:"transparent",color:E==="layer"?r.textPrimary:r.textMuted},children:"Layer"})]})]}),E==="type"?s.jsxs(s.Fragment,{children:[s.jsx(Ke,{title:"Business Terms",nodes:w.terms,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Business Views",nodes:w.businessViews,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"DQL Blocks",nodes:w.blocks,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Metrics",nodes:w.metrics,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Dimensions",nodes:w.dimensions,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Dashboards",nodes:w.dashboards,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Notebooks",nodes:w.notebooks,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Apps",nodes:w.apps,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Charts",nodes:w.charts,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"dbt Models",nodes:w.dbtModels,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"dbt Sources",nodes:w.dbtSources,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Source Tables",nodes:w.tables,t:r,onSelect:C,secondaryFor:Qe}),s.jsx(Ke,{title:"Business Domains",nodes:w.domains,t:r,onSelect:C,secondaryFor:Qe})]}):s.jsx(s.Fragment,{children:zi.map(y=>s.jsx(Ke,{title:Fi[y],nodes:R[y],t:r,onSelect:C},y))})]})]})}function PS({diff:e,diffReport:t,activeFilePath:n,diffPath:r,onScopeToFile:o,onClearScope:i,t:l}){const a=t!==null&&!t.identical,d=e.trim()!=="";return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{display:"flex",gap:6,fontSize:11},children:[s.jsx("button",{onClick:i,style:fa(r==null,l),children:"All"}),n&&s.jsx("button",{onClick:o,style:fa(r===n,l),children:"Active file"}),r&&s.jsx("span",{style:{color:l.textMuted,fontSize:10,alignSelf:"center",fontFamily:l.fontMono},children:r})]}),a&&s.jsx(DS,{report:t,t:l}),!a&&d&&s.jsx(LS,{diff:e,t:l}),!a&&!d&&s.jsx("div",{style:{color:l.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function DS({report:e,t}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>s.jsx(MS,{change:n,t},r))})}function MS({change:e,t}){const{marker:n,color:r,label:o}=NS(e),i="fields"in e?e.fields:null;return s.jsxs("div",{style:{border:`1px solid ${t.editorBorder}`,borderRadius:6,padding:"6px 10px",background:t.editorBg},children:[s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"baseline"},children:[s.jsx("span",{style:{color:r,fontFamily:t.fontMono,fontWeight:700,width:14},children:n}),s.jsx("span",{style:{color:t.textPrimary,fontSize:12,fontFamily:t.fontMono},children:o})]}),i&&i.length>0&&s.jsx("div",{style:{marginTop:4,display:"flex",flexDirection:"column",gap:2},children:i.map((l,a)=>s.jsx(IS,{field:l,t},a))})]})}function IS({field:e,t}){return s.jsxs("div",{style:{fontSize:11,fontFamily:t.fontMono,color:t.textPrimary,paddingLeft:22},children:[s.jsx("span",{style:{color:t.accent},children:e.path}),s.jsx("span",{style:{color:t.textMuted},children:": "}),s.jsx("span",{style:{color:t.error,textDecoration:"line-through"},children:pa(e.before)}),s.jsx("span",{style:{color:t.textMuted},children:" → "}),s.jsx("span",{style:{color:t.success},children:pa(e.after)})]})}function LS({diff:e,t}){return s.jsx("pre",{style:{fontFamily:t.fontMono,fontSize:11,margin:0,padding:8,background:t.editorBg,border:`1px solid ${t.editorBorder}`,borderRadius:6,overflow:"auto",whiteSpace:"pre",color:t.textPrimary},children:e.split(`
481
- `).map((n,r)=>s.jsx("div",{style:{color:BS(n,t)},children:n||" "},r))})}function NS(e){const t={marker:"+",color:"#3cb371"},n={marker:"-",color:"#e06060"},r={marker:"~",color:"#d4a24c"};switch(e.kind){case"block-added":return{...t,label:`block "${e.name}"`};case"block-removed":return{...n,label:`block "${e.name}"`};case"block-changed":return{...r,label:`block "${e.name}"`};case"dashboard-added":return{...t,label:`dashboard "${e.title}"`};case"dashboard-removed":return{...n,label:`dashboard "${e.title}"`};case"dashboard-changed":return{...r,label:`dashboard "${e.title}"`};case"workbook-added":return{...t,label:`workbook "${e.title}"`};case"workbook-removed":return{...n,label:`workbook "${e.title}"`};case"workbook-changed":return{...r,label:`workbook "${e.title}"`};case"cell-added":return{...t,label:`cell ${Oo(e.id,e.name)} [${e.cellType}]`};case"cell-removed":return{...n,label:`cell ${Oo(e.id,e.name)} [${e.cellType}]`};case"cell-changed":return{...r,label:`cell ${Oo(e.id,e.name)}`};case"notebook-changed":return{...r,label:"notebook"}}}function Oo(e,t){return t?`"${t}" (${e.slice(0,8)})`:e.slice(0,8)}function pa(e,t=60){if(e==null)return"∅";const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}function fa(e,t){return{background:e?t.btnHover:"transparent",color:e?t.textPrimary:t.textMuted,border:`1px solid ${t.headerBorder}`,padding:"2px 8px",borderRadius:4,fontSize:11,cursor:"pointer"}}function BS(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const FS=2e3,zS={modified:{label:"Modified",color:e=>e.warning,Icon:my},added:{label:"Added",color:e=>e.success,Icon:Mc},deleted:{label:"Deleted",color:e=>e.error,Icon:wy},renamed:{label:"Renamed",color:e=>e.accent,Icon:$g},untracked:{label:"Untracked",color:e=>e.textMuted,Icon:xy}},ha=["modified","added","renamed","deleted","untracked"];function qS(e){const t=e.trim();return t==="??"?"untracked":t.startsWith("R")?"renamed":t.includes("D")?"deleted":t.includes("A")?"added":"modified"}function US(){var A;const{state:e}=xe(),t=Fe[e.themeMode],[n,r]=u.useState("status"),[o,i]=u.useState(null),[l,a]=u.useState(null),[d,c]=u.useState(""),[f,p]=u.useState(null),[h,g]=u.useState(null),[S,x]=u.useState(!1),[b,k]=u.useState(!1),C=u.useCallback(async()=>{x(!0),k(!0);try{if(n==="status")i(await N.fetchGitStatus());else if(n==="log")a(await N.fetchGitLog(30));else{const R=await N.fetchGitDiff(h??void 0);c(R.diff),p(R.diffReport)}}finally{x(!1),window.setTimeout(()=>k(!1),400)}},[n,h]);u.useEffect(()=>{C()},[C]),u.useEffect(()=>{if(n!=="status")return;const R=window.setInterval(()=>{N.fetchGitStatus().then(y=>{i(M=>WS(M,y)?M:y)})},FS);return()=>window.clearInterval(R)},[n]);const E=((A=e.activeFile)==null?void 0:A.path)??null,v=s.jsxs("button",{onClick:()=>void C(),title:"Refresh","aria-label":"Refresh",style:{background:"transparent",border:`1px solid ${t.btnBorder}`,cursor:"pointer",color:t.textMuted,padding:"3px 6px",borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center"},children:[s.jsx(Ir,{size:12,strokeWidth:1.75,style:{animation:b?"dql-spin 0.6s linear":void 0}}),s.jsx("style",{children:"@keyframes dql-spin { to { transform: rotate(360deg); } }"})]}),w=s.jsxs(_c,{children:[s.jsx(Po,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),s.jsx(Po,{t,active:n==="log",onClick:()=>r("log"),children:"History"}),s.jsx(Po,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"})]});return s.jsxs(Ts,{title:"Git",actions:v,toolbar:w,bodyPadding:12,children:[S&&!o&&!l&&s.jsx(Nn,{title:"Loading…"}),n==="status"&&o&&s.jsx(KS,{status:o,t}),n==="log"&&l&&s.jsx(QS,{log:l,t}),n==="diff"&&s.jsx(PS,{diff:d,diffReport:f,activeFilePath:E,diffPath:h,onScopeToFile:()=>g(E),onClearScope:()=>g(null),t})]})}function WS(e,t){if(!e||e.inRepo!==t.inRepo||e.branch!==t.branch||e.ahead!==t.ahead||e.behind!==t.behind||e.changes.length!==t.changes.length)return!1;const n=e.changes.map(o=>`${o.path}\0${o.status}`).sort(),r=t.changes.map(o=>`${o.path}\0${o.status}`).sort();for(let o=0;o<n.length;o++)if(n[o]!==r[o])return!1;return!0}function KS({status:e,t}){const n=u.useMemo(()=>{const r={modified:[],added:[],deleted:[],renamed:[],untracked:[]};for(const o of e.changes)r[qS(o.status)].push(o);for(const o of ha)r[o].sort((i,l)=>i.path.localeCompare(l.path));return r},[e.changes]);return e.inRepo?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[s.jsx(VS,{status:e,t}),e.changes.length===0?s.jsx(HS,{t}):ha.map(r=>{const o=n[r];return o.length===0?null:s.jsx(GS,{group:r,items:o,t},r)})]}):s.jsx(ud,{t})}function VS({status:e,t}){const n=e.ahead??0,r=e.behind??0;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderLeft:`3px solid ${t.accent}`,borderRadius:7},children:[s.jsx(Sn,{size:16,strokeWidth:1.75,color:t.accent}),s.jsx("span",{style:{fontSize:13,fontWeight:600,color:t.textPrimary,fontFamily:t.fontMono},children:e.branch??"detached"}),s.jsx("div",{style:{flex:1}}),n>0&&s.jsxs("span",{title:`${n} commit(s) ahead of upstream`,style:Do(t.success,t),children:[s.jsx(Pg,{size:11,strokeWidth:2})," ",n]}),r>0&&s.jsxs("span",{title:`${r} commit(s) behind upstream`,style:Do(t.warning,t),children:[s.jsx(Rg,{size:11,strokeWidth:2})," ",r]}),n===0&&r===0&&s.jsx("span",{style:{...Do(t.textMuted,t),opacity:.7},children:"up to date"})]})}function HS({t:e}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"14px 12px",background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderRadius:7,color:e.textMuted,fontSize:12,fontFamily:e.font},children:[s.jsx(fy,{size:14,strokeWidth:1.75,color:e.success}),"Working tree clean"]})}function ud({t:e}){return s.jsx("div",{style:{padding:"14px 12px",background:e.cellBg,border:`1px solid ${e.cellBorder}`,borderRadius:7,color:e.textMuted,fontSize:12,fontFamily:e.font},children:"Not a git repository"})}function GS({group:e,items:t,t:n}){const r=zS[e],o=r.color(n),i=r.Icon;return s.jsxs("div",{children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:n.textMuted,fontFamily:n.font},children:[s.jsx(i,{size:11,strokeWidth:1.75}),s.jsx("span",{children:r.label}),s.jsx("span",{style:{marginLeft:2,padding:"0 5px",borderRadius:8,background:`${o}1a`,color:o,fontWeight:700,fontSize:9,letterSpacing:"0.04em"},children:t.length})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",background:n.cellBg,border:`1px solid ${n.cellBorder}`,borderRadius:7,overflow:"hidden"},children:t.map((l,a)=>s.jsx(JS,{change:l,t:n,color:o,divider:a<t.length-1},l.path))})]})}function JS({change:e,t,color:n,divider:r}){const o=e.status.trim()||"??";return s.jsxs("div",{title:e.path,style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",borderBottom:r?`1px solid ${t.cellBorder}`:"none",fontFamily:t.fontMono,fontSize:11},children:[s.jsx("span",{style:{width:22,textAlign:"center",flexShrink:0,color:n,fontWeight:700,fontSize:10,letterSpacing:"0.02em"},children:o}),s.jsx("span",{style:{color:t.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:e.path})]})}function QS({log:e,t}){return e.inRepo?e.commits.length===0?s.jsx("div",{style:{padding:"14px 12px",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,color:t.textMuted,fontSize:12,fontFamily:t.font},children:"No commits yet"}):s.jsx("div",{style:{display:"flex",flexDirection:"column",background:t.cellBg,border:`1px solid ${t.cellBorder}`,borderRadius:7,overflow:"hidden"},children:e.commits.map((n,r)=>s.jsxs("div",{style:{display:"flex",gap:10,padding:"8px 12px",borderBottom:r<e.commits.length-1?`1px solid ${t.cellBorder}`:"none"},children:[s.jsx(Dy,{size:13,strokeWidth:1.75,color:t.accent,style:{flexShrink:0,marginTop:2}}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{color:t.textPrimary,fontSize:12,fontFamily:t.font,fontWeight:500,lineHeight:1.35,wordBreak:"break-word"},children:n.subject}),s.jsxs("div",{style:{color:t.textMuted,fontSize:10,marginTop:3,display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[s.jsx("span",{style:{fontFamily:t.fontMono,color:t.accent},children:n.hash.slice(0,7)}),s.jsx("span",{children:"·"}),s.jsx("span",{style:{fontFamily:t.font},children:n.author}),s.jsx("span",{children:"·"}),s.jsx("span",{style:{fontFamily:t.fontMono},children:n.date})]})]})]},n.hash))}):s.jsx(ud,{t})}function Po({active:e,onClick:t,children:n,t:r}){return s.jsx("button",{onClick:t,style:{background:e?r.btnHover:"transparent",color:e?r.textPrimary:r.textMuted,border:"none",padding:"4px 12px",borderRadius:4,fontSize:11,fontWeight:600,letterSpacing:"0.02em",cursor:"pointer",fontFamily:r.font,transition:"background 0.15s, color 0.15s"},children:n})}function Do(e,t){return{display:"inline-flex",alignItems:"center",gap:3,padding:"1px 7px",fontSize:10,fontWeight:600,letterSpacing:"0.02em",borderRadius:10,background:`${e}1a`,color:e,fontFamily:t.font}}function YS(e){const{state:t,dispatch:n}=xe(),r=Fe[t.themeMode],[o,i]=u.useState([]),[l,a]=u.useState(!0),[d,c]=u.useState(""),[f,p]=u.useState(""),[h,g]=u.useState(new Set),S=()=>{a(!0),N.listApps().then(A=>i(A)).finally(()=>a(!1))};u.useEffect(()=>{S()},[]);const x=[...new Set(o.map(A=>A.domain))].sort(),b=o.filter(A=>{const R=d.toLowerCase();return!(R&&!A.name.toLowerCase().includes(R)&&!(A.description??"").toLowerCase().includes(R)||f&&A.domain!==f)}),k=A=>{g(R=>{const y=new Set(R);return y.has(A)?y.delete(A):y.add(A),y})},C=(A,R)=>{n({type:"OPEN_APP",appId:A.id,dashboardId:R})},E={background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.font,padding:"4px 6px",outline:"none"},v=s.jsx("button",{onClick:S,style:{background:"transparent",border:`1px solid ${r.cellBorder}`,borderRadius:4,color:r.textSecondary,cursor:"pointer",fontSize:10,fontFamily:r.font,padding:"3px 8px"},children:"Refresh"}),w=s.jsxs(_c,{children:[s.jsx("input",{value:d,onChange:A=>c(A.target.value),placeholder:"Search apps...",style:{...E,flex:1,minWidth:100}}),s.jsxs("select",{value:f,onChange:A=>p(A.target.value),style:E,children:[s.jsx("option",{value:"",children:"All domains"}),x.map(A=>s.jsx("option",{value:A,children:A},A))]})]});return s.jsx(Ts,{title:"Apps",status:s.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:b.length}),actions:v,toolbar:w,bodyPadding:0,children:l?s.jsx(Nn,{title:"Loading apps…"}):b.length===0?o.length===0?s.jsx(Nn,{title:"No apps yet",description:s.jsxs(s.Fragment,{children:["Create one from the CLI:",s.jsx("br",{}),s.jsx("code",{style:{display:"inline-block",marginTop:6,padding:"2px 6px",background:r.inputBg,borderRadius:3,fontSize:10},children:"dql app new <name> --domain <domain>"})]})}):s.jsx(Nn,{title:"No matches",description:"No apps match your filters."}):b.map(A=>{const R=h.has(A.id);return s.jsxs("div",{style:{borderBottom:`1px solid ${r.cellBorder}`},children:[s.jsxs("button",{onClick:()=>k(A.id),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:y=>{y.currentTarget.style.background=`${r.accent}0a`},onMouseLeave:y=>{y.currentTarget.style.background="transparent"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[s.jsx("span",{style:{fontSize:10,color:r.textMuted,fontFamily:r.font,width:10},children:R?"▾":"▸"}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:r.textPrimary,fontFamily:r.font},children:A.name}),s.jsx(Rc,{tone:"accent",children:A.domain})]}),A.description&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,lineHeight:1.3,marginBottom:4,marginLeft:16},children:A.description}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:r.textMuted,fontFamily:r.font,marginLeft:16},children:[A.owners[0]&&s.jsxs("span",{children:["by ",A.owners[0]]}),s.jsxs("span",{children:[A.dashboards.length," dashboard",A.dashboards.length===1?"":"s"]}),s.jsxs("span",{children:[A.members," member",A.members===1?"":"s"]})]})]}),R&&s.jsxs("div",{style:{padding:"4px 0 10px 28px",background:`${r.accent}04`},children:[A.dashboards.length===0&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 0"},children:"(empty app scaffold)"}),A.dashboards.map(y=>s.jsx("button",{onClick:()=>C(A,y.id),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",padding:"3px 12px",cursor:"pointer",fontSize:11,color:r.textSecondary,fontFamily:r.font},children:y.title},y.id))]})]},A.id)})})}const XS={files:"Build",block_library:"Build",lineage:"Lineage",connection:"Connection",git:"Git",apps:"Apps"};function ZS({onOpenFile:e}){const{state:t,dispatch:n}=xe(),r=Fe[t.themeMode],[o,i]=u.useState(!1),[l,a]=u.useState(340),[d,c]=u.useState(!1),[f,p]=u.useState(""),h=u.useRef(l),g=t.sidebarPanel,S=g==="files"||g==="block_library",x=t.semanticLayer.loading?"Loading semantic metrics…":`${t.semanticLayer.provider?`${t.semanticLayer.provider} synced`:"dbt synced"} · ${t.schemaTables.length} table${t.schemaTables.length===1?"":"s"} · ${t.semanticLayer.metrics.length.toLocaleString()} metric${t.semanticLayer.metrics.length===1?"":"s"}`;u.useEffect(()=>{if(!S)return;let k=!0;return n({type:"SET_SEMANTIC_LOADING",loading:!0}),N.getSemanticLayer().then(C=>{k&&n({type:"SET_SEMANTIC_LAYER",layer:C})}).catch(()=>{}).finally(()=>{k&&n({type:"SET_SEMANTIC_LOADING",loading:!1})}),()=>{k=!1}},[S,n]);const b=k=>{k.preventDefault();const C=k.clientX,E=h.current;c(!0);const v=A=>{const R=Math.min(560,Math.max(180,E+(A.clientX-C)));h.current=R,a(R)},w=()=>{c(!1),window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",w)};window.addEventListener("mousemove",v),window.addEventListener("mouseup",w)};return s.jsxs("div",{style:{width:l,flexShrink:0,background:r.sidebarBg,borderRight:`1px solid ${r.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden",position:"relative"},children:[s.jsxs("div",{style:{height:36,flexShrink:0,display:S?"none":"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px 0 14px",borderBottom:`1px solid ${r.headerBorder}`},children:[s.jsx("span",{style:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:r.textSecondary,fontFamily:r.font},children:XS[g??""]??""}),s.jsx("button",{title:"Collapse sidebar",onClick:()=>n({type:"TOGGLE_SIDEBAR"}),onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",border:"none",cursor:"pointer",color:o?r.textPrimary:r.textMuted,padding:"2px 4px",borderRadius:4,fontSize:14,lineHeight:1,transition:"color 0.15s",display:"flex",alignItems:"center"},children:"‹"})]}),s.jsxs("div",{style:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:[S&&s.jsx(Rv,{defaultTab:g==="block_library"?"blocks":"notebooks",tabs:["notebooks","semantic","database","blocks"],onOpenFile:e,blockDomain:f,onBlockDomainChange:p,onNewBlock:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),onCollapse:()=>n({type:"TOGGLE_SIDEBAR"}),footer:x,footerStatus:t.semanticLayer.loading?"loading":"ready"}),g==="lineage"&&s.jsx(OS,{}),g==="connection"&&s.jsx(cd,{}),g==="git"&&s.jsx(US,{}),g==="apps"&&s.jsx(YS,{onOpenFile:e})]}),s.jsx("div",{onMouseDown:b,title:"Drag to resize",style:{position:"absolute",top:0,right:-3,width:6,height:"100%",cursor:"col-resize",background:d?r.accent:"transparent",zIndex:10,transition:d?"none":"background 0.15s"},onMouseEnter:k=>{d||(k.currentTarget.style.background=`${r.accent}40`)},onMouseLeave:k=>{d||(k.currentTarget.style.background="transparent")}})]})}const pd=2;function e0(e,t={}){const n=t.version??pd,r=JSON.parse(e),{dqlnbVersion:o,...i}=r,l={dqlnbVersion:n,...i};return JSON.stringify(l,t0(),2)+`
482
- `}function t0(){return function(t,n){if(n===null||typeof n!="object"||Array.isArray(n))return n;const r=n,o=Object.keys(r);o.sort((l,a)=>{const d=ma[l],c=ma[a];return d!==void 0&&c!==void 0?d-c:d!==void 0?-1:c!==void 0?1:l<a?-1:l>a?1:0});const i={};for(const l of o)i[l]=r[l];return i}}const ma={dqlnbVersion:0,version:1,title:2,metadata:3,cells:4,id:10,type:11,name:12,content:13};function n0(e){try{const t=e.match(/workbook\s+"([^"]+)"/i),n=t?t[1]:"Untitled Workbook",r=[],o=/page\s+"([^"]+)"\s*\{([\s\S]*?)\}/gi;let i;for(;(i=o.exec(e))!==null;){const l=i[1],a=i[2].trim();r.push({id:tt(),type:"markdown",content:`# ${l}`,status:"idle"}),a&&r.push({id:tt(),type:"dql",name:l.toLowerCase().replace(/\s+/g,"_"),content:a,status:"idle"})}return r.length===0&&r.push({id:tt(),type:"dql",content:e.trim(),status:"idle"}),{title:n,cells:r}}catch(t){return console.warn("parse-workbook: falling back after error",t),{title:"Untitled Workbook",cells:[{id:tt(),type:"dql",content:e.trim(),status:"idle"}]}}}const r0=new Set(["id","type","content","source","name","title","paramConfig","paramValue","chartConfig","filterConfig","pivotConfig","singleValueConfig","tableConfig","chatConfig","upstream","blockBinding","dqlParameterValues","dqlArtifact","correctionProvenance","executionTarget","datasetRefs","dependencies","annotations","mixedSourcePlan","kernel"]);function o0(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",o=Vo((n.cells||[]).map(a=>{const d=Object.fromEntries(Object.entries(a).filter(([c])=>!r0.has(c)));return{id:a.id||tt(),type:a.type||"sql",content:a.content??a.source??"",name:a.name||a.title,status:"idle",...a.paramConfig?{paramConfig:a.paramConfig}:{},...a.paramValue!==void 0?{paramValue:a.paramValue}:{},...a.chartConfig?{chartConfig:a.chartConfig}:{},...a.filterConfig?{filterConfig:a.filterConfig}:{},...a.pivotConfig?{pivotConfig:a.pivotConfig}:{},...a.singleValueConfig?{singleValueConfig:a.singleValueConfig}:{},...a.tableConfig?{tableConfig:a.tableConfig}:{},...a.chatConfig?{chatConfig:a.chatConfig}:{},...a.upstream?{upstream:a.upstream}:{},...a.blockBinding?{blockBinding:a.blockBinding}:{},...a.dqlParameterValues?{dqlParameterValues:a.dqlParameterValues}:{},...a.dqlArtifact?{dqlArtifact:a.dqlArtifact}:{},...a.correctionProvenance?{correctionProvenance:a.correctionProvenance}:{},...a.executionTarget?{executionTarget:a.executionTarget}:{},...a.datasetRefs?{datasetRefs:a.datasetRefs}:{},...a.dependencies?{dependencies:a.dependencies}:{},...a.annotations?{annotations:a.annotations}:{},...a.mixedSourcePlan?{mixedSourcePlan:a.mixedSourcePlan}:{},...a.kernel?{kernel:a.kernel}:{},...Object.keys(d).length>0?{preservedFields:d}:{}}})),{title:i,...l}=n.metadata??{};return{title:r,cells:o,metadata:l}}catch(n){return console.warn("parse-workbook: falling back after error",n),{title:"Untitled",cells:[{id:tt(),type:"sql",content:e,status:"idle"}]}}}function s0(e,t,n){const r={dqlnbVersion:pd,version:1,title:e,metadata:{...n,modifiedAt:new Date().toISOString(),...n!=null&&n.createdAt?{}:{createdAt:new Date().toISOString()}},cells:t.map(o=>({...o.preservedFields??{},id:o.id,type:o.type,content:o.content,...o.name?{name:o.name}:{},...o.paramConfig?{paramConfig:o.paramConfig}:{},...o.paramValue!==void 0?{paramValue:o.paramValue}:{},...o.chartConfig?{chartConfig:o.chartConfig}:{},...o.filterConfig?{filterConfig:o.filterConfig}:{},...o.pivotConfig?{pivotConfig:o.pivotConfig}:{},...o.singleValueConfig?{singleValueConfig:o.singleValueConfig}:{},...o.tableConfig?{tableConfig:o.tableConfig}:{},...o.chatConfig?{chatConfig:o.chatConfig}:{},...o.upstream?{upstream:o.upstream}:{},...o.blockBinding?{blockBinding:o.blockBinding}:{},...o.dqlParameterValues?{dqlParameterValues:o.dqlParameterValues}:{},...o.dqlArtifact?{dqlArtifact:o.dqlArtifact}:{},...o.correctionProvenance?{correctionProvenance:o.correctionProvenance}:{},...o.executionTarget?{executionTarget:o.executionTarget}:{},...o.datasetRefs?{datasetRefs:o.datasetRefs}:{},...o.dependencies?{dependencies:o.dependencies}:{},...o.annotations?{annotations:o.annotations}:{},...o.mixedSourcePlan?{mixedSourcePlan:o.mixedSourcePlan}:{},...o.kernel?{kernel:o.kernel}:{}}))};return e0(JSON.stringify(r))}function i0(e,t){return e.endsWith(".dql")?n0(t):o0(t)}const fd=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function U1(e){const t=new Set;for(const n of e.matchAll(fd))t.add(n[1]);return[...t]}function a0(e,t){if(!t.columns.length||!t.rows.length)return`${e} AS (SELECT 1 WHERE 1=0)`;const n=t.columns,o=t.rows.slice(0,5e3).map(l=>`(${n.map(d=>{const c=l[d];return c==null?"NULL":typeof c=="number"?String(c):typeof c=="boolean"?c?"TRUE":"FALSE":`'${String(c).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
483
- `),i=n.map(l=>`"${l.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
484
- SELECT * FROM (VALUES
485
- ${o}
486
- ) AS _t(${i})
487
- )`}function l0(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function c0(e,t){var c;const n=[...e.matchAll(fd)];if(n.length===0)return{sql:e,substituted:[],unresolved:[],ambiguous:[]};const r=new Map;for(const f of t){const p=[f.id,(c=f.name)==null?void 0:c.trim()].filter(h=>!!h);for(const h of p)r.set(h,[...r.get(h)??[],f])}const o=[],i=[],l=[],a=[];let d=e;for(const f of n){const p=f[1],h=r.get(p)??[];if(h.length===0){i.push(p);continue}if(h.length>1){l.push(p);continue}const g=h[0];if(g.type==="param"){const S=g.paramConfig,x=g.paramValue??(S==null?void 0:S.defaultValue)??"",b=(S==null?void 0:S.paramType)??"text";d=d.replace(f[0],l0(x,b)),o.push(p);continue}if(!g.result||g.error||g.stale){i.push(p);continue}a.push(a0(p,g.result)),d=d.replace(f[0],`"${p}"`),o.push(p)}if(a.length>0){const f=d.trimStart();/^WITH\s+/i.test(f)?d=d.replace(/^(\s*WITH\s+)/i,`$1${a.join(`,
488
- `)},
489
- `):d=`WITH ${a.join(`,
490
- `)}
491
- ${d}`}return{sql:d,substituted:Array.from(new Set(o)),unresolved:Array.from(new Set(i)),ambiguous:Array.from(new Set(l))}}function hd(e){const t=i=>{var l;return((l=e.match(new RegExp(`\\b${i}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:l[1])??""},n=i=>{const l=e.match(new RegExp(`\\b${i}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i"));return((l==null?void 0:l[1].match(/"([^"]*)"/g))??[]).map(a=>a.slice(1,-1)).filter(Boolean)},r=n("metrics"),o=t("metric");return{metrics:r.length>0?r:o?[o]:[],dimensions:n("dimensions"),requestedFilters:n("requested_filters"),timeDimension:t("time_dimension"),granularity:t("granularity")}}function W1(e,t){let n=e.replace(/\n\s*metrics\s*=\s*\[[\s\S]*?\]/i,"").replace(/\n\s*metric\s*=\s*"[^"]*"/i,"");const r=Array.from(new Set(t.filter(Boolean)));return qs(n,` metrics = [${r.map(o=>`"${Pt(o)}"`).join(", ")}]`)}function md(e,t,n){const r=Array.from(new Set(n.filter(Boolean))),o=`${t} = [${r.map(l=>`"${Pt(l)}"`).join(", ")}]`,i=new RegExp(`\\b${t}\\s*=\\s*\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,o):qs(e,` ${o}`)}function gd(e){const t=ya(e,"parameterPolicy"),n=ya(e,"filterBindings"),r=new Set(Array.from(e.matchAll(/\$\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/g)).map(l=>l[1])),o=/\btype\s*=\s*"semantic"/i.test(e);return zs(e,"params").split(/\r?\n/).flatMap(l=>{const a=l.trim();if(!a||a.startsWith("//")||a.startsWith("#"))return[];const d=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(string|number|boolean|date)(\[\])?)?\s*(?:=\s*(.+))?$/.exec(a);if(!d)return[];const c=d[1],f=d[4]===void 0?void 0:Sd(d[4]),p=d[2]?`${d[2]}${d[3]??""}`:d0(kd(f),c),h=n.get(c),g=r.has(c)?{kind:"sql_value"}:c==="top_n"||c==="limit"?{kind:"limit"}:o&&h?{kind:"semantic_filter",field:h,operator:c.endsWith("_set")?"in":"equals"}:void 0;return[{name:c,type:p,required:d[4]===void 0,...d[4]===void 0?{}:{default:f},policy:p0(t.get(c)),...g?{binding:g}:{}}]})}function d0(e,t=""){const n=e.trim(),r=t.toLowerCase();if(n.includes(",")){const o=n.split(",").map(i=>i.trim()).filter(Boolean);return o.length>0&&o.every(i=>ga(i))?"date[]":o.length>0&&o.every(i=>zr(i))?"number[]":"string[]"}return n==="true"||n==="false"?"boolean":ga(n)?"date":zr(n)?"number":/\b(date|from|start|end|until)\b|(?:^|_)(date|at)(?:_|$)/.test(r)?"date":/(?:^|_)(top_n|limit|count|rank|number)(?:_|$)|_n$/.test(r)?"number":/(?:_set|_list|_ids|_values)$/.test(r)?"string[]":"string"}function yd(e){return e.default===void 0?"":kd(e.default)}function K1(e){if(/^\s*block\s+"/i.test(e))return e;const t=e.trim();return`block "notebook_query" {
492
- status = "draft"
493
- domain = "uncategorized"
494
- type = "custom"
495
- description = "Notebook analysis"
496
-
497
- query = """
498
- ${t?t.split(/\r?\n/).map(r=>` ${r}`).join(`
499
- `):" -- Write query"}
500
- """
501
- }
502
- `}function V1(e,t){const n=vd(t.name);if(!n)return e;const r=gd(e).filter(o=>o.name!==t.previousName&&o.name!==n).map(o=>({name:o.name,type:o.type,required:o.required,defaultText:yd(o),policy:o.policy}));return r.push({name:n,type:t.type,required:t.required,defaultText:t.defaultText??"",policy:t.policy}),xd(e,r)}function H1(e,t){const n=gd(e).filter(r=>r.name!==t).map(r=>({name:r.name,type:r.type,required:r.required,defaultText:yd(r),policy:r.policy}));return xd(e,n)}function G1(e,t,n){const r=vd(t),o=n.trim();if(!r||!o)return e;const l=zs(e,"filterBindings").split(/\r?\n/).filter(a=>a.trim()&&!new RegExp(`^${r}\\s*=`).test(a.trim()));return l.push(`${r} = "${Pt(o)}"`),qr(e,"filterBindings",l.join(`
503
- `))}function xd(e,t){const n=t.map(i=>{const l=`${i.name}: ${i.type}`;return i.required?l:`${l} = ${bd(i.defaultText,i.type)}`}).join(`
504
- `),r=t.map(i=>`${i.name} = "${i.policy}"`).join(`
505
- `);let o=qr(e,"params",n);return o=qr(o,"parameterPolicy",r),o}function bd(e,t){const n=e.trim();if(t==="boolean")return n==="true"?"true":"false";if(t==="number")return zr(n)?String(Number(n)):"0";if(t.endsWith("[]")){const r=t.slice(0,-2);return`[${n.split(",").map(i=>i.trim()).filter(Boolean).map(i=>bd(i,r)).join(", ")}]`}return`"${Pt(n)}"`}function vd(e){const t=e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return/^[a-z_][a-z0-9_]*$/.test(t)?t:""}function zr(e){return e!==""&&Number.isFinite(Number(e))}function ga(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)}function zs(e,t){const n=new RegExp(`\\b${t}\\s*\\{`,"i").exec(e);if(!n||n.index===void 0)return"";const r=e.indexOf("{",n.index);let o=0;for(let i=r;i<e.length;i+=1)if(e[i]==="{"&&(o+=1),e[i]==="}"&&(o-=1,o===0))return e.slice(r+1,i).trim();return""}function ya(e,t){const n=new Map;for(const r of zs(e,t).split(/\r?\n/)){const o=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"([^"]*)"\s*$/.exec(r);o&&n.set(o[1],o[2])}return n}function Sd(e){const t=e.trim();return t==="true"?!0:t==="false"?!1:zr(t)?Number(t):t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.startsWith("[")&&t.endsWith("]")?u0(t.slice(1,-1)).map(Sd):t}function u0(e){const t=[];let n=!1,r="";for(let o=0;o<e.length;o+=1){const i=e[o];i==='"'&&e[o-1]!=="\\"&&(n=!n),i===","&&!n?(r.trim()&&t.push(r.trim()),r=""):r+=i}return r.trim()&&t.push(r.trim()),t}function kd(e){return Array.isArray(e)?e.join(", "):String(e??"")}function p0(e){return e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:"dynamic"}function f0(e,t){const n=new Set(hd(e).requestedFilters),r=Array.from(new Set(t.filter(Boolean)));let o=md(e,"requested_filters",r);return o=Mo(o,"params",n,r,i=>`${i}: string`),o=Mo(o,"parameterPolicy",n,r,i=>`${i} = "dynamic"`),o=Mo(o,"filterBindings",n,r,i=>`${i} = "${Pt(i)}"`),o}function Mo(e,t,n,r,o){const a=[...b0(e,t).split(/\r?\n/).filter(d=>{var f;const c=(f=d.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::|=)/))==null?void 0:f[1];return!c||!n.has(c)}).filter(d=>d.trim()),...r.map(o)].join(`
506
- `);return qr(e,t,a)}function xa(e,t,n){const r=Pt(n),o=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return o.test(e)?e.replace(o,`$1"${r}"`):qs(e,` ${t} = "${r}"`)}function J1(e,t){const n=new Set(t.filter(Boolean)),r=hd(e);let o=md(e,"dimensions",r.dimensions.filter(i=>n.has(i)));return o=f0(o,r.requestedFilters.filter(i=>n.has(i))),r.timeDimension&&!n.has(r.timeDimension)&&(o=xa(o,"time_dimension",""),o=xa(o,"granularity","")),o}function Pt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function qs(e,t){return/visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
507
- ${t}
508
-
509
- visualization {`):e.replace(/\n\}\s*$/,`
510
- ${t}
511
- }
512
- `)}function h0(e){var i;const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=l=>{var a;return(a=n.match(new RegExp(`\\b${l}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:a[1]},o=r("chart");if(o)return{chart:o,x:r("x"),y:r("y"),color:r("color"),title:(i=n.match(/\btitle\s*=\s*"([^"]+)"/i))==null?void 0:i[1]}}function m0(e){const t=e.trim();if(!t)return null;const n=t.match(/query\s*=\s*"""([\s\S]*?)"""/i);if(n)return n[1].trim()||null;const r=t.match(/"""([\s\S]*?)"""/);if(r)return r[1].trim()||null;if(/^\s*(dashboard|workbook)\s+"/i.test(t))return null;const o=t.match(/\b(SELECT|WITH|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|SHOW|DESCRIBE|EXPLAIN)\b([\s\S]*)/i);if(o){let i=o[0];const l=i.search(/\b(visualization|tests|block)\s*\{/i);return l>0&&(i=i.slice(0,l)),i=g0(i),i.trim()||null}return null}function g0(e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];if(r==="("){t++;continue}if(r===")"){t>0&&t--;continue}if(r==="'"||r==='"'){for(n++;n<e.length&&e[n]!==r;)e[n]==="\\"&&n++,n++;continue}if(r===","&&t===0){let o=n+1;for(;o<e.length&&/\s/.test(e[o]);)o++;if(o<e.length&&/[a-zA-Z_]/.test(e[o])){for(;o<e.length&&/[a-zA-Z0-9_]/.test(e[o]);)o++;let i=o;for(;i<e.length&&/\s/.test(e[i]);)i++;if(i<e.length&&e[i]==="="&&e[i+1]!=="=")return e.slice(0,n)}}}return e}function Q1(e){const t=Us(e);return t?{name:t.name,domain:t.domain,owner:t.owner,description:t.description,blockType:t.blockType,status:t.status,tags:t.tags,llmContext:t.llmContext}:null}function y0(e,t,n){const r=n.replace(/"/g,'\\"'),o=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return o.test(e)?e.replace(o,`$1"${r}"`):kn(e,` ${t} = "${r}"`)}function x0(e,t){const n=t.replace(/"/g,'\\"');return/^\s*block\s+"/i.test(e)?e.replace(/^(\s*block\s+)"[^"]+"/i,`$1"${n}"`):e}function Y1(e,t){const n=t.map(o=>`"${o.replace(/"/g,'\\"')}"`).join(", "),r=/(\btags\s*=\s*)\[[^\]]*\]/i;return r.test(e)?e.replace(r,`$1[${n}]`):kn(e,` tags = [${n}]`)}function X1(e,t,n){const r=Array.from(new Set(n.map(l=>l.trim()).filter(Boolean))),o=`${t} = [${r.map(l=>`"${Pt(l)}"`).join(", ")}]`,i=new RegExp(`(\\b${t}\\s*=\\s*)\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,`$1[${r.map(l=>`"${Pt(l)}"`).join(", ")}]`):kn(e,` ${o}`)}function Z1(e,t){const n=/visualization\s*\{[\s\S]*?\n\s*\}/i;if(!n.test(e)){const r=S0(t);return kn(e,` ${r.replace(/\n/g,`
513
- `)}`,!0)}return e.replace(n,r=>{let o=r;for(const[i,l]of Object.entries(t)){if(l==null||l==="")continue;const a=String(l).replace(/"/g,'\\"'),d=new RegExp(`(\\b${i}\\s*=\\s*)"[^"]*"`,"i");d.test(o)?o=o.replace(d,`$1"${a}"`):o=o.replace(/\n(\s*)\}$/,`
514
- $1 ${i} = "${a}"
515
- $1}`)}return o})}function b0(e,t){var r;const n=e.match(new RegExp(`\\b${t}\\s*\\{([\\s\\S]*?)\\n\\s*\\}`,"i"));return((r=n==null?void 0:n[1])==null?void 0:r.split(/\r?\n/).map(o=>o.replace(/^\s{4}/,"")).join(`
516
- `).trim())??""}function qr(e,t,n){const r=n.trim(),o=r?` ${t} {
517
- ${r.split(/\r?\n/).map(l=>` ${l.trimEnd()}`).join(`
518
- `)}
519
- }`:"",i=new RegExp(`\\n\\s*${t}\\s*\\{[\\s\\S]*?\\n\\s*\\}`,"i");return i.test(e)?e.replace(i,o?`
520
- ${o}`:""):o?/\n\s*visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
521
- ${o}
522
-
523
- visualization {`):kn(e,o,!0):e}function ek(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function tk(e,t){const n=Us(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
524
- ${t}
525
- `;const r=n.query.trimEnd(),o=r?`${r}
526
- ${t}`:t;return v0(e,o)}function v0(e,t){if(!Us(e))return e;const r=y0(e,"type","custom"),o=` query = """
527
- ${t.trimEnd()}
528
- """`,i=/\n\s*query\s*=\s*"""[\s\S]*?"""/i;return i.test(r)?r.replace(i,`
529
- ${o}`):kn(r,o,!0)}function Us(e){var i,l;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=a=>{var d;return((d=e.match(new RegExp(`\\b${a}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:d[1])??""},n=((i=e.match(/^\s*block\s+"([^"]+)"/i))==null?void 0:i[1])??"",r=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),o=e.match(/query\s*=\s*"""([\s\S]*?)"""/i);return{name:n,domain:t("domain"),owner:t("owner"),description:t("description"),llmContext:t("llmContext"),status:t("status")||"draft",blockType:(t("type")||"custom").toLowerCase()==="semantic"?"semantic":"custom",tags:r?(r[1].match(/"([^"]*)"/g)??[]).map(a=>a.slice(1,-1)):[],metric:t("metric"),metrics:Tn(e,"metrics"),dimensions:Tn(e,"dimensions"),requestedFilters:Tn(e,"requested_filters"),sourceDqlKind:t("source_dql_kind"),sourceDqlName:t("source_dql_name"),sourceDqlPath:t("source_dql_path"),sourceDqlHash:t("source_dql_hash"),sourceDqlMetrics:Tn(e,"source_dql_metrics"),sourceDqlDimensions:Tn(e,"source_dql_dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((l=o==null?void 0:o[1])==null?void 0:l.trim())??"",visualization:ba(e,"visualization"),tests:ba(e,"tests")}}function Tn(e,t){const n=e.match(new RegExp(`\\b${t}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i"));return n?(n[1].match(/"([^"]*)"/g)??[]).map(r=>r.slice(1,-1)).filter(Boolean):[]}function ba(e,t){const n=new RegExp(`\\b${t}\\s*\\{`,"i").exec(e);if(!n||n.index==null)return"";let r=0,o=-1;for(let i=n.index;i<e.length;i++){const l=e[i];if(l==="{")r===0&&(o=i),r++;else if(l==="}"&&(r--,r===0&&o>=0))return e.slice(n.index,i+1).trim()}return""}function S0(e){const t=[];return t.push("visualization {"),t.push(` chart = "${e.chart??"table"}"`),e.x&&t.push(` x = ${e.x}`),e.y&&t.push(` y = ${e.y}`),e.color&&t.push(` color = ${e.color}`),e.title&&t.push(` title = "${k0(e.title)}"`),t.push("}"),t.join(`
530
- `)}function k0(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function kn(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
531
- ${t}
532
- `;const o=n?`
533
-
534
- ${t}
535
- `:`
536
- ${t}`;return r.replace(/\n\}\s*$/,`${o}
537
- }`)}function va(e,t){return t.filter(n=>n.datasetId&&(n.objectType==="dataset"||n.objectType==="staged_dataset")).filter(n=>wd(n.name).test(e)).map(n=>({id:n.datasetId,alias:n.name,role:n.objectType==="staged_dataset"?"staged":"source",fingerprint:n.fileFingerprint}))}function w0(e,t){return t.filter(n=>n.source==="database").filter(n=>wd(n.name).test(e)).map(n=>n.name)}function nk(e,t){const n=[];for(const r of e)for(const o of t){const i=j0(r,o.name,o.flags??[]);i.score>0&&n.push({warehouseKey:r,localKey:o.name,...i})}return n.sort((r,o)=>o.score-r.score||r.warehouseKey.localeCompare(o.warehouseKey)).slice(0,12)}function rk(e){const t=e.warehouseRows.map(o=>o[e.warehouseKey]).filter(o=>o!=null);if(t.length===0||!e.localSampledRows||e.localDistinctCount===void 0)return"unknown";const n=new Set(t.map(E0)).size===t.length,r=e.localDistinctCount>=e.localSampledRows;return n&&r?"one_to_one":n?"one_to_many":r?"many_to_one":"many_to_many"}function ok(e){const t=new Set(e.staged.columns??[]),r=[" warehouse.*",...(e.local.columns??[]).filter(i=>i!==e.localKey).map(i=>{const l=t.has(i)?`local_${i}`:i;return` local_data.${ln(i)} AS ${ln(l)}`})];return{id:`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,type:"sql",name:`${e.local.alias}_${e.staged.alias}_analysis`,content:["-- Local research join: governed warehouse snapshot plus local dataset","-- Review required: verify join cardinality and freshness before sharing","SELECT",r.join(`,
538
- `),`FROM ${ln(e.staged.alias)} AS warehouse`,`${e.joinType.toUpperCase()} JOIN ${ln(e.local.alias)} AS local_data`,` ON warehouse.${ln(e.warehouseKey)} = local_data.${ln(e.localKey)}`,"LIMIT 1000"].join(`
539
- `),status:"idle",executionTarget:{target:"local"},datasetRefs:[{id:e.staged.id,alias:e.staged.alias,role:"staged",fingerprint:e.staged.fileFingerprint},{id:e.local.id,alias:e.local.alias,role:"source",fingerprint:e.local.fileFingerprint}],dependencies:[{cellId:e.sourceCell.id}],annotations:[{id:`note_${Date.now()}_join`,body:`Combined ${e.staged.alias} (${e.staged.refreshedAt}) with ${e.local.alias} (${e.local.refreshedAt}) using ${e.warehouseKey} = ${e.localKey}. Review required.`,createdAt:new Date().toISOString(),author:"DQL"}]}}function j0(e,t,n){const r=e.toLowerCase(),o=t.toLowerCase();if(r===o)return{score:100,reason:"Same column name"};const i=Sa(r),l=Sa(o);return i===l?{score:90,reason:"Same normalized name"}:(i.endsWith(l)||l.endsWith(i))&&(i.endsWith("id")||l.endsWith("id"))?{score:n.includes("identifier")?78:70,reason:"Related identifier names"}:ka(r).filter(d=>ka(o).includes(d)).length>0&&(r.includes("id")||o.includes("id"))?{score:n.includes("identifier")?62:55,reason:"Shared entity identifier"}:{score:0,reason:""}}function Sa(e){return e.replace(/[^a-z0-9]/g,"").replace(/identifier$/,"id")}function ka(e){return e.split(/[^a-z0-9]+/).filter(t=>t.length>1)}function wd(e){return new RegExp(`(?:^|[^a-zA-Z0-9_])(?:["\`])?${C0(e)}(?:["\`])?(?=$|[^a-zA-Z0-9_])`,"i")}function ln(e){return`"${e.replace(/"/g,'""')}"`}function C0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function E0(e){return typeof e=="string"?e:JSON.stringify(e)}const Vt=new Map,At=new Map;function Io(e){const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}_${Math.random().toString(36).slice(2,10)}`;return`cellrun_${e}_${t}`}function A0(e){if(e.type==="markdown"||e.type==="param")return null;if(e.type==="sql")return e.content.trim()||null;const t=e.content.trim();return t?m0(t):null}function T0(e){if(!e||typeof e!="object")return;const t=e;return{...typeof t.chart=="string"?{chart:t.chart}:{},...typeof t.x=="string"?{x:t.x}:{},...typeof t.y=="string"?{y:t.y}:{},...typeof t.color=="string"?{color:t.color}:{},...typeof t.title=="string"?{title:t.title}:{}}}function In(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function R0(e){const t=In(e);if((t==null?void 0:t.target)==="local")return{target:"local"};if((t==null?void 0:t.target)==="connection")return{target:"connection",...typeof t.connectionName=="string"?{connectionName:t.connectionName}:{}}}function Rn(e,t,n){return new bt({status:400,code:e,message:t,recoverable:!0,details:{phase:"preflight",...n}})}function kr(e){const t=e.error instanceof bt?e.error:void 0,n=In(t==null?void 0:t.details),r=In(n==null?void 0:n.semanticTrace);return{version:1,runId:e.runId,cellId:e.cell.id,route:e.route,status:e.status??"error",startedAt:e.startedAt,completedAt:e.completedAt,durationMs:e.durationMs,executionTarget:e.cell.executionTarget??R0(n==null?void 0:n.executionTarget),semanticTrace:r,targetBinding:In(n==null?void 0:n.targetBinding),executionReceipt:In(n==null?void 0:n.executionReceipt),error:{code:t==null?void 0:t.code,phase:typeof(n==null?void 0:n.phase)=="string"?n.phase:"execution",message:e.message,details:t==null?void 0:t.details}}}function wr(e,t){return e.map(n=>n.id!==t.cellId?n:t.status==="success"?{...n,status:"success",result:t.result,error:void 0,execution:t.execution,executionCount:(n.executionCount??0)+1,stale:!1}:t.status==="error"||t.status==="blocked"||t.status==="cancelled"?{...n,status:t.status==="cancelled"?"idle":"error",result:void 0,error:t.status==="cancelled"?void 0:t.error,execution:t.execution,executionCount:(n.executionCount??0)+1,stale:!1}:n)}function jd(){const{state:e,dispatch:t}=xe(),n=u.useRef(e);n.current=e;const r=u.useCallback(async(a,d)=>{var R,y,M,$;const c=n.current,f=d??c.cells,p=f.find(T=>T.id===a);if(!p)return{cellId:a,status:"skipped"};const h=p.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",g=p.type==="dql"?null:A0(p);if(p.type!=="dql"&&!g)return{cellId:a,status:"skipped"};const S=Vt.get(a);S&&S.controller.abort();const x=Io(a),b=new Date().toISOString(),k=Date.now(),C=new AbortController,E={controller:C,runId:x,startedAt:b,route:h,executionTarget:p.executionTarget};Vt.set(a,E),At.set(a,x);const v=()=>{var T;return((T=Vt.get(a))==null?void 0:T.runId)===x&&At.get(a)===x},w=(p.executionCount??0)+1;t({type:"UPDATE_CELL",id:a,updates:{status:"running",error:void 0,result:void 0,execution:void 0,fromSnapshot:!1}});const A=(T,L,I="error")=>{const G=new Date().toISOString(),Y=kr({cell:p,runId:x,route:h,startedAt:b,completedAt:G,durationMs:Date.now()-k,message:T,error:L,status:I});return v()&&(t({type:"UPDATE_CELL",id:a,updates:{status:I==="cancelled"?"idle":"error",error:I==="cancelled"?void 0:T,result:void 0,execution:Y,executionCount:w,stale:!1}}),t({type:"APPEND_QUERY_LOG",entry:{id:tt(),cellName:p.name??p.id,rows:0,time:Y.durationMs,ts:new Date,...I==="cancelled"?{}:{error:T}}})),{cellId:a,runId:x,status:I,error:I==="cancelled"?void 0:T,execution:Y}};try{if(p.type==="dql"){const re=await N.executeNotebookCell(p,C.signal,{notebookPath:(R=c.activeFile)==null?void 0:R.path,cellId:p.id,cellName:p.name,source:h,runId:x});if(!re.result)throw new Error("DQL cell produced no executable result.");if(!v())return{cellId:a,runId:x,status:"cancelled"};const ge=new Date().toISOString(),ye=Date.now()-k,Ae={...re.result,executionTime:re.result.executionTime??ye,rowCount:re.result.rowCount??re.result.rows.length},ze=T0(re.chartConfig)??h0(p.content),Ie={version:1,runId:x,cellId:a,route:h,status:"success",startedAt:b,completedAt:ge,durationMs:ye,executionTarget:re.executionTarget??p.executionTarget,engine:re.engine,compiledSql:re.compiledSql,executedSql:re.executedSql,semanticTrace:re.semanticTrace,targetBinding:re.targetBinding,executionReceipt:re.executionReceipt};return t({type:"UPDATE_CELL",id:a,updates:{status:"success",result:Ae,error:void 0,execution:Ie,executionTarget:re.executionTarget??p.executionTarget,...ze?{chartConfig:ze}:{},executionCount:w,stale:!1}}),t({type:"APPEND_QUERY_LOG",entry:{id:tt(),cellName:re.blockName??p.name??p.id,rows:Ae.rowCount??Ae.rows.length,time:Ae.executionTime??ye,ts:new Date}}),setTimeout(()=>{At.get(a)===x&&(t({type:"UPDATE_CELL",id:a,updates:{status:"idle"}}),At.delete(a))},2e3),{cellId:a,runId:x,status:"success",result:Ae,execution:Ie}}const T=va(g,c.schemaTables),L=w0(g,c.schemaTables);if(T.length>0&&L.length>0){const re=[`Mixed-source query detected: ${L.join(", ")} runs in the warehouse, while ${T.map(ge=>ge.alias??ge.id).join(", ")} is local data.`,"Direct cross-engine joins are not executed. Run the warehouse-only extraction first, then choose Combine with local data on its result."].join(" ");return A(re,Rn("CROSS_ENGINE_JOIN_REQUIRED",re,{warehouseTables:L,datasets:T.map(ge=>ge.alias??ge.id)}))}const I=T.length>0?{target:"local"}:p.executionTarget;T.length>0&&((y=p.executionTarget)==null?void 0:y.target)!=="local"&&t({type:"UPDATE_CELL",id:a,updates:{executionTarget:I,datasetRefs:T}});const G=c0(g,f);if(G.ambiguous.length>0){const re=`Ambiguous notebook dependency: ${G.ambiguous.join(", ")} matches more than one cell. Rename the duplicate cells or reference a stable cell ID.`;return A(re,Rn("AMBIGUOUS_NOTEBOOK_DEPENDENCY",re,{ambiguousReferences:G.ambiguous}))}if(G.unresolved.length>0){const re=`Notebook dependency result is unavailable: ${G.unresolved.join(", ")}. Run or repair the upstream cell before retrying this cell.`;return A(re,Rn("UPSTREAM_RESULT_UNAVAILABLE",re,{unresolvedReferences:G.unresolved}))}const Y=await N.executeQuery(G.sql,C.signal,{notebookPath:(M=c.activeFile)==null?void 0:M.path,cellId:p.id,cellName:p.name,source:h,runId:x},I);if(!v())return{cellId:a,runId:x,status:"cancelled"};const P=new Date().toISOString(),q=Date.now()-k,{executionTarget:O,compiledSql:W,executedSql:se,targetBinding:H,executionReceipt:te,...J}=Y,B={...J,executionTime:J.executionTime??q,rowCount:J.rowCount??J.rows.length},ne=(I==null?void 0:I.target)==="local"?va(G.sql,c.schemaTables):p.datasetRefs,ce={version:1,runId:x,cellId:a,route:h,status:"success",startedAt:b,completedAt:P,durationMs:q,executionTarget:O??I,compiledSql:W??G.sql,executedSql:se??G.sql,targetBinding:H,executionReceipt:te};return t({type:"UPDATE_CELL",id:a,updates:{status:"success",result:B,error:void 0,execution:ce,executionCount:w,stale:!1,datasetRefs:ne,executionTarget:O??I}}),t({type:"APPEND_QUERY_LOG",entry:{id:tt(),cellName:p.name??p.id,rows:B.rowCount??B.rows.length,time:B.executionTime??q,ts:new Date}}),setTimeout(()=>{At.get(a)===x&&(t({type:"UPDATE_CELL",id:a,updates:{status:"idle"}}),At.delete(a))},2e3),{cellId:a,runId:x,status:"success",result:B,execution:ce}}catch(T){if(C.signal.aborted||!v())return A("Cell execution was cancelled.",T,"cancelled");const L=T instanceof Error?T.message:String(T);return A(L,T)}finally{(($=Vt.get(a))==null?void 0:$.runId)===x&&Vt.delete(a)}},[t]),o=u.useCallback(async()=>{const a=n.current.cells,d=pg(a);let c=a.map(h=>({...h}));const f=new Map,p=new Map;for(const h of d.missing)p.set(h.cellId,[...p.get(h.cellId)??[],h.dependency]);for(const h of d.cycleCellIds){const g=c.find(E=>E.id===h);if(!g)continue;const S=Io(h),x=new Date().toISOString(),b="Dependency cycle detected. Update the cell dependencies before running all.",k=kr({cell:g,runId:S,route:g.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",startedAt:x,completedAt:x,durationMs:0,message:b,error:Rn("DEPENDENCY_CYCLE",b,{cycleCellIds:d.cycleCellIds}),status:"blocked"}),C={cellId:h,runId:S,status:"blocked",error:b,execution:k};f.set(h,C),c=wr(c,C),t({type:"UPDATE_CELL",id:h,updates:{status:"error",error:b,result:void 0,execution:k,executionCount:(g.executionCount??0)+1,stale:!1}})}for(const h of d.ordered){const g=c.find(k=>k.id===h.id)??h,S=p.get(g.id)??[],x=Rs(g,c).filter(k=>{const C=f.get(k.cellId);return C&&C.status!=="success"});if(S.length>0||x.length>0){const k=[...S,...x.map(R=>{var y;return((y=c.find(M=>M.id===R.cellId))==null?void 0:y.name)??R.cellId})],C=Io(g.id),E=new Date().toISOString(),v=`Not executed because ${k.join(", ")} did not produce a valid upstream result.`,w=kr({cell:g,runId:C,route:g.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",startedAt:E,completedAt:E,durationMs:0,message:v,error:Rn("UPSTREAM_EXECUTION_FAILED",v,{blockedBy:k}),status:"blocked"}),A={cellId:g.id,runId:C,status:"blocked",error:v,execution:w};f.set(g.id,A),c=wr(c,A),t({type:"UPDATE_CELL",id:g.id,updates:{status:"error",error:v,result:void 0,execution:w,executionCount:(g.executionCount??0)+1,stale:!1}});continue}const b=await r(g.id,c);f.set(g.id,b),c=wr(c,b)}},[t,r]),i=u.useCallback(async a=>{if(!a)return;const d=`{{${a}}}`;let c=n.current.cells.map(f=>({...f}));for(const f of c){if(f.type==="markdown"||f.type==="param"||!f.content.includes(d))continue;const p=await r(f.id,c);c=wr(c,p)}},[r]),l=u.useCallback(a=>{const d=Vt.get(a);if(!d)return;d.controller.abort(),Vt.delete(a),At.get(a)===d.runId&&At.delete(a);const c=new Date().toISOString(),f=n.current.cells.find(p=>p.id===a);t({type:"UPDATE_CELL",id:a,updates:{status:"idle",error:void 0,result:void 0,...f?{execution:kr({cell:f,runId:d.runId,route:d.route,startedAt:d.startedAt,completedAt:c,durationMs:Date.parse(c)-Date.parse(d.startedAt),message:"Cell execution was cancelled.",status:"cancelled"}),executionCount:(f.executionCount??0)+1}:{}}})},[t]);return{executeCell:r,executeAll:o,executeDependents:i,cancelCell:l}}function Ge(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function _0(e){return typeof e=="number"?Math.abs(e)>=1e6?`${(e/1e6).toFixed(1)}M`:Math.abs(e)>=1e3?`${(e/1e3).toFixed(1)}K`:Number.isInteger(e)?String(e):e.toFixed(2):""}function $0(e){const t=e.split(`
540
- `),n=[];let r=!1,o=!1;for(const i of t){const l=i;if(l.startsWith("```")){o&&(n.push("</ul>"),o=!1),r?(n.push("</code></pre>"),r=!1):(n.push("<pre><code>"),r=!0);continue}if(r){n.push(Ge(l));continue}if(l.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${Ge(l.slice(4))}</h3>`);continue}if(l.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${Ge(l.slice(3))}</h2>`);continue}if(l.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${Ge(l.slice(2))}</h1>`);continue}if(l.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${Ge(l.slice(2))}</p></blockquote>`);continue}if(l.startsWith("- ")||l.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${wa(l.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),l.trim()===""){n.push("<br>");continue}n.push(`<p>${wa(l)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
541
- `)}function wa(e){return Ge(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function O0(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,i=t.map(a=>`<th>${Ge(a)}</th>`).join(""),l=r.map(a=>`<tr>${t.map(c=>{const f=a[c],p=typeof f=="number",h=f==null?"—":String(f);return`<td${p?' class="num"':""}>${Ge(h)}</td>`}).join("")}</tr>`).join("");return`
542
- <div class="table-wrap">
543
- <table>
544
- <thead><tr>${i}</tr></thead>
545
- <tbody>${l}</tbody>
546
- </table>
547
- ${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
548
- </div>`}function P0(e){const{columns:t,rows:n}=e;if(t.length<2||n.length===0)return null;const r=t.find(i=>typeof n[0][i]=="number"),o=t.find(i=>i!==r);return!r||!o?null:{labelCol:o,valueCol:r}}function D0(e){const t=P0(e);if(!t)return null;const n=e.rows.slice(0,20).map(f=>({label:String(f[t.labelCol]??""),value:Number(f[t.valueCol]??0)})),r=Math.max(...n.map(f=>f.value),1),o=28,i=6,l=140,a=440,d=n.length*(o+i)+40,c=n.map((f,p)=>{const h=p*(o+i)+20,g=Math.max(f.value/r*a,2);return`
549
- <text x="${l-6}" y="${h+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${Ge(f.label.slice(0,20))}</text>
550
- <rect x="${l}" y="${h}" width="${g}" height="${o}" rx="3" fill="#388bfd" />
551
- <text x="${l+g+5}" y="${h+o/2+4}" font-size="11" fill="#e6edf3">${_0(f.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${l+a+80}" height="${d}" style="max-width:100%">${c}</svg>`}function M0(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${$0(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${Ge(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,i=`<pre class="cell-code"><code>${Ge(r.content)}</code></pre>`;let l="";if(r.result&&r.result.rows.length>0){const a=D0(r.result),d=O0(r.result);l=`<div class="cell-output">${`<div class="output-meta">${r.result.rows.length.toLocaleString()} rows${r.result.executionTime?` · ${r.result.executionTime}ms`:""}</div>`}${a??""}${a?"":d}</div>`}else r.error&&(l=`<div class="cell-error">⚠ ${Ge(r.error)}</div>`);return`<section class="cell sql-cell">${o}${i}${l}</section>`}).join(`
552
- `);return`<!DOCTYPE html>
553
- <html lang="en">
554
- <head>
555
- <meta charset="UTF-8">
556
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
557
- <title>${Ge(e)}</title>
558
- <style>
559
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
560
- body {
561
- font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
562
- background: #0d1117; color: #e6edf3;
563
- line-height: 1.6; padding: 0;
564
- }
565
- .page-header {
566
- background: #161b22; border-bottom: 1px solid #21262d;
567
- padding: 16px 32px; display: flex; align-items: center; gap: 12px;
568
- }
569
- .logo {
570
- width: 28px; height: 28px; border-radius: 6px;
571
- background: linear-gradient(135deg, #388bfd, #1f6feb);
572
- display: flex; align-items: center; justify-content: center;
573
- font-size: 10px; font-weight: 700; color: #fff;
574
- font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
575
- }
576
- .page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
577
- .page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
578
- .content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
579
- .cell { border-radius: 8px; overflow: hidden; }
580
- .md-cell { padding: 4px 0; }
581
- .md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
582
- .md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
583
- .md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
584
- .md-cell p { color: #c9d1d9; margin-bottom: 8px; }
585
- .md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
586
- .md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
587
- .md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
588
- .md-cell pre code { background: none; padding: 0; }
589
- .md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
590
- .sql-cell { background: #161b22; border: 1px solid #30363d; }
591
- .cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
592
- .cell-type { font-size: 10px; font-weight: 600; letter-spacing: 0.05em; color: #8b949e; background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; }
593
- .cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
594
- .cell-code { background: #0d1117; padding: 14px; font-size: 12px; font-family: 'JetBrains Mono', monospace; color: #c9d1d9; overflow-x: auto; border-bottom: 1px solid #21262d; line-height: 1.55; white-space: pre; }
595
- .cell-output { padding: 14px; }
596
- .output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
597
- .table-wrap { overflow-x: auto; }
598
- table { width: 100%; border-collapse: collapse; font-size: 12px; }
599
- th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
600
- td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
601
- td.num { text-align: right; font-family: monospace; }
602
- tr:last-child td { border-bottom: none; }
603
- .truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
604
- .cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
605
- .exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
606
- </style>
607
- </head>
608
- <body>
609
- <div class="page-header">
610
- <div class="logo">DQL</div>
611
- <span class="page-title">${Ge(e)}</span>
612
- <span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
613
- </div>
614
- <div class="content">
615
- ${n}
616
- </div>
617
- <p class="exported-by">Built with DQL Workbench</p>
618
- </body>
619
- </html>`}function I0(e,t){const n=M0(e,t),r=new Blob([n],{type:"text/html;charset=utf-8"}),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-dashboard.html`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}function L0({t:e}){return s.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"linear-gradient(135deg, #5b8cff 0%, #7c5cff 100%)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function N0(){var te;const{state:e,dispatch:t}=xe(),n=Fe[e.themeMode],{executeAll:r}=jd(),[o,i]=u.useState(!1),[l,a]=u.useState(""),[d,c]=u.useState(!1),[f,p]=u.useState(!1),[h,g]=u.useState(!1),[S,x]=u.useState(!1),[b,k]=u.useState(!1),C=u.useRef(null),[E,v]=u.useState(!1),[w,A]=u.useState(!1),R=u.useRef(null),y=u.useRef(null),M=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,$=e.mainView==="notebook",T=e.mainView==="notebook"||e.mainView==="block_studio",L=T&&!!e.activeFile,I={home:"Home",business_artifact:((te=e.activeFile)==null?void 0:te.name.replace(/\.(dqlnb|dql)$/i,""))??"Business Definition",lineage:"Lineage",lineage_detail:"Lineage",connection:"Settings",apps:"Apps",git:"Source control",settings:"Settings",imports:"Import SQL",domains:"Domains",modeling:"Domains"},G=T?e.activeFile?e.notebookTitle||"Untitled":e.mainView==="block_studio"?"Blocks":"Notebooks":I[e.mainView]??"DQL Workbench";u.useEffect(()=>{o&&y.current&&(y.current.focus(),y.current.select())},[o]),u.useEffect(()=>{if(!w)return;function J(B){R.current&&!R.current.contains(B.target)&&A(!1)}return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[w]);const Y=()=>{a(e.notebookTitle),i(!0)},P=()=>{i(!1),l.trim()&&l!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:l.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:x0(e.blockStudioDraft,l.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},q=u.useCallback(async()=>{var J;if(e.activeFile){t({type:"SET_SAVING",saving:!0});try{if(e.mainView==="block_studio"){if(!e.blockStudioMetadata)return;const B=await N.saveBlockStudio({path:e.activeBlockPath,source:e.blockStudioDraft,metadata:{name:e.blockStudioMetadata.name,domain:e.blockStudioMetadata.domain,folderPath:e.blockStudioMetadata.folderPath,description:e.blockStudioMetadata.description,owner:e.blockStudioMetadata.owner,tags:e.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${B.metadata.name}.dql`,path:B.path,type:"block",folder:"blocks"},payload:B}),e.files.some(ne=>ne.path===B.path)||t({type:"FILE_ADDED",file:{name:`${B.metadata.name}.dql`,path:B.path,type:"block",folder:"blocks"}})}else{const B=e.activeFile.type==="block"?((J=e.cells[0])==null?void 0:J.content)??"":s0(e.notebookTitle,e.cells,e.notebookMetadata);await N.saveNotebook(e.activeFile.path,B),t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}c(!0),setTimeout(()=>c(!1),2e3)}catch(B){console.error("Save failed:",B)}finally{t({type:"SET_SAVING",saving:!1})}}},[e.activeFile,e.activeBlockPath,e.blockStudioDraft,e.blockStudioMetadata,e.files,e.mainView,e.notebookTitle,e.notebookMetadata,e.cells,t]);u.useEffect(()=>{const J=B=>{(B.metaKey||B.ctrlKey)&&B.key==="s"&&(B.preventDefault(),q())};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[q]),u.useEffect(()=>{if(!e.autoSave||!M||!e.activeFile||e.mainView==="block_studio")return;const J=setTimeout(()=>{q()},750);return()=>clearTimeout(J)},[e.autoSave,M,e.activeFile,e.cells,e.blockStudioDraft,q]);const O=[{mode:"obsidian",label:"Obsidian",glyph:"●",swatch:"#0d0e11"},{mode:"paper",label:"Paper",glyph:"☼",swatch:"#f7f4ed"},{mode:"white",label:"White",glyph:"○",swatch:"#ffffff"}],W=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode,se=O.find(J=>J.mode===W)??O[0];u.useEffect(()=>{if(!b)return;const J=ne=>{C.current&&!C.current.contains(ne.target)&&k(!1)},B=ne=>{ne.key==="Escape"&&k(!1)};return document.addEventListener("mousedown",J),document.addEventListener("keydown",B),()=>{document.removeEventListener("mousedown",J),document.removeEventListener("keydown",B)}},[b]);const H={height:28,padding:"0 10px",borderRadius:6,border:`1px solid ${n.btnBorder}`,cursor:"pointer",fontSize:12,fontWeight:500,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, color 0.15s",whiteSpace:"nowrap"};return s.jsxs("div",{style:{height:48,flexShrink:0,background:n.headerBg,borderBottom:`1px solid ${n.headerBorder}`,display:"flex",alignItems:"center",padding:"0 12px",gap:8,userSelect:"none"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[s.jsx(L0,{t:n}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&T&&s.jsx("span",{style:{fontSize:10,fontWeight:600,color:e.activeFile.type==="block"?"#e3b341":n.accent,background:`${e.activeFile.type==="block"?"#e3b341":n.accent}18`,borderRadius:4,padding:"2px 6px",fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em",flexShrink:0},children:e.activeFile.type}),e.activeFile&&T?o?s.jsx("input",{ref:y,value:l,onChange:J=>a(J.target.value),onBlur:P,onKeyDown:J=>{J.key==="Enter"&&P(),J.key==="Escape"&&i(!1)},style:{background:"transparent",border:`1px solid ${n.cellBorderActive}`,borderRadius:4,color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,padding:"2px 6px",outline:"none",minWidth:120,maxWidth:320}}):s.jsxs("span",{onClick:Y,title:"Click to rename",style:{color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,cursor:"text",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"2px 4px",borderRadius:4,border:"1px solid transparent"},children:[G,M&&s.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):s.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:G||"DQL Workbench"})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.appMode==="studio"&&L&&e.mainView!=="block_studio"&&s.jsx(s.Fragment,{children:s.jsxs("button",{onClick:$?r:void 0,disabled:!e.activeFile||!$,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),style:{...H,height:30,padding:"0 14px",borderRadius:999,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!$?.4:f?.9:1,boxShadow:"0 1px 2px rgba(107,93,211,0.25)",gap:6},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run all"]})}),s.jsxs("div",{ref:C,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>k(J=>!J),onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),title:`Theme: ${se.label}`,"aria-haspopup":"true","aria-expanded":b,style:{...H,background:S||b?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 10px",fontSize:12,display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{width:12,height:12,borderRadius:3,background:se.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:se.label}),s.jsx("span",{style:{fontSize:8,color:n.textMuted},children:"▾"})]}),b&&s.jsx("div",{role:"menu",style:{position:"absolute",top:"100%",right:0,marginTop:4,minWidth:160,background:n.headerBg,border:`1px solid ${n.headerBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.32)",padding:4,zIndex:1e3,display:"flex",flexDirection:"column",gap:1},children:O.map(J=>{const B=J.mode===W;return s.jsxs("button",{role:"menuitemradio","aria-checked":B,onClick:()=>{t({type:"SET_THEME",mode:J.mode}),k(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",background:B?n.btnHover:"transparent",color:n.textPrimary,cursor:"pointer",borderRadius:4,fontSize:12,fontFamily:n.font,textAlign:"left"},onMouseEnter:ne=>{B||(ne.currentTarget.style.background=n.btnHover)},onMouseLeave:ne=>{B||(ne.currentTarget.style.background="transparent")},children:[s.jsx("span",{style:{width:14,height:14,borderRadius:3,background:J.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{flex:1},children:J.label}),B&&s.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},J.mode)})})]}),e.appMode==="studio"&&L&&e.mainView!=="block_studio"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:q,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),title:"Save (Cmd+S)",style:{...H,background:h&&e.activeFile?n.btnHover:n.btnBg,color:d?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?s.jsxs(s.Fragment,{children:[s.jsx(F0,{}),"Saving…"]}):d?s.jsx(s.Fragment,{children:"✓ Saved"}):s.jsx(s.Fragment,{children:"Save"})}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),L&&e.mainView!=="block_studio"&&s.jsxs("div",{ref:R,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>{e.activeFile&&A(J=>!J)},disabled:!e.activeFile,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),title:"Share / export",style:{...H,height:30,padding:"0 14px",borderRadius:999,background:(E||w)&&e.activeFile?"#2a2a30":"#1a1a1a",color:"#ffffff",border:"1px solid #1a1a1a",opacity:e.activeFile?1:.4,gap:6},children:[s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M5.5 10.75a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75Zm0-3a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75ZM3 3.75A1.75 1.75 0 0 1 4.75 2h6.586c.464 0 .909.184 1.237.513l1.914 1.914c.329.328.513.773.513 1.237v6.586A1.75 1.75 0 0 1 13.25 14h-8.5A1.75 1.75 0 0 1 3 12.25Z"})}),"Share",s.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1,opacity:.7},children:s.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),w&&s.jsx("div",{style:{position:"absolute",top:32,right:0,zIndex:200,background:n.modalBg,border:`1px solid ${n.cellBorder}`,borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,minWidth:160,display:"flex",flexDirection:"column",gap:2},children:s.jsx(B0,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{I0(e.notebookTitle||"dashboard",e.cells),A(!1)}})})]})]})]})}function B0({label:e,description:t,t:n,onClick:r}){const[o,i]=u.useState(!1);return s.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:o?n.btnHover:"transparent",border:"none",borderRadius:5,cursor:"pointer",padding:"6px 10px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.12s"},children:[s.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),s.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function F0(){return s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),s.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function z0(e){return e.toTimeString().slice(0,8)}function q0(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function U0(){const{state:e,dispatch:t}=xe(),n=Fe[e.themeMode],[r,o]=u.useState(!1),i=e.queryLog.filter(a=>a.error),l=a=>t({type:"SET_DEV_PANEL_TAB",tab:a});return s.jsxs("div",{style:{height:e.devPanelOpen?180:0,flexShrink:0,background:n.sidebarBg,borderTop:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden",transition:"height 0.2s ease",position:"relative"},children:[e.devPanelOpen&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{height:32,flexShrink:0,display:"flex",alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,padding:"0 8px",gap:2},children:[["logs","errors"].map(a=>s.jsx(W0,{label:a==="errors"?`Errors${i.length>0?` (${i.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===a,onClick:()=>l(a),t:n},a)),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>t({type:"SET_CELLS",cells:e.cells}),title:"Clear logs",style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:"none",cursor:"pointer",color:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",borderRadius:4},children:"Clear"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?s.jsx(ja,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(a=>s.jsx(Ca,{entry:a,t:n},a.id))),e.devPanelTab==="errors"&&(i.length===0?s.jsx(ja,{t:n,message:"No errors."}):[...i].reverse().map(a=>s.jsx(Ca,{entry:a,t:n},a.id)))]})]}),s.jsxs("button",{onClick:()=>t({type:"TOGGLE_DEV_PANEL"}),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:e.devPanelOpen?"Close panel":"Open dev panel",style:{position:"absolute",bottom:e.devPanelOpen?4:-28,right:8,height:22,padding:"0 8px",borderRadius:"4px 4px 0 0",borderTop:`1px solid ${n.headerBorder}`,borderLeft:`1px solid ${n.headerBorder}`,borderRight:`1px solid ${n.headerBorder}`,borderBottom:e.devPanelOpen?`1px solid ${n.sidebarBg}`:`1px solid ${n.headerBorder}`,background:r?n.btnHover:n.sidebarBg,color:n.textMuted,cursor:"pointer",fontSize:11,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, bottom 0.2s ease",zIndex:10},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function W0({label:e,active:t,onClick:n,t:r}){const[o,i]=u.useState(!1);return s.jsx("button",{onClick:n,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t?r.textPrimary:o?r.textSecondary:r.textMuted,fontSize:12,fontFamily:r.font,fontWeight:t?500:400,padding:"4px 8px",height:32,transition:"color 0.15s"},children:e})}function ja({t:e,message:t}){return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function Ca({entry:e,t}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"3px 12px",fontSize:11,fontFamily:t.fontMono,color:e.error?t.error:t.textSecondary,borderLeft:e.error?`2px solid ${t.error}`:"2px solid transparent"},children:[s.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:z0(e.ts)}),s.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?s.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),s.jsx("span",{style:{color:t.textMuted},children:q0(e.time)})]})]})}function K0(){const{state:e,dispatch:t}=xe(),{executeAll:n}=jd();u.useEffect(()=>{const r=o=>{const i=o.metaKey||o.ctrlKey;if(i&&o.key==="b"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_SIDEBAR"});return}if(i&&o.shiftKey&&o.key==="Enter"){o.preventDefault(),e.activeFile&&n();return}if(i&&o.key==="j"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_DEV_PANEL"});return}if(i&&o.key==="d"&&!o.shiftKey){o.preventDefault(),e.activeFile&&t({type:"TOGGLE_DASHBOARD_MODE"});return}if(o.key==="Escape"){if(e.dashboardMode){t({type:"TOGGLE_DASHBOARD_MODE"});return}if(e.newNotebookModalOpen){t({type:"CLOSE_NEW_NOTEBOOK_MODAL"});return}if(e.newBlockModalOpen){t({type:"CLOSE_NEW_BLOCK_MODAL"});return}}};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,n,e.activeFile,e.newNotebookModalOpen,e.newBlockModalOpen,e.dashboardMode])}const V0=600;function H0(e,t){const n=t.filter(r=>r.result||r.error||(r.executionCount??0)>0).map(r=>{var o;return{cellId:r.id,status:r.status,result:r.result,error:r.error,executionCount:r.executionCount,executedAt:((o=r.execution)==null?void 0:o.completedAt)??new Date().toISOString(),execution:r.execution}});return{version:1,notebookPath:e,capturedAt:new Date().toISOString(),cells:n}}function Ea(e){return e.map(t=>{var n,r;return`${t.id}:${((n=t.execution)==null?void 0:n.runId)??""}:${t.executionCount??0}:${((r=t.result)==null?void 0:r.rowCount)??-1}:${t.error??""}`}).join("|")}function G0(){var o;const{state:e}=xe(),t=u.useRef(null),n=u.useRef(""),r=u.useRef(null);u.useEffect(()=>{var a;const i=((a=e.activeFile)==null?void 0:a.path)??null;if(!i)return;if(i!==r.current){r.current=i,n.current=Ea(e.cells);return}const l=Ea(e.cells);return l!==n.current&&(n.current=l,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const d=H0(i,e.cells);N.saveRunSnapshot(i,d).catch(()=>{})},V0)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}const J0=u.lazy(()=>je(()=>import("./HomePage-U3ryMLEF.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.HomePage}))),Q0=u.lazy(()=>je(()=>import("./AnalyticsHome-BtXEdJNR.js"),__vite__mapDeps([7,8,9,10,11,1,12,13,3,14,15,16,17,18,2,19,6])).then(e=>({default:e.AnalyticsHome}))),Y0=u.lazy(()=>je(()=>import("./GlobalAiRail-8G_rEyhK.js"),__vite__mapDeps([20,9,10,11,1,12,13,3,14,15,16,17,18,2,19,21,22,23,6])).then(e=>({default:e.GlobalAiRail}))),X0=u.lazy(()=>je(()=>import("./NotebookEditor-BdxJL3LX.js"),__vite__mapDeps([24,4,2,5,25,26,27,11,9,10,1,12,13,3,14,15,16,17,18,19,8,28,29,6,30,31,21,22,23])).then(e=>({default:e.NotebookEditor}))),Z0=u.lazy(()=>je(()=>import("./NewNotebookModal-CUx0WmXb.js"),__vite__mapDeps([32,4,15,6])).then(e=>({default:e.NewNotebookModal}))),e1=u.lazy(()=>je(()=>import("./NewBlockModal-ksEwimjl.js"),__vite__mapDeps([33,6])).then(e=>({default:e.NewBlockModal}))),t1=u.lazy(()=>je(()=>import("./SetupOnboarding-Bt0AAe0h.js"),__vite__mapDeps([34,35,2,6])).then(e=>({default:e.SetupOnboarding}))),n1=u.lazy(()=>je(()=>import("./BlockStudio-oQHTJsXC.js"),__vite__mapDeps([36,25,26,11,28,29,6,30,9,10,1,12,13,3,14,15,16,17,18,2,19,21,22,23,37,38])).then(e=>({default:e.BlockStudio}))),r1=u.lazy(()=>je(()=>import("./BusinessArtifactView-Dpsftjs7.js"),__vite__mapDeps([39,28,29,6,30])).then(e=>({default:e.BusinessArtifactView}))),o1=u.lazy(()=>je(()=>import("./LineageDetailView-CeV5QMXS.js"),__vite__mapDeps([40,28,29,6,30,41,35,17])).then(e=>({default:e.LineageDetailView}))),s1=u.lazy(()=>je(()=>import("./LineageDAG-CEmgJzm3.js"),__vite__mapDeps([41,29,6,30])).then(e=>({default:e.LineageDAG}))),i1=u.lazy(()=>je(()=>import("./HelpDocsPage-e2CesE73.js"),__vite__mapDeps([42,6])).then(e=>({default:e.HelpDocsPage}))),a1=u.lazy(()=>je(()=>Promise.resolve().then(()=>TS),void 0).then(e=>({default:e.ConnectionPanel}))),l1=u.lazy(()=>je(()=>import("./GitPage-Cj6mc-Yv.js"),__vite__mapDeps([43,44,15,6])).then(e=>({default:e.GitPage}))),c1=u.lazy(()=>je(()=>import("./ReadinessPage-DZ9wDW76.js"),__vite__mapDeps([45,1,46,47,13,3,2,6])).then(e=>({default:e.ReadinessPage}))),d1=u.lazy(()=>je(()=>import("./AgentLogPage-CsSC2tOR.js"),__vite__mapDeps([48,35,18,49,6])).then(e=>({default:e.AgentLogPage}))),u1=u.lazy(()=>je(()=>import("./GovernedContextPage-BTtzt0Za.js").then(e=>e.G),__vite__mapDeps([50,3,13,19,16,15])).then(e=>({default:e.GovernedContextPage}))),p1=u.lazy(()=>je(()=>import("./DbtFirstModelingPage-c6ZteaI6.js"),__vite__mapDeps([51,50,3,13,19,16,15,29,6,30,31,23,37,49,14])).then(e=>({default:e.DbtFirstModelingPage}))),f1=u.lazy(()=>je(()=>import("./AppsView-HjQkbbE6.js"),__vite__mapDeps([52,21,22,23,15,11,27,47,38,53,3,35,5,16,4,6])).then(e=>({default:e.AppsView}))),h1=u.lazy(()=>je(()=>import("./LineageDrawer-B1oAn-N_.js"),__vite__mapDeps([54,28,29,6,30,37,15,22,14,53,44])).then(e=>({default:e.LineageDrawer}))),m1=u.lazy(()=>je(()=>import("./AiBuildDialog-CjJ-9bQW.js"),__vite__mapDeps([55,46,12,13,3,14,15,6])).then(e=>({default:e.AiBuildDialog})));function g1(){const{state:e,dispatch:t}=xe(),n=Fe[e.themeMode],r=u.useRef({}),o=e.mainView==="block_studio"||e.mainView==="imports",[i,l]=u.useState(!1),[a,d]=u.useState(null),[c,f]=u.useState(!1);u.useEffect(()=>{let g=!0;return N.getSetupLaunch().then(S=>{g&&(d(S),S.shouldOpen&&t({type:"OPEN_SETUP"}))}).catch(()=>{}).finally(()=>{g&&f(!0)}),()=>{g=!1}},[t]),K0(),G0(),u.useEffect(()=>{const g=S=>{(S.metaKey||S.ctrlKey)&&S.key.toLowerCase()==="k"&&!S.shiftKey&&(S.preventDefault(),l(x=>!x)),(S.metaKey||S.ctrlKey)&&S.shiftKey&&S.key.toLowerCase()==="i"&&(S.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[t]);const p=u.useCallback(async g=>{try{if(g.type==="term"||g.type==="business_view"){e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"}),t({type:"OPEN_BUSINESS_ARTIFACT",file:g});return}if(g.type==="block"){const v=await N.openBlockStudio(g.path);t({type:"OPEN_BLOCK_STUDIO",file:g,payload:v});return}const{content:S}=await N.readNotebook(g.path),{title:x,cells:b,metadata:k}=i0(g.path,S),C=g.path.endsWith(".dqlnb")?await N.fetchRunSnapshot(g.path):null;let E=b;if(C!=null&&C.found&&C.snapshot){const v=new Map(C.snapshot.cells.map(w=>[w.cellId,w]));E=b.map(w=>{const A=v.get(w.id);return A?{...w,status:A.status??w.status,result:A.result??w.result,error:A.error??w.error,executionCount:A.executionCount??w.executionCount,execution:A.execution??w.execution,fromSnapshot:A.result!=null}:w})}t({type:"OPEN_FILE",file:g,cells:E,title:x,metadata:k}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(S){if(console.error("Failed to open file:",S),g.type==="block")try{const{content:x}=await N.readNotebook(g.path);t({type:"OPEN_BLOCK_STUDIO",file:g,payload:{path:g.path,source:x,companionPath:null,metadata:{name:g.name.replace(/\.dql$/i,""),path:g.path,domain:g.path.split("/").slice(1,-1).join("/")||"uncategorized",description:"",owner:"",tags:[]},validation:{valid:!1,diagnostics:[{severity:"warning",message:"Opened block without studio metadata. Save once to normalize it."}],semanticRefs:{metrics:[],dimensions:[],segments:[]}}}});return}catch(x){console.error("Failed to open block fallback:",x)}else t({type:"OPEN_FILE",file:g,cells:[_s("sql")],title:g.name})}},[t,e.sidebarPanel]);u.useCallback(g=>{const S=r.current[g];S&&S.scrollIntoView({behavior:"smooth",block:"start"})},[]);const h=u.useCallback((g,S)=>{S?r.current[g]=S:delete r.current[g]},[]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[s.jsx(N0,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(vb,{}),e.appMode==="studio"&&e.sidebarOpen&&!o&&s.jsx(ZS,{onOpenFile:p}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:s.jsx(u.Suspense,{fallback:s.jsx(y1,{t:n}),children:e.mainView==="home"?s.jsx(J0,{}):e.mainView==="ask"?s.jsx(Q0,{}):e.mainView==="business_artifact"?s.jsx(r1,{}):e.mainView==="lineage"?s.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s.jsx(s1,{})}):e.mainView==="lineage_detail"?s.jsx(o1,{}):e.mainView==="help"?s.jsx(i1,{}):e.mainView==="connection"||e.mainView==="settings"?s.jsx(x1,{children:s.jsx(a1,{variant:"page"})}):e.mainView==="git"?s.jsx(l1,{}):e.mainView==="readiness"?s.jsx(c1,{}):e.mainView==="skills"?s.jsx(u1,{initialTab:"skills"}):e.mainView==="domains"||e.mainView==="modeling"?s.jsx(p1,{}):e.mainView==="apps"?s.jsx(f1,{}):e.mainView==="agent_log"?s.jsx(b1,{title:"Agent steps",description:"What the agent did to answer this question, and where the time went — route, tools, checks, and per-step timing.",children:s.jsx(d1,{})}):s.jsx(s.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?s.jsx(n1,{},"block-editor"):s.jsxs(s.Fragment,{children:[s.jsx(X0,{onOpenFile:p,registerCellRef:h}),e.appMode==="studio"&&s.jsx(U0,{})]})})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(u.Suspense,{fallback:null,children:s.jsx(h1,{})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(lb,{}),e.globalAi.open&&e.mainView==="apps"&&s.jsx(u.Suspense,{fallback:null,children:s.jsx(Y0,{})})]}),e.newNotebookModalOpen&&s.jsx(u.Suspense,{fallback:null,children:s.jsx(Z0,{onFileOpened:p})}),e.newBlockModalOpen&&s.jsx(u.Suspense,{fallback:null,children:s.jsx(e1,{onFileOpened:p})}),s.jsx(Ax,{open:i,onClose:()=>l(!1)}),s.jsx(u.Suspense,{fallback:null,children:s.jsx(m1,{})}),e.setupOpen&&s.jsx(u.Suspense,{fallback:s.jsx(Aa,{t:n}),children:s.jsx(t1,{launch:a!=null&&a.shouldOpen?a:void 0,onAcknowledged:()=>d(g=>g&&{...g,shouldOpen:!1,reason:null})})}),!c&&s.jsx(Aa,{t:n})]})}function y1({t:e}){return s.jsx("div",{role:"status","aria-live":"polite",style:{flex:1,minWidth:0,display:"grid",placeItems:"center",background:e.appBg,color:e.textSecondary,fontFamily:e.font},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:12.5},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:999,background:e.accent}}),"Loading workspace…"]})})}function Aa({t:e}){return s.jsx("div",{role:"status","aria-live":"polite",style:{position:"fixed",inset:0,zIndex:1100,display:"grid",placeItems:"center",background:e.appBg,color:e.textSecondary,fontFamily:e.font},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:12.5},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:999,background:e.accent}}),"Checking workspace setup…"]})})}function x1({children:e}){return s.jsx("div",{style:{flex:1,minWidth:0,overflow:"auto"},children:s.jsx("div",{style:{maxWidth:1120,margin:"0 auto",padding:"18px 28px 32px"},children:e})})}function b1({title:e,description:t,children:n}){return s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"18px 24px 12px",borderBottom:"1px solid rgba(127, 127, 127, 0.16)"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700},children:e}),s.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:6,maxWidth:760,lineHeight:1.5},children:t})]}),s.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:n})]})}function v1(){const{state:e,dispatch:t}=xe(),n=u.useRef(null),r=u.useRef(null);u.useEffect(()=>{var o;n.current=((o=e.activeFile)==null?void 0:o.path)??null},[e.activeFile]),u.useEffect(()=>{if(typeof EventSource>"u")return;const o=()=>{const i=new EventSource(`${window.location.origin}/api/watch`);r.current=i,i.addEventListener("change",l=>{try{const a=JSON.parse(l.data);(a.type==="file-added"||a.type==="file-deleted")&&N.listNotebooks().then(d=>{t({type:"SET_FILES",files:d})}),a.type==="file-changed"&&N.listNotebooks().then(d=>{t({type:"SET_FILES",files:d})}),a.type==="semantic-reload"&&(t({type:"SET_SEMANTIC_LOADING",loading:!0}),N.getSemanticLayer().then(d=>{t({type:"SET_SEMANTIC_LAYER",layer:d})}))}catch{}}),i.addEventListener("error",()=>{i.close(),setTimeout(o,5e3)})};return o(),()=>{var i;(i=r.current)==null||i.close(),r.current=null}},[t])}function S1(){const{state:e,dispatch:t}=xe(),n=Fe[e.themeMode];u.useEffect(()=>{const o="dql-global-styles";let i=document.getElementById(o);i||(i=document.createElement("style"),i.id=o,document.head.appendChild(i)),i.textContent=`
620
- * { margin: 0; padding: 0; box-sizing: border-box; }
621
- body {
622
- font-family: var(--font-ui, ${n.font});
623
- overflow: hidden;
624
- background: var(--color-bg-primary);
625
- color: var(--color-text-primary);
626
- }
627
- ::-webkit-scrollbar { width: 6px; height: 6px; }
628
- ::-webkit-scrollbar-track { background: transparent; }
629
- ::-webkit-scrollbar-thumb {
630
- background: var(--color-border-secondary);
631
- border-radius: 3px;
632
- }
633
- ::-webkit-scrollbar-thumb:hover {
634
- background: var(--color-text-tertiary);
635
- }
636
- ::selection {
637
- background: color-mix(in srgb, var(--color-accent-blue) 25%, transparent);
638
- color: var(--color-text-primary);
639
- }
640
- .dql-meta-pill:hover {
641
- background: var(--dql-pill-hover-bg) !important;
642
- border-color: var(--dql-pill-hover-border) !important;
643
- }
644
- `},[n]),u.useEffect(()=>{const o=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode;document.documentElement.setAttribute("data-theme",o)},[e.themeMode]);const r=u.useRef(!1);return u.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:!0}),N.listNotebooks().then(o=>{t({type:"SET_FILES",files:o}),t({type:"SET_FILES_LOADING",loading:!1}),r.current=!0})},[t]),v1(),s.jsx(Kd,{theme:e.themeMode,applyGlobal:!0,children:s.jsx(nf,{delayDuration:200,skipDelayDuration:400,children:s.jsx(g1,{})})})}function k1(){return s.jsx(vg,{children:s.jsx(S1,{})})}qd.createRoot(document.getElementById("root")).render(s.jsx(k1,{}));export{jo as $,V1 as A,$s as B,ey as C,tr as D,K1 as E,uy as F,Sn as G,jd as H,ok as I,Uv as J,va as K,Fn as L,w0 as M,Vy as N,gb as O,ox as P,M1 as Q,Pe as R,Lc as S,Nc as T,I1 as U,q1 as V,L1 as W,Ic as X,Ir as Y,uS as Z,cd as _,N as a,Go as a0,Q1 as a1,Rv as a2,ek as a3,tk as a4,y0 as a5,x0 as a6,Y1 as a7,W1 as a8,md as a9,ny as aA,td as aB,ly as aC,Pc as aD,i0 as aE,Yg as aF,je as aG,By as aH,Dc as aI,px as aJ,my as aK,Bc as aL,G1 as aM,Rc as aN,X1 as aa,v0 as ab,b0 as ac,J1 as ad,xa as ae,Z1 as af,qr as ag,fv as ah,Li as ai,F1 as aj,z1 as ak,B1 as al,N1 as am,qc as an,O1 as ao,P1 as ap,D1 as aq,ib as ar,ab as as,$1 as at,zi as au,qy as av,Rg as aw,Pg as ax,Dy as ay,Ry as az,Os as b,ke as c,oo as d,Oc as e,Ug as f,X as g,hx as h,m0 as i,s as j,Ps as k,U1 as l,_s as m,rb as n,ob as o,rk as p,gd as q,u as r,nk as s,Fe as t,xe as u,yd as v,H1 as w,f0 as x,hd as y,d0 as z};