@duckcodeailabs/dql-cli 1.12.10 → 1.12.11

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 (71) hide show
  1. package/dist/assets/dql-notebook/assets/{AgentAnswerCard-Dp4odOLE.js → AgentAnswerCard-CpL2kDCV.js} +1 -1
  2. package/dist/assets/dql-notebook/assets/{AgentLogPage-uvVs284-.js → AgentLogPage-hzHqpD3-.js} +1 -1
  3. package/dist/assets/dql-notebook/assets/{AiBuildDialog-DEUS19WF.js → AiBuildDialog-BQRWoxp9.js} +1 -1
  4. package/dist/assets/dql-notebook/assets/AiBuildResult-D9t_4sQl.js +33 -0
  5. package/dist/assets/dql-notebook/assets/{AiSidePanel-C7BZVSkM.js → AiSidePanel-BCQB9rVF.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AnalyticsHome-4TgtH6SB.js → AnalyticsHome-Ba4Ve_Gd.js} +1 -1
  7. package/dist/assets/dql-notebook/assets/AppsView-CdAT9BOq.js +4466 -0
  8. package/dist/assets/dql-notebook/assets/{BlockStudio-DUXN3MKz.js → BlockStudio-Brg4fwn5.js} +13 -13
  9. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-D8FIgrkF.js → BusinessArtifactView-CnTbFVGT.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/DbtFirstModelingPage-CQe2FUZq.js +22 -0
  11. package/dist/assets/dql-notebook/assets/{GitPage-BS2sm9zh.js → GitPage-DHyDBChc.js} +1 -1
  12. package/dist/assets/dql-notebook/assets/{GlobalAiRail-B_MZsB0z.js → GlobalAiRail-Cys4n_rq.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/GovernedContextPage-DyKoDSZ2.js +7 -0
  14. package/dist/assets/dql-notebook/assets/{HelpDocsPage-Bc5pLakt.js → HelpDocsPage-CL0vbSER.js} +3 -3
  15. package/dist/assets/dql-notebook/assets/{HomePage-DQSo-K4y.js → HomePage-DzAucwBW.js} +9 -4
  16. package/dist/assets/dql-notebook/assets/{LineageDAG-RdpWmGmR.js → LineageDAG-QHqd_AM5.js} +1 -1
  17. package/dist/assets/dql-notebook/assets/{LineageDetailView-CZEx2r1H.js → LineageDetailView-DdVH-nz6.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{LineageDrawer-P7ZdOW8-.js → LineageDrawer-BvrVZNKY.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/LineagePathBreadcrumb-CSut-zvm.js +14 -0
  20. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-Ctp_yFh8.js → MiniLineageGraph-zg_1wW3M.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/NewBlockModal-9cDletl-.js +1 -0
  22. package/dist/assets/dql-notebook/assets/NewNotebookModal-V6de8L4d.js +46 -0
  23. package/dist/assets/dql-notebook/assets/NotebookEditor-EZ0pfWVs.js +200 -0
  24. package/dist/assets/dql-notebook/assets/{ReadinessPage-C8hATaT_.js → ReadinessPage-BaGvjyfd.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{SetupOnboarding-DX2f53J2.js → SetupOnboarding-Bg-MjbC9.js} +2 -2
  26. package/dist/assets/dql-notebook/assets/{TrustBadge-DPnKzRSY.js → TrustBadge-DGuHB8kP.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/{UnifiedAgentRunPanel-CwxQ4T19.js → UnifiedAgentRunPanel-BlWAVEwO.js} +17 -17
  28. package/dist/assets/dql-notebook/assets/{answer-to-notebook-Bm9oByWA.js → answer-to-notebook-BDzY4MuQ.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{arrow-left-D2FbLWqh.js → arrow-left-IjlnAihE.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{arrow-right-OYItAZ-s.js → arrow-right-BI4cXgOY.js} +2 -2
  31. package/dist/assets/dql-notebook/assets/{book-open-text-BnnirfAc.js → book-open-text-i6xhxu_I.js} +1 -1
  32. package/dist/assets/dql-notebook/assets/{bot-BJNxPYFm.js → bot-C6DE7Q6m.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{chevron-up-DM5LX-26.js → chevron-up-DSEILnDs.js} +2 -2
  34. package/dist/assets/dql-notebook/assets/{circle-x-Dic_-4tF.js → circle-x-BoAorVSm.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{codemirror-1_I9gm6Z.js → codemirror-DXt7RW72.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{dagre.esm-C9zxjHHX.js → dagre.esm-CycymVj6.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{external-link-DHxAcoCE.js → external-link-ZwE5iHsX.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/{grip-vertical-02I-EOjL.js → grip-vertical-Dnp2st8l.js} +1 -1
  39. package/dist/assets/dql-notebook/assets/index-BTuliKhK.js +634 -0
  40. package/dist/assets/dql-notebook/assets/{link-2-Delh-lai.js → link-2-CTKe6Snr.js} +2 -2
  41. package/dist/assets/dql-notebook/assets/{list-tree-BrIZg6l6.js → list-tree-Ced8e_S1.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{maximize-2-CQOA-bbN.js → maximize-2-Cojc6867.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{minimize-2-CUDBPkwe.js → minimize-2-CBIAE0XH.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{panel-right-open-CwhZfkKJ.js → panel-right-open-po3bWSeL.js} +2 -2
  45. package/dist/assets/dql-notebook/assets/{pencil-Cf6-MgpT.js → pencil-Cb45c6WU.js} +2 -2
  46. package/dist/assets/dql-notebook/assets/{rotate-ccw-DndbJAiz.js → rotate-ccw-B9v1LTJ0.js} +2 -2
  47. package/dist/assets/dql-notebook/assets/{semantic-fields-DwKPY_mU.js → semantic-fields-B6ii0an0.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/{star-DvcMC9wZ.js → star-CO4tfaDq.js} +2 -2
  49. package/dist/assets/dql-notebook/assets/{triangle-alert-DUf4Ook0.js → triangle-alert-BSdIu2El.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-DbdBi0oH.js → usePersistedAgentThreadId-CkVFrrjk.js} +2 -2
  51. package/dist/assets/dql-notebook/assets/{user-round-DSt0xU3K.js → user-round-BfrV8U-W.js} +3 -3
  52. package/dist/assets/dql-notebook/assets/{wand-sparkles-ro8Cq0ro.js → wand-sparkles-BgTxZNBc.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/{workflow-DVJXehjU.js → workflow--2ycp0yy.js} +2 -2
  54. package/dist/assets/dql-notebook/assets/{wrench-DxUnoHtz.js → wrench-LMCrpa9_.js} +1 -1
  55. package/dist/assets/dql-notebook/assets/{x-9Gtb3EAd.js → x-CeNgQwGm.js} +2 -2
  56. package/dist/assets/dql-notebook/index.html +1 -1
  57. package/dist/local-runtime.d.ts +40 -1
  58. package/dist/local-runtime.d.ts.map +1 -1
  59. package/dist/local-runtime.js +602 -172
  60. package/dist/local-runtime.js.map +1 -1
  61. package/dist/package.json +10 -10
  62. package/package.json +10 -10
  63. package/dist/assets/dql-notebook/assets/AiBuildResult-B9KmBRsh.js +0 -33
  64. package/dist/assets/dql-notebook/assets/AppsView-CnfNtk5W.js +0 -4466
  65. package/dist/assets/dql-notebook/assets/DbtFirstModelingPage-DR8hTZ95.js +0 -22
  66. package/dist/assets/dql-notebook/assets/GovernedContextPage-CNM5UCAH.js +0 -7
  67. package/dist/assets/dql-notebook/assets/LineagePathBreadcrumb-DTUMFkJ8.js +0 -14
  68. package/dist/assets/dql-notebook/assets/NewBlockModal-BLtjuWGy.js +0 -1
  69. package/dist/assets/dql-notebook/assets/NewNotebookModal-xgaKB2kI.js +0 -46
  70. package/dist/assets/dql-notebook/assets/NotebookEditor-D6RgLQw-.js +0 -202
  71. package/dist/assets/dql-notebook/assets/index-Ca3UeUWI.js +0 -644
@@ -1,644 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/HomePage-DQSo-K4y.js","assets/TrustBadge-DPnKzRSY.js","assets/arrow-right-OYItAZ-s.js","assets/triangle-alert-DUf4Ook0.js","assets/book-open-text-BnnirfAc.js","assets/workflow-DVJXehjU.js","assets/react-CRB3T2We.js","assets/AnalyticsHome-4TgtH6SB.js","assets/answer-to-notebook-Bm9oByWA.js","assets/UnifiedAgentRunPanel-CwxQ4T19.js","assets/AgentAnswerCard-Dp4odOLE.js","assets/usePersistedAgentThreadId-DbdBi0oH.js","assets/AiBuildResult-B9KmBRsh.js","assets/user-round-DSt0xU3K.js","assets/rotate-ccw-DndbJAiz.js","assets/x-9Gtb3EAd.js","assets/pencil-Cf6-MgpT.js","assets/list-tree-BrIZg6l6.js","assets/wrench-DxUnoHtz.js","assets/chevron-up-DM5LX-26.js","assets/star-DvcMC9wZ.js","assets/GlobalAiRail-B_MZsB0z.js","assets/AiSidePanel-C7BZVSkM.js","assets/minimize-2-CUDBPkwe.js","assets/maximize-2-CQOA-bbN.js","assets/NotebookEditor-D6RgLQw-.js","assets/LineagePathBreadcrumb-DTUMFkJ8.js","assets/codemirror-1_I9gm6Z.js","assets/semantic-fields-DwKPY_mU.js","assets/MiniLineageGraph-Ctp_yFh8.js","assets/dagre.esm-C9zxjHHX.js","assets/dagre-BZV40eAE.css","assets/link-2-Delh-lai.js","assets/NewNotebookModal-xgaKB2kI.js","assets/NewBlockModal-BLtjuWGy.js","assets/SetupOnboarding-DX2f53J2.js","assets/arrow-left-D2FbLWqh.js","assets/BlockStudio-DUXN3MKz.js","assets/panel-right-open-CwhZfkKJ.js","assets/bot-BJNxPYFm.js","assets/BusinessArtifactView-D8FIgrkF.js","assets/LineageDetailView-CZEx2r1H.js","assets/LineageDAG-RdpWmGmR.js","assets/HelpDocsPage-Bc5pLakt.js","assets/GitPage-BS2sm9zh.js","assets/external-link-DHxAcoCE.js","assets/ReadinessPage-C8hATaT_.js","assets/ai-build-bus-1BR770pY.js","assets/wand-sparkles-ro8Cq0ro.js","assets/AgentLogPage-uvVs284-.js","assets/circle-x-Dic_-4tF.js","assets/GovernedContextPage-CNM5UCAH.js","assets/DbtFirstModelingPage-DR8hTZ95.js","assets/AppsView-CnfNtk5W.js","assets/grip-vertical-02I-EOjL.js","assets/LineageDrawer-P7ZdOW8-.js","assets/AiBuildDialog-DEUS19WF.js"])))=>i.map(i=>d[i]);
2
- var Nd=Object.defineProperty;var Bd=(e,t,n)=>t in e?Nd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ee=(e,t,n)=>Bd(e,typeof t!="symbol"?t+"":t,n);import{r as $a,a as Oa,g as Pa}from"./react-CRB3T2We.js";function Fd(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 ri;function zd(){if(ri)return jn;ri=1;var e=$a(),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 oi;function qd(){return oi||(oi=1,ao.exports=zd()),ao.exports}var s=qd(),lr={},si;function Ud(){if(si)return lr;si=1;var e=Oa();return lr.createRoot=e.createRoot,lr.hydrateRoot=e.hydrateRoot,lr}var Wd=Ud(),u=$a();const De=Pa(u),Da=Fd({__proto__:null,default:De},[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"},he={1:"4px",2:"8px",3:"12px",4:"16px"},Lt={sm:"4px",md:"6px",lg:"8px"},Fe={xs:"11px",sm:"12px",md:"14px"},ts={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)"},Kd={obsidian:lo,paper:cr,white:cr,dark:lo,light:cr,midnight:lo,arctic:cr};function Ma(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function ii(e){const t={};for(const[n,r]of Object.entries(e))t[Ma(n)]=r;return t}function le(e){return`var(${Ma(e)})`}const Vd=u.createContext(null);function Hd({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[i,l]=u.useState(t),a=e??i,d=Kd[a],c=u.useCallback(h=>{e===void 0&&l(h),n==null||n(h)},[e,n]);u.useEffect(()=>{if(!r)return;const h=ii(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:ii(d);return s.jsx(Vd.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 ai(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=ai(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():ai(e[o],null)}}}}function je(...e){return u.useCallback(Ur(...e),e)}function Gd(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 Nt(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,Jd(o,...t)]}function Jd(...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 ns=Oa();const Qd=Pa(ns);function hn(e){const t=Yd(e),n=u.forwardRef((r,o)=>{const{children:i,...l}=r,a=u.Children.toArray(i),d=a.find(Zd);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 Yd(e){const t=u.forwardRef((n,r)=>{const{children:o,...i}=n;if(u.isValidElement(o)){const l=tu(o),a=eu(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 Ia=Symbol("radix.slottable");function Xd(e){const t=({children:n})=>s.jsx(s.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=Ia,t}function Zd(e){return u.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ia}function eu(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 tu(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 nu=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ke=nu.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 La(e,t){e&&ns.flushSync(()=>e.dispatchEvent(t))}function Ot(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 ru(e,t=globalThis==null?void 0:globalThis.document){const n=Ot(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 ou="DismissableLayer",No="dismissableLayer.update",su="dismissableLayer.pointerDownOutside",iu="dismissableLayer.focusOutside",li,Na=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(Na),[f,p]=u.useState(null),h=(f==null?void 0:f.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,g]=u.useState({}),S=je(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=cu(R=>{const y=R.target,M=[...c.branches].some(O=>O.contains(y));!v||M||(o==null||o(R),l==null||l(R),R.defaultPrevented||a==null||a())},h),A=du(R=>{const y=R.target;[...c.branches].some(O=>O.contains(y))||(i==null||i(R),l==null||l(R),R.defaultPrevented||a==null||a())},h);return ru(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&&(li=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(f)),c.layers.add(f),ci(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=li)}},[f,h,n,c]),u.useEffect(()=>()=>{f&&(c.layers.delete(f),c.layersWithOutsidePointerEventsDisabled.delete(f),ci())},[f,c]),u.useEffect(()=>{const R=()=>g({});return document.addEventListener(No,R),()=>document.removeEventListener(No,R)},[]),s.jsx(ke.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=ou;var au="DismissableLayerBranch",lu=u.forwardRef((e,t)=>{const n=u.useContext(Na),r=u.useRef(null),o=je(t,r);return u.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),s.jsx(ke.div,{...e,ref:o})});lu.displayName=au;function cu(e,t=globalThis==null?void 0:globalThis.document){const n=Ot(e),r=u.useRef(!1),o=u.useRef(()=>{});return u.useEffect(()=>{const i=a=>{if(a.target&&!r.current){let d=function(){Ba(su,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 du(e,t=globalThis==null?void 0:globalThis.document){const n=Ot(e),r=u.useRef(!1);return u.useEffect(()=>{const o=i=>{i.target&&!r.current&&Ba(iu,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 ci(){const e=new CustomEvent(No);document.dispatchEvent(e)}function Ba(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?La(o,i):o.dispatchEvent(i)}var Pt=globalThis!=null&&globalThis.document?u.useLayoutEffect:()=>{},uu=Da[" useId ".trim().toString()]||(()=>{}),pu=0;function Ln(e){const[t,n]=u.useState(uu());return Pt(()=>{n(r=>r??String(pu++))},[e]),t?`radix-${t}`:""}const fu=["top","right","bottom","left"],Dt=Math.min,Xe=Math.max,Rr=Math.round,dr=Math.floor,bt=e=>({x:e,y:e}),hu={left:"right",right:"left",bottom:"top",top:"bottom"};function Bo(e,t,n){return Xe(e,Dt(t,n))}function Ct(e,t){return typeof e=="function"?e(t):e}function Et(e){return e.split("-")[0]}function xn(e){return e.split("-")[1]}function rs(e){return e==="x"?"y":"x"}function os(e){return e==="y"?"height":"width"}function xt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function ss(e){return rs(xt(e))}function mu(e,t,n){n===void 0&&(n=!1);const r=xn(e),o=ss(e),i=os(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 gu(e){const t=_r(e);return[Fo(e),t,Fo(t)]}function Fo(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const di=["left","right"],ui=["right","left"],yu=["top","bottom"],xu=["bottom","top"];function bu(e,t,n){switch(e){case"top":case"bottom":return n?t?ui:di:t?di:ui;case"left":case"right":return t?yu:xu;default:return[]}}function vu(e,t,n,r){const o=xn(e);let i=bu(Et(e),n==="start",r);return o&&(i=i.map(l=>l+"-"+o),t&&(i=i.concat(i.map(Fo)))),i}function _r(e){const t=Et(e);return hu[t]+e.slice(t.length)}function Su(e){return{top:0,right:0,bottom:0,left:0,...e}}function Fa(e){return typeof e!="number"?Su(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 pi(e,t,n){let{reference:r,floating:o}=e;const i=xt(t),l=ss(t),a=os(l),d=Et(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 ku(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}=Ct(t,e),S=Fa(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 wu=50,ju=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:l}=n,a=l.detectOverflow?l:{...l,detectOverflow:ku},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}=pi(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<wu&&(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}=pi(c,h,d)),x=-1)}return{x:f,y:p,placement:h,strategy:o,middlewareData:S}},Cu=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}=Ct(e,t)||{};if(c==null)return{};const p=Fa(f),h={x:n,y:r},g=ss(o),S=os(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,O=Dt(p[k],M),T=Dt(p[C],M),L=O,I=R-x[S]-T,V=R/2-x[S]/2+y,X=Bo(L,V,I),J=!d.arrow&&xn(o)!=null&&V!==X&&i.reference[S]/2-(V<L?O:T)-x[S]/2<0,W=J?V<L?V-L:V-I:0;return{[g]:h[g]+W,data:{[g]:X,centerOffset:V-X-W,...J&&{alignmentOffset:W}},reset:J}}}),Eu=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}=Ct(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const k=Et(o),C=xt(a),E=Et(a)===a,v=await(d.isRTL==null?void 0:d.isRTL(c.floating)),w=h||(E||!x?[_r(a)]:gu(a)),A=S!=="none";!h&&A&&w.push(...vu(a,x,S,v));const R=[a,...w],y=await d.detectOverflow(t,b),M=[];let O=((r=i.flip)==null?void 0:r.overflows)||[];if(f&&M.push(y[k]),p){const V=mu(o,l,v);M.push(y[V[0]],y[V[1]])}if(O=[...O,{placement:o,overflows:M}],!M.every(V=>V<=0)){var T,L;const V=(((T=i.flip)==null?void 0:T.index)||0)+1,X=R[V];if(X&&(!(p==="alignment"?C!==xt(X):!1)||O.every(D=>xt(D.placement)===C?D.overflows[0]>0:!0)))return{data:{index:V,overflows:O},reset:{placement:X}};let J=(L=O.filter(W=>W.overflows[0]<=0).sort((W,D)=>W.overflows[1]-D.overflows[1])[0])==null?void 0:L.placement;if(!J)switch(g){case"bestFit":{var I;const W=(I=O.filter(D=>{if(A){const $=xt(D.placement);return $===C||$==="y"}return!0}).map(D=>[D.placement,D.overflows.filter($=>$>0).reduce(($,Q)=>$+Q,0)]).sort((D,$)=>D[1]-$[1])[0])==null?void 0:I[0];W&&(J=W);break}case"initialPlacement":J=a;break}if(o!==J)return{reset:{placement:J}}}return{}}}};function fi(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function hi(e){return fu.some(t=>e[t]>=0)}const Au=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:o="referenceHidden",...i}=Ct(e,t);switch(o){case"referenceHidden":{const l=await r.detectOverflow(t,{...i,elementContext:"reference"}),a=fi(l,n.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:hi(a)}}}case"escaped":{const l=await r.detectOverflow(t,{...i,altBoundary:!0}),a=fi(l,n.floating);return{data:{escapedOffsets:a,escaped:hi(a)}}}default:return{}}}}},za=new Set(["left","top"]);async function Tu(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),l=Et(n),a=xn(n),d=xt(n)==="y",c=za.has(l)?-1:1,f=i&&d?-1:1,p=Ct(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 Ru=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 Tu(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}}}}},_u=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}=Ct(e,t),f={x:n,y:r},p=await i.detectOverflow(t,c),h=xt(Et(o)),g=rs(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=Bo(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=Bo(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}}}}}},$u=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}=Ct(e,t),f={x:n,y:r},p=xt(o),h=rs(p);let g=f[h],S=f[p];const x=Ct(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=za.has(Et(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}}}},Ou=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}=Ct(e,t),f=await l.detectOverflow(t,c),p=Et(o),h=xn(o),g=xt(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=Dt(x-f[b],C),w=Dt(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 O=Xe(f.left,0),T=Xe(f.right,0),L=Xe(f.top,0),I=Xe(f.bottom,0);g?y=S-2*(O!==0||T!==0?O+T:Xe(f.left,f.right)):R=x-2*(L!==0||I!==0?L+I:Xe(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 qa(e)?(e.nodeName||"").toLowerCase():"#document"}function Ze(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function St(e){var t;return(t=(qa(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function qa(e){return Wr()?e instanceof Node||e instanceof Ze(e).Node:!1}function pt(e){return Wr()?e instanceof Element||e instanceof Ze(e).Element:!1}function At(e){return Wr()?e instanceof HTMLElement||e instanceof Ze(e).HTMLElement:!1}function mi(e){return!Wr()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof Ze(e).ShadowRoot}function Qn(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=ft(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&o!=="inline"&&o!=="contents"}function Pu(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 Du=/transform|translate|scale|rotate|perspective|filter/,Mu=/paint|layout|strict|content/,Wt=e=>!!e&&e!=="none";let co;function is(e){const t=pt(e)?ft(e):e;return Wt(t.transform)||Wt(t.translate)||Wt(t.scale)||Wt(t.rotate)||Wt(t.perspective)||!as()&&(Wt(t.backdropFilter)||Wt(t.filter))||Du.test(t.willChange||"")||Mu.test(t.contain||"")}function Iu(e){let t=Mt(e);for(;At(t)&&!mn(t);){if(is(t))return t;if(Kr(t))return null;t=Mt(t)}return null}function as(){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 ft(e){return Ze(e).getComputedStyle(e)}function Vr(e){return pt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Mt(e){if(bn(e)==="html")return e;const t=e.assignedSlot||e.parentNode||mi(e)&&e.host||St(e);return mi(t)?t.host:t}function Ua(e){const t=Mt(e);return mn(t)?e.ownerDocument?e.ownerDocument.body:e.body:At(t)&&Qn(t)?t:Ua(t)}function qn(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Ua(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),l=Ze(o);if(i){const a=zo(l);return t.concat(l,l.visualViewport||[],Qn(o)?o:[],a&&n?qn(a):[])}else return t.concat(o,qn(o,[],n))}function zo(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Wa(e){const t=ft(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=At(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 ls(e){return pt(e)?e:e.contextElement}function pn(e){const t=ls(e);if(!At(t))return bt(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=Wa(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 Lu=bt(0);function Ka(e){const t=Ze(e);return!as()||!t.visualViewport?Lu:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Nu(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==Ze(e)?!1:t}function Gt(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=ls(e);let l=bt(1);t&&(r?pt(r)&&(l=pn(r)):l=pn(e));const a=Nu(i,n,r)?Ka(i):bt(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=Ze(i),g=r&&pt(r)?Ze(r):r;let S=h,x=zo(S);for(;x&&r&&g!==S;){const b=pn(x),k=x.getBoundingClientRect(),C=ft(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=Ze(x),x=zo(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(St(e)).left+n}function Va(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 Bu(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i=o==="fixed",l=St(r),a=t?Kr(t.floating):!1;if(r===l||a&&i)return n;let d={scrollLeft:0,scrollTop:0},c=bt(1);const f=bt(0),p=At(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?Va(l,d):bt(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 Fu(e){return Array.from(e.getClientRects())}function zu(e){const t=St(e),n=Vr(e),r=e.ownerDocument.body,o=Xe(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Xe(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+Hr(e);const a=-n.scrollTop;return ft(r).direction==="rtl"&&(l+=Xe(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:l,y:a}}const gi=25;function qu(e,t){const n=Ze(e),r=St(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=as();(!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<=gi&&(i-=S)}else c<=gi&&(i+=c);return{width:i,height:l,x:a,y:d}}function Uu(e,t){const n=Gt(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=At(e)?pn(e):bt(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 yi(e,t,n){let r;if(t==="viewport")r=qu(e,n);else if(t==="document")r=zu(St(e));else if(pt(t))r=Uu(t,n);else{const o=Ka(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return $r(r)}function Ha(e,t){const n=Mt(e);return n===t||!pt(n)||mn(n)?!1:ft(n).position==="fixed"||Ha(n,t)}function Wu(e,t){const n=t.get(e);if(n)return n;let r=qn(e,[],!1).filter(a=>pt(a)&&bn(a)!=="body"),o=null;const i=ft(e).position==="fixed";let l=i?Mt(e):e;for(;pt(l)&&!mn(l);){const a=ft(l),d=is(l);!d&&a.position==="fixed"&&(o=null),(i?!d&&!o:!d&&a.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||Qn(l)&&!d&&Ha(e,l))?r=r.filter(f=>f!==l):o=a,l=Mt(l)}return t.set(e,r),r}function Ku(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const l=[...n==="clippingAncestors"?Kr(t)?[]:Wu(t,this._c):[].concat(n),r],a=yi(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=yi(t,l[h],o);d=Xe(g.top,d),c=Dt(g.right,c),f=Dt(g.bottom,f),p=Xe(g.left,p)}return{width:c-p,height:f-d,x:p,y:d}}function Vu(e){const{width:t,height:n}=Wa(e);return{width:t,height:n}}function Hu(e,t,n){const r=At(t),o=St(t),i=n==="fixed",l=Gt(e,!0,i,t);let a={scrollLeft:0,scrollTop:0};const d=bt(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?Va(o,a):bt(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 ft(e).position==="static"}function xi(e,t){if(!At(e)||ft(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return St(e)===n&&(n=n.ownerDocument.body),n}function Ga(e,t){const n=Ze(e);if(Kr(e))return n;if(!At(e)){let o=Mt(e);for(;o&&!mn(o);){if(pt(o)&&!uo(o))return o;o=Mt(o)}return n}let r=xi(e,t);for(;r&&Pu(r)&&uo(r);)r=xi(r,t);return r&&mn(r)&&uo(r)&&!is(r)?n:r||Iu(e)||n}const Gu=async function(e){const t=this.getOffsetParent||Ga,n=this.getDimensions,r=await n(e.floating);return{reference:Hu(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Ju(e){return ft(e).direction==="rtl"}const Qu={convertOffsetParentRelativeRectToViewportRelativeRect:Bu,getDocumentElement:St,getClippingRect:Ku,getOffsetParent:Ga,getElementRects:Gu,getClientRects:Fu,getDimensions:Vu,getScale:pn,isElement:pt,isRTL:Ju};function Ja(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Yu(e,t){let n=null,r;const o=St(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:Xe(0,Dt(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&&!Ja(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 Xu(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=ls(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?Yu(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&&!Ja(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 Zu=Ru,ep=_u,tp=Eu,np=Ou,rp=Au,bi=Cu,op=$u,sp=(e,t,n)=>{const r=new Map,o={platform:Qu,...n},i={...o.platform,_c:r};return ju(e,t,{...o,platform:i})};var ip=typeof document<"u",ap=function(){},jr=ip?u.useLayoutEffect:ap;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 Qa(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function vi(e,t){const n=Qa(e);return Math.round(t*n)/n}function po(e){const t=u.useRef(e);return jr(()=>{t.current=e}),t}function lp(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(D=>{D!==A.current&&(A.current=D,x(D))},[]),E=u.useCallback(D=>{D!==R.current&&(R.current=D,k(D))},[]),v=i||S,w=l||b,A=u.useRef(null),R=u.useRef(null),y=u.useRef(f),M=d!=null,O=po(d),T=po(o),L=po(c),I=u.useCallback(()=>{if(!A.current||!R.current)return;const D={placement:t,strategy:n,middleware:h};T.current&&(D.platform=T.current),sp(A.current,R.current,D).then($=>{const Q={...$,isPositioned:L.current!==!1};V.current&&!Or(y.current,Q)&&(y.current=Q,ns.flushSync(()=>{p(Q)}))})},[h,t,n,T,L]);jr(()=>{c===!1&&y.current.isPositioned&&(y.current.isPositioned=!1,p(D=>({...D,isPositioned:!1})))},[c]);const V=u.useRef(!1);jr(()=>(V.current=!0,()=>{V.current=!1}),[]),jr(()=>{if(v&&(A.current=v),w&&(R.current=w),v&&w){if(O.current)return O.current(v,w,I);I()}},[v,w,I,O,M]);const X=u.useMemo(()=>({reference:A,floating:R,setReference:C,setFloating:E}),[C,E]),J=u.useMemo(()=>({reference:v,floating:w}),[v,w]),W=u.useMemo(()=>{const D={position:n,left:0,top:0};if(!J.floating)return D;const $=vi(J.floating,f.x),Q=vi(J.floating,f.y);return a?{...D,transform:"translate("+$+"px, "+Q+"px)",...Qa(J.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:$,top:Q}},[n,a,J.floating,f.x,f.y]);return u.useMemo(()=>({...f,update:I,refs:X,elements:J,floatingStyles:W}),[f,I,X,J,W])}const cp=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?bi({element:r.current,padding:o}).fn(n):{}:r?bi({element:r,padding:o}).fn(n):{}}}},dp=(e,t)=>{const n=Zu(e);return{name:n.name,fn:n.fn,options:[e,t]}},up=(e,t)=>{const n=ep(e);return{name:n.name,fn:n.fn,options:[e,t]}},pp=(e,t)=>({fn:op(e).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=np(e);return{name:n.name,fn:n.fn,options:[e,t]}},mp=(e,t)=>{const n=rp(e);return{name:n.name,fn:n.fn,options:[e,t]}},gp=(e,t)=>{const n=cp(e);return{name:n.name,fn:n.fn,options:[e,t]}};var yp="Arrow",Ya=u.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...i}=e;return s.jsx(ke.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"})})});Ya.displayName=yp;var xp=Ya;function bp(e){const[t,n]=u.useState(void 0);return Pt(()=>{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 cs="Popper",[Xa,vn]=Nt(cs),[vp,Za]=Xa(cs),el=e=>{const{__scopePopper:t,children:n}=e,[r,o]=u.useState(null);return s.jsx(vp,{scope:t,anchor:r,onAnchorChange:o,children:n})};el.displayName=cs;var tl="PopperAnchor",nl=u.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Za(tl,n),l=u.useRef(null),a=je(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(ke.div,{...o,ref:a})});nl.displayName=tl;var ds="PopperContent",[Sp,kp]=Xa(ds),rl=u.forwardRef((e,t)=>{var re,ye,xe,Te,qe,Le;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=Za(ds,n),[k,C]=u.useState(null),E=je(t,Se=>C(Se)),[v,w]=u.useState(null),A=bp(v),R=(A==null?void 0:A.width)??0,y=(A==null?void 0:A.height)??0,M=r+(i!=="center"?"-"+i:""),O=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:O,boundary:T.filter(jp),altBoundary:L},{refs:V,floatingStyles:X,placement:J,isPositioned:W,middlewareData:D}=lp({strategy:"fixed",placement:M,whileElementsMounted:(...Se)=>Xu(...Se,{animationFrame:g==="always"}),elements:{reference:b.anchor},middleware:[dp({mainAxis:o+y,alignmentAxis:l}),d&&up({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?pp():void 0,...I}),d&&fp({...I}),hp({...I,apply:({elements:Se,rects:ue,availableWidth:Ne,availableHeight:Ue})=>{const{width:Oe,height:Me}=ue.reference,et=Se.floating.style;et.setProperty("--radix-popper-available-width",`${Ne}px`),et.setProperty("--radix-popper-available-height",`${Ue}px`),et.setProperty("--radix-popper-anchor-width",`${Oe}px`),et.setProperty("--radix-popper-anchor-height",`${Me}px`)}}),v&&gp({element:v,padding:a}),Cp({arrowWidth:R,arrowHeight:y}),h&&mp({strategy:"referenceHidden",...I})]}),[$,Q]=il(J),q=Ot(S);Pt(()=>{W&&(q==null||q())},[W,q]);const ee=(re=D.arrow)==null?void 0:re.x,H=(ye=D.arrow)==null?void 0:ye.y,B=((xe=D.arrow)==null?void 0:xe.centerOffset)!==0,[ne,ce]=u.useState();return Pt(()=>{k&&ce(window.getComputedStyle(k).zIndex)},[k]),s.jsx("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...X,transform:W?X.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ne,"--radix-popper-transform-origin":[(Te=D.transformOrigin)==null?void 0:Te.x,(qe=D.transformOrigin)==null?void 0:qe.y].join(" "),...((Le=D.hide)==null?void 0:Le.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:s.jsx(Sp,{scope:n,placedSide:$,onArrowChange:w,arrowX:ee,arrowY:H,shouldHideArrow:B,children:s.jsx(ke.div,{"data-side":$,"data-align":Q,...x,ref:E,style:{...x.style,animation:W?void 0:"none"}})})})});rl.displayName=ds;var ol="PopperArrow",wp={top:"bottom",right:"left",bottom:"top",left:"right"},sl=u.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,i=kp(ol,r),l=wp[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(xp,{...o,ref:n,style:{...o.style,display:"block"}})})});sl.displayName=ol;function jp(e){return e!==null}var Cp=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]=il(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 il(e){const[t,n="center"]=e.split("-");return[t,n]}var Ep=el,Gr=nl,us=rl,ps=sl,Ap="Portal",Yn=u.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,i]=u.useState(!1);Pt(()=>i(!0),[]);const l=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return l?Qd.createPortal(s.jsx(ke.div,{...r,ref:t}),l):null});Yn.displayName=Ap;function Tp(e,t){return u.useReducer((n,r)=>t[n][r]??n,e)}var st=e=>{const{present:t,children:n}=e,r=Rp(t),o=typeof n=="function"?n({present:r.isPresent}):u.Children.only(n),i=je(r.ref,_p(o));return typeof n=="function"||r.isPresent?u.cloneElement(o,{ref:i}):null};st.displayName="Presence";function Rp(e){const[t,n]=u.useState(),r=u.useRef(null),o=u.useRef(e),i=u.useRef("none"),l=e?"mounted":"unmounted",[a,d]=Tp(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]),Pt(()=>{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]),Pt(()=>{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 _p(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 $p=Da[" useInsertionEffect ".trim().toString()]||Pt;function fs({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,i,l]=Op({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=Pp(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 Op({defaultProp:e,onChange:t}){const[n,r]=u.useState(e),o=u.useRef(n),i=u.useRef(t);return $p(()=>{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 Pp(e){return typeof e=="function"}var Dp=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"}),Mp="VisuallyHidden",al=u.forwardRef((e,t)=>s.jsx(ke.span,{...e,ref:t,style:{...Dp,...e.style}}));al.displayName=Mp;var Ip=al,[Jr]=Nt("Tooltip",[vn]),Qr=vn(),ll="TooltipProvider",Lp=700,qo="tooltip.open",[Np,hs]=Jr(ll),cl=e=>{const{__scopeTooltip:t,delayDuration:n=Lp,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(Np,{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})};cl.displayName=ll;var Un="Tooltip",[Bp,Xn]=Jr(Un),dl=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:l,delayDuration:a}=e,d=hs(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]=fs({prop:r,defaultProp:o??!1,onChange:R=>{R?(d.onOpen(),document.dispatchEvent(new CustomEvent(qo))):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(Ep,{...c,children:s.jsx(Bp,{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})})};dl.displayName=Un;var Uo="TooltipTrigger",ul=u.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Xn(Uo,n),i=hs(Uo,n),l=Qr(n),a=u.useRef(null),d=je(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(ke.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)})})});ul.displayName=Uo;var ms="TooltipPortal",[Fp,zp]=Jr(ms,{forceMount:void 0}),pl=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,i=Xn(ms,t);return s.jsx(Fp,{scope:t,forceMount:n,children:s.jsx(st,{present:n||i.open,children:s.jsx(Yn,{asChild:!0,container:o,children:r})})})};pl.displayName=ms;var gn="TooltipContent",fl=u.forwardRef((e,t)=>{const n=zp(gn,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,l=Xn(gn,e.__scopeTooltip);return s.jsx(st,{present:r||l.open,children:l.disableHoverableContent?s.jsx(hl,{side:o,...i,ref:t}):s.jsx(qp,{side:o,...i,ref:t})})}),qp=u.forwardRef((e,t)=>{const n=Xn(gn,e.__scopeTooltip),r=hs(gn,e.__scopeTooltip),o=u.useRef(null),i=je(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=Hp(k,b.getBoundingClientRect()),E=Gp(k,C),v=Jp(x.getBoundingClientRect()),w=Yp([...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=!Qp(k,l);C?h():E&&(h(),c())};return document.addEventListener("pointermove",S),()=>document.removeEventListener("pointermove",S)}},[d,f,l,c,h]),s.jsx(hl,{...e,ref:i})}),[Up,Wp]=Jr(Un,{isInside:!1}),Kp=Xd("TooltipContent"),hl=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(qo,f),()=>document.removeEventListener(qo,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(us,{"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(Kp,{children:r}),s.jsx(Up,{scope:n,isInside:!0,children:s.jsx(Ip,{id:d.contentId,role:"tooltip",children:o||r})})]})})});fl.displayName=gn;var ml="TooltipArrow",Vp=u.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Qr(n);return Wp(ml,n).isInside?null:s.jsx(ps,{...o,...r,ref:t})});Vp.displayName=ml;function Hp(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 Gp(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 Jp(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 Qp(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 Yp(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),Xp(t)}function Xp(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 Zp=cl,ef=dl,tf=ul,nf=pl,rf=fl;function gl({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:i=200,container:l}){return s.jsxs(ef,{delayDuration:i,children:[s.jsx(tf,{asChild:!0,children:t}),s.jsx(nf,{container:l,children:s.jsx(rf,{side:n,align:r,sideOffset:o,style:{background:le("surfaceElevated"),color:le("textPrimary"),border:`1px solid ${le("borderDefault")}`,borderRadius:Lt.sm,padding:`${he[1]} ${he[2]}`,fontSize:Fe.sm,boxShadow:le("shadowMd"),zIndex:zn.tooltip,userSelect:"none"},children:e})})]})}const of=Zp;var fo="focusScope.autoFocusOnMount",ho="focusScope.autoFocusOnUnmount",Si={bubbles:!1,cancelable:!0},sf="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=Ot(o),f=Ot(i),p=u.useRef(null),h=je(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:$t(p.current,{select:!0})},b=function(E){if(g.paused||!a)return;const v=E.relatedTarget;v!==null&&(a.contains(v)||$t(p.current,{select:!0}))},k=function(E){if(document.activeElement===document.body)for(const w of E)w.removedNodes.length>0&&$t(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){wi.add(g);const x=document.activeElement;if(!a.contains(x)){const k=new CustomEvent(fo,Si);a.addEventListener(fo,c),a.dispatchEvent(k),k.defaultPrevented||(af(pf(yl(a)),{select:!0}),document.activeElement===x&&$t(a))}return()=>{a.removeEventListener(fo,c),setTimeout(()=>{const k=new CustomEvent(ho,Si);a.addEventListener(ho,f),a.dispatchEvent(k),k.defaultPrevented||$t(x??document.body,{select:!0}),a.removeEventListener(ho,f),wi.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]=lf(C);E&&v?!x.shiftKey&&k===v?(x.preventDefault(),n&&$t(E,{select:!0})):x.shiftKey&&k===E&&(x.preventDefault(),n&&$t(v,{select:!0})):k===C&&x.preventDefault()}},[n,r,g.paused]);return s.jsx(ke.div,{tabIndex:-1,...l,ref:h,onKeyDown:S})});Yr.displayName=sf;function af(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if($t(r,{select:t}),document.activeElement!==n)return}function lf(e){const t=yl(e),n=ki(t,e),r=ki(t.reverse(),e);return[n,r]}function yl(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 ki(e,t){for(const n of e)if(!cf(n,{upTo:t}))return n}function cf(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 df(e){return e instanceof HTMLInputElement&&"select"in e}function $t(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&df(e)&&t&&e.select()}}var wi=uf();function uf(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ji(e,t),e.unshift(t)},remove(t){var n;e=ji(e,t),(n=e[0])==null||n.resume()}}}function ji(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pf(e){return e.filter(t=>t.tagName!=="A")}var mo=0;function gs(){u.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Ci()),document.body.insertAdjacentElement("beforeend",e[1]??Ci()),mo++,()=>{mo===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),mo--}},[])}function Ci(){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 yt=function(){return yt=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},yt.apply(this,arguments)};function xl(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 ff(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",hf="with-scroll-bars-hidden",mf="--removed-body-scroll-bar-size";function go(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function gf(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 yf=typeof window<"u"?u.useLayoutEffect:u.useEffect,Ei=new WeakMap;function xf(e,t){var n=gf(null,function(r){return e.forEach(function(o){return go(o,r)})});return yf(function(){var r=Ei.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)})}Ei.set(n,e)},[e]),n}function bf(e){return e}function vf(e,t){t===void 0&&(t=bf);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 Sf(e){e===void 0&&(e={});var t=vf(null);return t.options=yt({async:!0,ssr:!1},e),t}var bl=function(e){var t=e.sideCar,n=xl(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,yt({},n))};bl.isSideCarExport=!0;function kf(e,t){return e.useMedium(t),bl}var vl=Sf(),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=xl(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),w=h,A=xf([n,t]),R=yt(yt({},v),o);return u.createElement(u.Fragment,null,f&&u.createElement(w,{sideCar:vl,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),yt(yt({},R),{ref:A})):u.createElement(C,yt({},R,{className:d,ref:A}),a))});Xr.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Xr.classNames={fullWidth:Er,zeroRight:Cr};var wf=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function jf(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=wf();return t&&e.setAttribute("nonce",t),e}function Cf(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Ef(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Af=function(){var e=0,t=null;return{add:function(n){e==0&&(t=jf())&&(Cf(t,n),Ef(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Tf=function(){var e=Af();return function(t,n){u.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Sl=function(){var e=Tf(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Rf={left:0,top:0,right:0,gap:0},xo=function(e){return parseInt(e||"",10)||0},_f=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)]},$f=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Rf;var t=_f(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])}},Of=Sl(),fn="data-scroll-locked",Pf=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(hf,` {
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(mf,": ").concat(a,`px;
46
- }
47
- `)},Ai=function(){var e=parseInt(document.body.getAttribute(fn)||"0",10);return isFinite(e)?e:0},Df=function(){u.useEffect(function(){return document.body.setAttribute(fn,(Ai()+1).toString()),function(){var e=Ai()-1;e<=0?document.body.removeAttribute(fn):document.body.setAttribute(fn,e.toString())}},[])},Mf=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;Df();var i=u.useMemo(function(){return $f(o)},[o]);return u.createElement(Of,{styles:Pf(i,!t,o,n?"":"!important")})},Wo=!1;if(typeof window<"u")try{var pr=Object.defineProperty({},"passive",{get:function(){return Wo=!0,!0}});window.addEventListener("test",pr,pr),window.removeEventListener("test",pr,pr)}catch{Wo=!1}var nn=Wo?{passive:!1}:!1,If=function(e){return e.tagName==="TEXTAREA"},kl=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!If(e)&&n[t]==="visible")},Lf=function(e){return kl(e,"overflowY")},Nf=function(e){return kl(e,"overflowX")},Ti=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=wl(e,r);if(o){var i=jl(e,r),l=i[1],a=i[2];if(l>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Bf=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},Ff=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},wl=function(e,t){return e==="v"?Lf(t):Nf(t)},jl=function(e,t){return e==="v"?Bf(t):Ff(t)},zf=function(e,t){return e==="h"&&t==="rtl"?-1:1},qf=function(e,t,n,r,o){var i=zf(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=jl(e,a),S=g[0],x=g[1],b=g[2],k=x-b-i*S;(S||k)&&wl(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]},Ri=function(e){return[e.deltaX,e.deltaY]},_i=function(e){return e&&"current"in e?e.current:e},Uf=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Wf=function(e){return`
48
- .block-interactivity-`.concat(e,` {pointer-events: none;}
49
- .allow-interactivity-`).concat(e,` {pointer-events: all;}
50
- `)},Kf=0,rn=[];function Vf(e){var t=u.useRef([]),n=u.useRef([0,0]),r=u.useRef(),o=u.useState(Kf++)[0],i=u.useState(Sl)[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=ff([e.lockRef.current],(e.shards||[]).map(_i),!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,O=M?M===A||M.contains(A):!1;if(O)return!1;var T=Ti(R,A);if(!T)return!0;if(T?w=R:(w=R==="v"?"h":"v",T=Ti(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 qf(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?Ri(b):fr(b),C=t.current.filter(function(w){return w.name===b.type&&(w.target===b.target||b.target===w.shadowParent)&&Uf(w.delta,k)})[0];if(C&&C.should){b.cancelable&&b.preventDefault();return}if(!C){var E=(l.current.shards||[]).map(_i).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:Hf(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,Ri(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:Wf(o)}):null,g?u.createElement(Mf,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Hf(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Gf=kf(vl,Vf);var Zr=u.forwardRef(function(e,t){return u.createElement(Xr,yt({},e,{ref:t,sideCar:Gf}))});Zr.classNames=Xr.classNames;var Jf=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,Cl=function(e){return e&&(e.host||Cl(e.parentNode))},Qf=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=Cl(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})},Yf=function(e,t,n,r){var o=Qf(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={})}},ys=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Jf(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Yf(r,o,n,"aria-hidden")):function(){return null}},eo="Dialog",[El]=Nt(eo),[Xf,ht]=El(eo),Al=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]=fs({prop:r,defaultProp:o??!1,onChange:i,caller:eo});return s.jsx(Xf,{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})};Al.displayName=eo;var Tl="DialogTrigger",Zf=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ht(Tl,n),i=je(t,o.triggerRef);return s.jsx(ke.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":vs(o.open),...r,ref:i,onClick:ie(e.onClick,o.onOpenToggle)})});Zf.displayName=Tl;var xs="DialogPortal",[eh,Rl]=El(xs,{forceMount:void 0}),_l=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=ht(xs,t);return s.jsx(eh,{scope:t,forceMount:n,children:u.Children.map(r,l=>s.jsx(st,{present:n||i.open,children:s.jsx(Yn,{asChild:!0,container:o,children:l})}))})};_l.displayName=xs;var Pr="DialogOverlay",$l=u.forwardRef((e,t)=>{const n=Rl(Pr,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=ht(Pr,e.__scopeDialog);return i.modal?s.jsx(st,{present:r||i.open,children:s.jsx(nh,{...o,ref:t})}):null});$l.displayName=Pr;var th=hn("DialogOverlay.RemoveScroll"),nh=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ht(Pr,n);return s.jsx(Zr,{as:th,allowPinchZoom:!0,shards:[o.contentRef],children:s.jsx(ke.div,{"data-state":vs(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Jt="DialogContent",Ol=u.forwardRef((e,t)=>{const n=Rl(Jt,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=ht(Jt,e.__scopeDialog);return s.jsx(st,{present:r||i.open,children:i.modal?s.jsx(rh,{...o,ref:t}):s.jsx(oh,{...o,ref:t})})});Ol.displayName=Jt;var rh=u.forwardRef((e,t)=>{const n=ht(Jt,e.__scopeDialog),r=u.useRef(null),o=je(t,n.contentRef,r);return u.useEffect(()=>{const i=r.current;if(i)return ys(i)},[]),s.jsx(Pl,{...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())})}),oh=u.forwardRef((e,t)=>{const n=ht(Jt,e.__scopeDialog),r=u.useRef(!1),o=u.useRef(!1);return s.jsx(Pl,{...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()}})}),Pl=u.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...l}=e,a=ht(Jt,n),d=u.useRef(null),c=je(t,d);return gs(),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":vs(a.open),...l,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx(ah,{titleId:a.titleId}),s.jsx(ch,{contentRef:d,descriptionId:a.descriptionId})]})]})}),bs="DialogTitle",Dl=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ht(bs,n);return s.jsx(ke.h2,{id:o.titleId,...r,ref:t})});Dl.displayName=bs;var Ml="DialogDescription",sh=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ht(Ml,n);return s.jsx(ke.p,{id:o.descriptionId,...r,ref:t})});sh.displayName=Ml;var Il="DialogClose",ih=u.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=ht(Il,n);return s.jsx(ke.button,{type:"button",...r,ref:t,onClick:ie(e.onClick,()=>o.onOpenChange(!1))})});ih.displayName=Il;function vs(e){return e?"open":"closed"}var Ll="DialogTitleWarning",[$1,Nl]=Gd(Ll,{contentName:Jt,titleName:bs,docsSlug:"dialog"}),ah=({titleId:e})=>{const t=Nl(Ll),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},lh="DialogDescriptionWarning",ch=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Nl(lh).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},dh=Al,uh=_l,ph=$l,fh=Ol,hh=Dl;function Bl(e){const t=e+"CollectionProvider",[n,r]=Nt(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=x=>{const{scope:b,children:k}=x,C=De.useRef(null),E=De.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=De.forwardRef((x,b)=>{const{scope:k,children:C}=x,E=i(a,k),v=je(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=De.forwardRef((x,b)=>{const{scope:k,children:C,...E}=x,v=De.useRef(null),w=je(b,v),A=i(f,k);return De.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 De.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 mh=u.createContext(void 0);function gh(e){const t=u.useContext(mh);return e||t||"ltr"}var vo="rovingFocusGroup.onEntryFocus",yh={bubbles:!1,cancelable:!0},Zn="RovingFocusGroup",[Ko,Fl,xh]=Bl(Zn),[bh,zl]=Nt(Zn,[xh]),[vh,Sh]=bh(Zn),ql=u.forwardRef((e,t)=>s.jsx(Ko.Provider,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Ko.Slot,{scope:e.__scopeRovingFocusGroup,children:s.jsx(kh,{...e,ref:t})})}));ql.displayName=Zn;var kh=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=je(t,h),S=gh(i),[x,b]=fs({prop:l,defaultProp:a??null,onChange:d,caller:Zn}),[k,C]=u.useState(!1),E=Ot(c),v=Fl(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(vh,{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(ke.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 O=new CustomEvent(vo,yh);if(y.currentTarget.dispatchEvent(O),!O.defaultPrevented){const T=v().filter(J=>J.focusable),L=T.find(J=>J.active),I=T.find(J=>J.id===x),X=[L,I,...T].filter(Boolean).map(J=>J.ref.current);Kl(X,f)}}w.current=!1}),onBlur:ie(e.onBlur,()=>C(!1))})})}),Ul="RovingFocusGroupItem",Wl=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=Sh(Ul,n),p=f.currentTabStopId===c,h=Fl(n),{onFocusableItemAdd:g,onFocusableItemRemove:S,currentTabStopId:x}=f;return u.useEffect(()=>{if(r)return g(),()=>S()},[r,g,S]),s.jsx(Ko.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:s.jsx(ke.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=Ch(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?Eh(E,v+1):E.slice(v+1)}setTimeout(()=>Kl(E))}}),children:typeof l=="function"?l({isCurrentTabStop:p,hasTabStop:x!=null}):l})})});Wl.displayName=Ul;var wh={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function jh(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Ch(e,t,n){const r=jh(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return wh[r]}function Kl(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Eh(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Ah=ql,Th=Wl,Vo=["Enter"," "],Rh=["ArrowDown","PageUp","Home"],Vl=["ArrowUp","PageDown","End"],_h=[...Rh,...Vl],$h={ltr:[...Vo,"ArrowRight"],rtl:[...Vo,"ArrowLeft"]},Oh={ltr:["ArrowLeft"],rtl:["ArrowRight"]},to="Menu",[Wn,Ph,Dh]=Bl(to),[Xt,Hl]=Nt(to,[Dh,vn,zl]),Ss=vn(),Gl=zl(),[O1,Zt]=Xt(to),[P1,er]=Xt(to),Mh="MenuAnchor",ks=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Ss(n);return s.jsx(Gr,{...o,...r,ref:t})});ks.displayName=Mh;var ws="MenuPortal",[Ih,Jl]=Xt(ws,{forceMount:void 0}),Ql=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Zt(ws,t);return s.jsx(Ih,{scope:t,forceMount:n,children:s.jsx(st,{present:n||i.open,children:s.jsx(Yn,{asChild:!0,container:o,children:r})})})};Ql.displayName=ws;var rt="MenuContent",[Lh,js]=Xt(rt),Yl=u.forwardRef((e,t)=>{const n=Jl(rt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Zt(rt,e.__scopeMenu),l=er(rt,e.__scopeMenu);return s.jsx(Wn.Provider,{scope:e.__scopeMenu,children:s.jsx(st,{present:r||i.open,children:s.jsx(Wn.Slot,{scope:e.__scopeMenu,children:l.modal?s.jsx(Nh,{...o,ref:t}):s.jsx(Bh,{...o,ref:t})})})})}),Nh=u.forwardRef((e,t)=>{const n=Zt(rt,e.__scopeMenu),r=u.useRef(null),o=je(t,r);return u.useEffect(()=>{const i=r.current;if(i)return ys(i)},[]),s.jsx(Cs,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ie(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Bh=u.forwardRef((e,t)=>{const n=Zt(rt,e.__scopeMenu);return s.jsx(Cs,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Fh=hn("MenuContent.ScrollLock"),Cs=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(rt,n),k=er(rt,n),C=Ss(n),E=Gl(n),v=Ph(n),[w,A]=u.useState(null),R=u.useRef(null),y=je(t,R,b.onContentChange),M=u.useRef(0),O=u.useRef(""),T=u.useRef(0),L=u.useRef(null),I=u.useRef("right"),V=u.useRef(0),X=S?Zr:u.Fragment,J=S?{as:Fh,allowPinchZoom:!0}:void 0,W=$=>{var re,ye;const Q=O.current+$,q=v().filter(xe=>!xe.disabled),ee=document.activeElement,H=(re=q.find(xe=>xe.ref.current===ee))==null?void 0:re.textValue,B=q.map(xe=>xe.textValue),ne=Xh(B,Q,H),ce=(ye=q.find(xe=>xe.textValue===ne))==null?void 0:ye.ref.current;(function xe(Te){O.current=Te,window.clearTimeout(M.current),Te!==""&&(M.current=window.setTimeout(()=>xe(""),1e3))})(Q),ce&&setTimeout(()=>ce.focus())};u.useEffect(()=>()=>window.clearTimeout(M.current),[]),gs();const D=u.useCallback($=>{var q,ee;return I.current===((q=L.current)==null?void 0:q.side)&&em($,(ee=L.current)==null?void 0:ee.area)},[]);return s.jsx(Lh,{scope:n,searchRef:O,onItemEnter:u.useCallback($=>{D($)&&$.preventDefault()},[D]),onItemLeave:u.useCallback($=>{var Q;D($)||((Q=R.current)==null||Q.focus(),A(null))},[D]),onTriggerLeave:u.useCallback($=>{D($)&&$.preventDefault()},[D]),pointerGraceTimerRef:T,onPointerGraceIntentChange:u.useCallback($=>{L.current=$},[]),children:s.jsx(X,{...J,children:s.jsx(Yr,{asChild:!0,trapped:o,onMountAutoFocus:ie(i,$=>{var Q;$.preventDefault(),(Q=R.current)==null||Q.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(Ah,{asChild:!0,...E,dir:k.dir,orientation:"vertical",loop:r,currentTabStopId:w,onCurrentTabStopIdChange:A,onEntryFocus:ie(d,$=>{k.isUsingKeyboardRef.current||$.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(us,{role:"menu","aria-orientation":"vertical","data-state":fc(b.open),"data-radix-menu-content":"",dir:k.dir,...C,...x,ref:y,style:{outline:"none",...x.style},onKeyDown:ie(x.onKeyDown,$=>{const q=$.target.closest("[data-radix-menu-content]")===$.currentTarget,ee=$.ctrlKey||$.altKey||$.metaKey,H=$.key.length===1;q&&($.key==="Tab"&&$.preventDefault(),!ee&&H&&W($.key));const B=R.current;if($.target!==B||!_h.includes($.key))return;$.preventDefault();const ce=v().filter(re=>!re.disabled).map(re=>re.ref.current);Vl.includes($.key)&&ce.reverse(),Qh(ce)}),onBlur:ie(e.onBlur,$=>{$.currentTarget.contains($.target)||(window.clearTimeout(M.current),O.current="")}),onPointerMove:ie(e.onPointerMove,Kn($=>{const Q=$.target,q=V.current!==$.clientX;if($.currentTarget.contains(Q)&&q){const ee=$.clientX>V.current?"right":"left";I.current=ee,V.current=$.clientX}}))})})})})})})});Yl.displayName=rt;var zh="MenuGroup",Es=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(ke.div,{role:"group",...r,ref:t})});Es.displayName=zh;var qh="MenuLabel",Xl=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(ke.div,{...r,ref:t})});Xl.displayName=qh;var Dr="MenuItem",$i="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=js(Dr,e.__scopeMenu),d=je(t,i),c=u.useRef(!1),f=()=>{const p=i.current;if(!n&&p){const h=new CustomEvent($i,{bubbles:!0,cancelable:!0});p.addEventListener($i,g=>r==null?void 0:r(g),{once:!0}),La(p,h),h.defaultPrevented?c.current=!1:l.onClose()}};return s.jsx(Zl,{...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===" "||Vo.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});no.displayName=Dr;var Zl=u.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,l=js(Dr,n),a=Gl(n),d=u.useRef(null),c=je(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(Th,{asChild:!0,...a,focusable:!r,children:s.jsx(ke.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))})})})}),Uh="MenuCheckboxItem",ec=u.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return s.jsx(sc,{scope:e.__scopeMenu,checked:n,children:s.jsx(no,{role:"menuitemcheckbox","aria-checked":Mr(n)?"mixed":n,...o,ref:t,"data-state":Ts(n),onSelect:ie(o.onSelect,()=>r==null?void 0:r(Mr(n)?!0:!n),{checkForDefaultPrevented:!1})})})});ec.displayName=Uh;var tc="MenuRadioGroup",[Wh,Kh]=Xt(tc,{value:void 0,onValueChange:()=>{}}),nc=u.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,i=Ot(r);return s.jsx(Wh,{scope:e.__scopeMenu,value:n,onValueChange:i,children:s.jsx(Es,{...o,ref:t})})});nc.displayName=tc;var rc="MenuRadioItem",oc=u.forwardRef((e,t)=>{const{value:n,...r}=e,o=Kh(rc,e.__scopeMenu),i=n===o.value;return s.jsx(sc,{scope:e.__scopeMenu,checked:i,children:s.jsx(no,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":Ts(i),onSelect:ie(r.onSelect,()=>{var l;return(l=o.onValueChange)==null?void 0:l.call(o,n)},{checkForDefaultPrevented:!1})})})});oc.displayName=rc;var As="MenuItemIndicator",[sc,Vh]=Xt(As,{checked:!1}),ic=u.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=Vh(As,n);return s.jsx(st,{present:r||Mr(i.checked)||i.checked===!0,children:s.jsx(ke.span,{...o,ref:t,"data-state":Ts(i.checked)})})});ic.displayName=As;var Hh="MenuSeparator",ac=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(ke.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});ac.displayName=Hh;var Gh="MenuArrow",lc=u.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=Ss(n);return s.jsx(ps,{...o,...r,ref:t})});lc.displayName=Gh;var Jh="MenuSub",[D1,cc]=Xt(Jh),_n="MenuSubTrigger",dc=u.forwardRef((e,t)=>{const n=Zt(_n,e.__scopeMenu),r=er(_n,e.__scopeMenu),o=cc(_n,e.__scopeMenu),i=js(_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(ks,{asChild:!0,...c,children:s.jsx(Zl,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":fc(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===" "||$h[r.dir].includes(p.key)&&(n.onOpenChange(!0),(g=n.content)==null||g.focus(),p.preventDefault())})})})});dc.displayName=_n;var uc="MenuSubContent",pc=u.forwardRef((e,t)=>{const n=Jl(rt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Zt(rt,e.__scopeMenu),l=er(rt,e.__scopeMenu),a=cc(uc,e.__scopeMenu),d=u.useRef(null),c=je(t,d);return s.jsx(Wn.Provider,{scope:e.__scopeMenu,children:s.jsx(st,{present:r||i.open,children:s.jsx(Wn.Slot,{scope:e.__scopeMenu,children:s.jsx(Cs,{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=Oh[l.dir].includes(f.key);p&&h&&(i.onOpenChange(!1),(g=a.trigger)==null||g.focus(),f.preventDefault())})})})})})});pc.displayName=uc;function fc(e){return e?"open":"closed"}function Mr(e){return e==="indeterminate"}function Ts(e){return Mr(e)?"indeterminate":e?"checked":"unchecked"}function Qh(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Yh(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Xh(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=Yh(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 Zh(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 em(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Zh(n,t)}function Kn(e){return t=>t.pointerType==="mouse"?e(t):void 0}var tm=ks,nm=Ql,rm=Yl,om=Es,sm=Xl,im=no,am=ec,lm=nc,cm=oc,dm=ic,um=ac,pm=lc,fm=dc,hm=pc,hc="DropdownMenu",[mm]=Nt(hc,[Hl]),Qe=Hl(),[M1,mc]=mm(hc),gc="DropdownMenuTrigger",gm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=mc(gc,n),l=Qe(n);return s.jsx(tm,{asChild:!0,...l,children:s.jsx(ke.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())})})})});gm.displayName=gc;var ym="DropdownMenuPortal",yc=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Qe(t);return s.jsx(nm,{...r,...n})};yc.displayName=ym;var xc="DropdownMenuContent",bc=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=mc(xc,n),i=Qe(n),l=u.useRef(!1);return s.jsx(rm,{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)"}})});bc.displayName=xc;var xm="DropdownMenuGroup",bm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(om,{...o,...r,ref:t})});bm.displayName=xm;var vm="DropdownMenuLabel",vc=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(sm,{...o,...r,ref:t})});vc.displayName=vm;var Sm="DropdownMenuItem",Sc=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(im,{...o,...r,ref:t})});Sc.displayName=Sm;var km="DropdownMenuCheckboxItem",wm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(am,{...o,...r,ref:t})});wm.displayName=km;var jm="DropdownMenuRadioGroup",Cm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(lm,{...o,...r,ref:t})});Cm.displayName=jm;var Em="DropdownMenuRadioItem",Am=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(cm,{...o,...r,ref:t})});Am.displayName=Em;var Tm="DropdownMenuItemIndicator",Rm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(dm,{...o,...r,ref:t})});Rm.displayName=Tm;var _m="DropdownMenuSeparator",kc=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(um,{...o,...r,ref:t})});kc.displayName=_m;var $m="DropdownMenuArrow",Om=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(pm,{...o,...r,ref:t})});Om.displayName=$m;var Pm="DropdownMenuSubTrigger",Dm=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(fm,{...o,...r,ref:t})});Dm.displayName=Pm;var Mm="DropdownMenuSubContent",Im=u.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qe(n);return s.jsx(hm,{...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)"}})});Im.displayName=Mm;var Lm=yc,Nm=bc,Bm=vc,Fm=Sc,zm=kc;const qm=u.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>s.jsx(Lm,{container:e,children:s.jsx(Nm,{ref:o,sideOffset:n,style:{minWidth:180,background:le("surfaceElevated"),color:le("textPrimary"),border:`1px solid ${le("borderDefault")}`,borderRadius:Lt.md,boxShadow:le("shadowMd"),padding:he[1],zIndex:zn.popover,...t},...r})}));qm.displayName="DropdownMenuContent";const Um=u.forwardRef(({style:e,...t},n)=>s.jsx(Fm,{ref:n,style:{display:"flex",alignItems:"center",gap:he[2],padding:`${he[1]} ${he[2]}`,fontSize:Fe.sm,borderRadius:Lt.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));Um.displayName="DropdownMenuItem";const Wm=u.forwardRef(({style:e,...t},n)=>s.jsx(zm,{ref:n,style:{height:1,background:le("borderSubtle"),margin:`${he[1]} 0`,...e},...t}));Wm.displayName="DropdownMenuSeparator";const Km=u.forwardRef(({style:e,...t},n)=>s.jsx(Bm,{ref:n,style:{padding:`${he[1]} ${he[2]}`,fontSize:Fe.xs,color:le("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));Km.displayName="DropdownMenuLabel";var wc="Popover",[jc]=Nt(wc,[vn]),ro=vn(),[I1,Bt]=jc(wc),Cc="PopoverAnchor",Vm=u.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Bt(Cc,n),i=ro(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:a}=o;return u.useEffect(()=>(l(),()=>a()),[l,a]),s.jsx(Gr,{...i,...r,ref:t})});Vm.displayName=Cc;var Ec="PopoverTrigger",Hm=u.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Bt(Ec,n),i=ro(n),l=je(t,o.triggerRef),a=s.jsx(ke.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":$c(o.open),...r,ref:l,onClick:ie(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?a:s.jsx(Gr,{asChild:!0,...i,children:a})});Hm.displayName=Ec;var Rs="PopoverPortal",[Gm,Jm]=jc(Rs,{forceMount:void 0}),Ac=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Bt(Rs,t);return s.jsx(Gm,{scope:t,forceMount:n,children:s.jsx(st,{present:n||i.open,children:s.jsx(Yn,{asChild:!0,container:o,children:r})})})};Ac.displayName=Rs;var yn="PopoverContent",Tc=u.forwardRef((e,t)=>{const n=Jm(yn,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Bt(yn,e.__scopePopover);return s.jsx(st,{present:r||i.open,children:i.modal?s.jsx(Ym,{...o,ref:t}):s.jsx(Xm,{...o,ref:t})})});Tc.displayName=yn;var Qm=hn("PopoverContent.RemoveScroll"),Ym=u.forwardRef((e,t)=>{const n=Bt(yn,e.__scopePopover),r=u.useRef(null),o=je(t,r),i=u.useRef(!1);return u.useEffect(()=>{const l=r.current;if(l)return ys(l)},[]),s.jsx(Zr,{as:Qm,allowPinchZoom:!0,children:s.jsx(Rc,{...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})})})}),Xm=u.forwardRef((e,t)=>{const n=Bt(yn,e.__scopePopover),r=u.useRef(!1),o=u.useRef(!1);return s.jsx(Rc,{...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()}})}),Rc=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=Bt(yn,n),g=ro(n);return gs(),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(us,{"data-state":$c(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)"}})})})}),_c="PopoverClose",Zm=u.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Bt(_c,n);return s.jsx(ke.button,{type:"button",...r,ref:t,onClick:ie(e.onClick,()=>o.onOpenChange(!1))})});Zm.displayName=_c;var eg="PopoverArrow",tg=u.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=ro(n);return s.jsx(ps,{...o,...r,ref:t})});tg.displayName=eg;function $c(e){return e?"open":"closed"}var ng=Ac,rg=Tc;const og=u.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>s.jsx(ng,{container:e,children:s.jsx(rg,{ref:o,sideOffset:n,style:{background:le("surfaceElevated"),color:le("textPrimary"),border:`1px solid ${le("borderDefault")}`,borderRadius:Lt.md,boxShadow:le("shadowMd"),padding:he[3],zIndex:zn.popover,minWidth:220,...t},...r})}));og.displayName="PopoverContent";function _s({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 Oc({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 Pc({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 sg({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 ${he[1]}px`,borderRadius:Lt.sm,border:`1px solid ${le("borderSubtle")}`,background:le("surfaceRaised"),color:le("textSecondary"),fontFamily:"var(--dql-font-mono, monospace)",fontSize:Fe.xs,fontWeight:ts.medium,lineHeight:1,whiteSpace:"nowrap",...n},children:e??t})}const Oi=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},ig=(e=>e?Oi(e):Oi),ag=e=>e;function lg(e,t=ag){const n=De.useSyncExternalStore(e.subscribe,De.useCallback(()=>t(e.getState()),[e,t]),De.useCallback(()=>t(e.getInitialState()),[e,t]));return De.useDebugValue(n),n}const Pi=e=>{const t=ig(e),n=r=>lg(t,r);return Object.assign(n,t),n},cg=(e=>e?Pi(e):Pi),Di=e=>Symbol.iterator in e,Mi=e=>"entries"in e,Ii=(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},dg=(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 ug(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:Di(e)&&Di(t)?Mi(e)&&Mi(t)?Ii(e,t):dg(e,t):Ii({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function pg(e){const t=De.useRef(void 0);return n=>{const r=e(n);return ug(t.current,r)?t.current:t.current=r}}const fg=/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g;function $s(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(fg)){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 hg(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 $s(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 mg(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||$s(i,t).some(l=>l.cellId===o)&&(n.add(i.id),r.push(i.id))}return n}function gg(){var e;if(typeof window<"u")try{(e=window.localStorage)==null||e.removeItem("dql-app-mode")}catch{}return"studio"}function yg(){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 xg(){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 bg={mainView:xg(),agentLogRun:void 0,settingsTab:"overview",themeMode:yg(),appMode:gg(),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 Ho(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=nt();while(t.has(r));return t.add(r),r===n.id?n:{...n,id:r}})}function vg(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:Ho(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:Ho(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:nt()}: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?mg(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 Go=cg((e,t)=>({...bg,dispatch:n=>{const r=vg(t(),n);e(r)}})),Sg=u.createContext(null);function kg({children:e}){return De.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")&&Go.getState().dispatch({type:"SET_THEME",mode:r})};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]),s.jsx(s.Fragment,{children:e})}function ve(){const e=Go(pg(r=>{const{dispatch:o,...i}=r;return i})),t=Go(r=>r.dispatch);return u.useContext(Sg)??{state:e,dispatch:t}}function nt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Os(e,t=""){const n={id:nt(),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 wg="modulepreload",jg=function(e){return"/"+e},Li={},Ce=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=jg(c),c in Li)return;Li[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":wg,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 Dc=(...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 Cg=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 Eg=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 Ni=e=>{const t=Eg(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 Ag={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 Tg=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 Rg=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,...Ag,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Dc("lucide",o),...!i&&!Tg(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 Y=(e,t)=>{const n=u.forwardRef(({className:r,...o},i)=>u.createElement(Rg,{ref:i,iconNode:t,className:Dc(`lucide-${Cg(Ni(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Ni(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 _g=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],$g=Y("arrow-down",_g);/**
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 Og=[["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"}]],Pg=Y("arrow-right-left",Og);/**
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 Dg=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Mg=Y("arrow-up",Dg);/**
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 Ig=[["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"}]],Ps=Y("blocks",Ig);/**
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 Lg=[["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"}]],Ng=Y("bookmark",Lg);/**
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 Bg=[["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"}]],Fg=Y("box",Bg);/**
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 zg=[["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"}]],Jo=Y("boxes",zg);/**
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 qg=[["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"}]],Ug=Y("briefcase",qg);/**
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 Wg=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Kg=Y("check",Wg);/**
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 Vg=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ds=Y("chevron-down",Vg);/**
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 Hg=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],oo=Y("chevron-right",Hg);/**
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 Gg=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],Jg=Y("chevrons-left",Gg);/**
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 Qg=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],Yg=Y("chevrons-right",Qg);/**
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 Xg=[["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"}]],Zg=Y("circle-alert",Xg);/**
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 ey=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Mc=Y("circle-check",ey);/**
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 ty=[["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"}]],ny=Y("circle-question-mark",ty);/**
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 ry=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],oy=Y("clock",ry);/**
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 sy=[["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"}]],iy=Y("command",sy);/**
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 ay=[["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=Y("database",ay);/**
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 ly=[["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"}]],Ic=Y("download",ly);/**
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 cy=[["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"}]],dy=Y("eye-off",cy);/**
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 uy=[["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"}]],Lc=Y("eye",uy);/**
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 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:"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"}]],fy=Y("file-braces",py);/**
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 hy=[["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"}]],my=Y("file-check",hy);/**
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 gy=[["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"}]],yy=Y("file-pen",gy);/**
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 xy=[["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"}]],Nc=Y("file-plus",xy);/**
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 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:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],vy=Y("file-question-mark",by);/**
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 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:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],ky=Y("file-spreadsheet",Sy);/**
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 wy=[["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"}]],Ms=Y("file-text",wy);/**
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 jy=[["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"}]],Cy=Y("file-x",jy);/**
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 Ey=[["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"}]],Ay=Y("files",Ey);/**
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 Ty=[["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"}]],Bc=Y("folder-open",Ty);/**
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 Ry=[["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=Y("folder",Ry);/**
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 _y=[["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"}]],$y=Y("funnel",_y);/**
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 Oy=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Py=Y("gauge",Oy);/**
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 Dy=[["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=Y("git-branch",Dy);/**
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 My=[["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"}]],Iy=Y("git-commit-horizontal",My);/**
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 Ly=[["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"}]],Ny=Y("git-fork",Ly);/**
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 By=[["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"}]],Is=Y("layers",By);/**
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 Fy=[["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"}]],zy=Y("layout-dashboard",Fy);/**
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 qy=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Fn=Y("loader-circle",qy);/**
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 Uy=[["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"}]],Wy=Y("message-circle",Uy);/**
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 Ky=[["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"}]],Vy=Y("monitor",Ky);/**
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 Hy=[["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"}]],Gy=Y("network",Hy);/**
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 Jy=[["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"}]],Qy=Y("notebook-pen",Jy);/**
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 Yy=[["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"}]],Xy=Y("package",Yy);/**
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 Zy=[["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"}]],ex=Y("palette",Zy);/**
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 tx=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],nx=Y("panel-left",tx);/**
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 rx=[["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"}]],ox=Y("plug",rx);/**
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 sx=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ix=Y("plus",sx);/**
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 ax=[["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=Y("refresh-cw",ax);/**
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 lx=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Bi=Y("search",lx);/**
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 cx=[["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"}]],dx=Y("settings-2",cx);/**
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 ux=[["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"}]],px=Y("settings",ux);/**
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 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:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],hx=Y("shield-alert",fx);/**
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 mx=[["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"}]],gx=Y("shield-check",mx);/**
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 yx=[["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"}]],xx=Y("sigma",yx);/**
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 bx=[["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"}]],Fc=Y("sparkles",bx);/**
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 vx=[["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"}]],Sx=Y("square-dashed",vx);/**
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 kx=[["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"}]],wx=Y("tag",kx);/**
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 jx=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Cx=Y("terminal",jx);/**
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 Ex=[["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"}]],zc=Y("trash-2",Ex);function Ax(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 Tx(e,t){const n=e.mode??"both";return n==="both"||n===t}function Rx({open:e,onClose:t}){const{state:n,dispatch:r}=ve(),[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",Ay],["Lineage","lineage",Ny],["Git","git",Sn],["Block Library","block_library",Ps],["Apps","apps",Gy],["Connections","connection",ox]],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:nx,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?dy:Lc,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:zy,shortcut:"⌘D",run:x(()=>g({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:Cx,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:Nc,mode:"studio",run:x(()=>g({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:Sx,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:ex,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=>Tx(x,n.appMode)).map(x=>({a:x,s:Ax(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(dh,{open:e,onOpenChange:g=>!g&&t(),children:s.jsxs(uh,{children:[s.jsx(ph,{style:{position:"fixed",inset:0,background:le("surfaceOverlay"),zIndex:zn.overlay}}),s.jsxs(fh,{"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:Lt.lg,boxShadow:le("shadowLg"),zIndex:zn.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:p,children:[s.jsx(hh,{style:{position:"absolute",left:-9999},children:"Command palette"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:he[2],padding:`${he[3]}px ${he[4]}px`,borderBottom:`1px solid ${le("borderSubtle")}`},children:[s.jsx(iy,{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:Fe.md}})]}),s.jsxs("div",{ref:d,style:{maxHeight:360,overflowY:"auto",padding:`${he[1]}px 0`},children:[f.length===0&&s.jsx("div",{style:{padding:he[4],fontSize:Fe.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(De.Fragment,{children:[x&&s.jsx("div",{style:{padding:`${he[2]}px ${he[4]}px ${he[1]}px`},children:s.jsx(Oc,{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:he[3],padding:`${he[2]}px ${he[4]}px`,fontSize:Fe.sm,cursor:"pointer",background:b?le("surfaceHover"):"transparent",color:le("textPrimary")},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:he[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(sg,{shortcut:g.shortcut})]})]},g.id)})]})]})]})})}function Qo(e){const t=Tt(e);if(!t)return;const n=Px(t.kind),r=_x(t.source);if(!n||!r)return;const o=Wx(t.limit);return{kind:n,source:r,name:ot(t.name),sourcePath:ot(t.sourcePath),metrics:Yo(t.metrics),dimensions:Yo(t.dimensions),filters:Dx(t.filters),timeDimension:Mx(t.timeDimension),orderBy:Ix(t.orderBy),parameters:Lx(t.parameters),parameterValues:zx(t.parameterValues),persistence:qx(t.persistence),trustState:Ux(t.trustState),compiledSql:ot(t.compiledSql),executionReceipt:Ox(t.executionReceipt),filterableColumns:$x(t.filterableColumns),...o===void 0?{}:{limit:o}}}function _x(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function $x(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Tt(n),o=ot(r==null?void 0:r.column),i=ot(r==null?void 0:r.predicateTarget);return o&&i?[{column:o,predicateTarget:i}]:[]});return t.length>0?t:void 0}function Ox(e){const t=Tt(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 Px(e){return e==="certified_block"||e==="semantic_block"||e==="sql_block"?e:void 0}function Dx(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Tt(n);if(!r)return[];const o=ot(r.dimension),i=ot(r.operator);return!o||!i?[]:[{dimension:o,operator:i,values:Yo(r.values)??[]}]});return t.length?t:void 0}function Mx(e){const t=Tt(e);if(!t)return;const n=ot(t.name),r=ot(t.granularity);return n&&r?{name:n,granularity:r}:void 0}function Ix(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Tt(n);if(!r)return[];const o=ot(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 Lx(e){if(!Array.isArray(e))return;const t=new Set,n=e.flatMap(r=>{const o=Tt(r),i=ot(o==null?void 0:o.name),l=Nx(o==null?void 0:o.type),a=Bx(o==null?void 0:o.policy);if(!o||!i||!l||!a||t.has(i))return[];t.add(i);const d=Fx(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 Nx(e){return e==="string"||e==="number"||e==="boolean"||e==="date"||e==="string[]"||e==="number[]"||e==="date[]"?e:void 0}function Bx(e){return e==="dynamic"||e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:void 0}function Fx(e){const t=Tt(e);if(!t)return;if(t.kind==="sql_value")return{kind:"sql_value"};if(t.kind==="limit")return{kind:"limit"};const n=ot(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 zx(e){const t=Tt(e);if(!t)return;const n=Object.entries(t).filter(([r])=>r.trim().length>0);return n.length?Object.fromEntries(n):void 0}function qx(e){return e==="transient"||e==="saved"?e:void 0}function Ux(e){return e==="certified"||e==="governed"||e==="review_required"?e:void 0}function Tt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ot(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Yo(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 Wx(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}const qc="dql_token",Fi="dql.server-token.v1";function Kx(e){var r;return((r=new URLSearchParams(e.replace(/^#/,"")).get(qc))==null?void 0:r.trim())||void 0}function Vx(e){const t=new URLSearchParams(e.replace(/^#/,""));t.delete(qc);const n=t.toString();return n?`#${n}`:""}function Hx(){var e;if(!(typeof window>"u"))try{const t=Kx(window.location.hash);if(t){window.sessionStorage.setItem(Fi,t);const n=Vx(window.location.hash);return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${n}`),t}return((e=window.sessionStorage.getItem(Fi))==null?void 0:e.trim())||void 0}catch{return}}const zi=Hx();function $n(e){const t=new Headers(e);return zi&&t.set("Authorization",`Bearer ${zi}`),t}const Gx={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 vt extends Error{constructor(n){super(n.message);Ee(this,"status");Ee(this,"code");Ee(this,"recoverable");Ee(this,"details");Ee(this,"nextActions");Ee(this,"requestId");Ee(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 Xo(e,t){const n=t.trim()||e.statusText||`HTTP ${e.status}`;if(!t.trim())return new vt({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 vt({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 vt({message:n,status:e.status})}}const So=new Map;async function j(e,t){if(((t==null?void 0:t.method)??"GET").toUpperCase()==="GET"&&!(t!=null&&t.signal)&&!(t!=null&&t.body)){const o=So.get(e);if(o)return o;const i=qi(e,t).finally(()=>{So.delete(e)});return So.set(e,i),i}return qi(e,t)}async function qi(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 Xo(n,o)}if(n.status!==204)return n.json()}async function Jx(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 wt(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:Qo(e==null?void 0:e.dqlArtifact),dqlPromotionAction:sb((e==null?void 0:e.dqlPromotionAction)??((n=e==null?void 0:e.dqlPromotion)==null?void 0:n.recommendedAction)),dqlPromotion:Uc(e==null?void 0:e.dqlPromotion),researchPlan:Qx(e==null?void 0:e.researchPlan),reviewChecklist:rb(e==null?void 0:e.reviewChecklist,e),...t?{resultPreview:t}:{resultPreview:void 0}}}function Qx(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:Yx(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:ge(n.evidenceCount),relationCount:ge(n.relationCount),missingContextCount:ge(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 Yx(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 ge(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function sn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Xx(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{totalReviewCount:ge(t.totalReviewCount),openReviewCount:ge(t.openReviewCount),terminalReviewCount:ge(t.terminalReviewCount),draftCreatedCount:ge(t.draftCreatedCount),certifiedCount:ge(t.certifiedCount),completedCount:ge(t.completedCount),rejectedCount:ge(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 Zx(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:ge(n.totalRuns),activeRuns:ge(n.activeRuns),closedRuns:ge(n.closedRuns),notebooks:ge(n.notebooks),domains:ge(n.domains),owners:ge(n.owners),sourceLinkedRuns:ge(n.sourceLinkedRuns)},health:{staleOpenRuns:ge(r.staleOpenRuns),expiredOpenRuns:ge(r.expiredOpenRuns),staleThresholdDays:ge(r.staleThresholdDays)||7,expiredThresholdDays:ge(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:ge(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:ge(l.pageSize)||25,maxPageSize:ge(l.maxPageSize)||500,sourceCoverageLimit:ge(l.sourceCoverageLimit)||1e4,seedCellLimit:ge(l.seedCellLimit)||1e3},warnings:Array.isArray(t.warnings)?t.warnings.filter(a=>typeof a=="string"):[]}}function eb(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 tb(e){const t=typeof e=="string"?e:"";return(t.split(/[\\/]/).pop()??t).replace(/\.dqlnb$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()||"Untitled notebook"}function nb(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 rb(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 ob(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 sb(e){return e==="reuse_existing"||e==="extend_existing"||e==="create_replacement"||e==="create_new"||e==="review_required"?e:void 0}function Uc(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:Gx,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 Xo(r,o)}return Jx(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 repairAgentRunExecution(e,t){return j(`/api/agent-runs/${encodeURIComponent(e)}/repair-execution`,{method:"POST",body:JSON.stringify({threadId: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 updateAgentThread(e,t){return j(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},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 addDqlArtifactResultFilter(e,t,n,r,o){const i=await j("/api/dql/artifacts/add-filter",{method:"POST",body:JSON.stringify({artifact:e,resultColumns:t,column:n,value:r,executionTarget:o})}),l=Qo(i==null?void 0:i.artifact);if(!l)throw new Error("Adding the filter input returned an invalid artifact contract.");return{artifact:l,parameterName:String((i==null?void 0:i.parameterName)??n)}},async invokeDqlArtifact(e,t,n,r,o){var a,d,c,f,p,h;const i=await j("/api/dql/artifacts/execute",{method:"POST",body:JSON.stringify({artifact:e,parameters:t,question:n,blockName:r,executionTarget:o})}),l=Qo(i==null?void 0:i.artifact);if(!l)throw new Error("DQL artifact execution returned an invalid artifact contract.");return{artifact:l,parameters:l.parameters??[],result:{...cn(i==null?void 0:i.result),...typeof((a=i==null?void 0:i.result)==null?void 0:a.sql)=="string"?{sql:i.result.sql}:{},...typeof((d=i==null?void 0:i.result)==null?void 0:d.blockName)=="string"?{blockName:i.result.blockName}:{},...typeof((c=i==null?void 0:i.result)==null?void 0:c.blockPath)=="string"?{blockPath:i.result.blockPath}:{},...(f=i==null?void 0:i.result)!=null&&f.chartConfig?{chartConfig:i.result.chartConfig}:{},...Array.isArray((p=i==null?void 0:i.result)==null?void 0:p.parameters)?{parameters:i.result.parameters}:{},...typeof((h=i==null?void 0:i.result)==null?void 0:h.auditId)=="string"?{auditId:i.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 vt({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 vt({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 Xo(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(wt),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:eb(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:tb(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:nb((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:Xx(r.reviewMetrics),limit:r.limit,offset:typeof r.offset=="number"?r.offset:0}},async getNotebookResearchDiagnostics(){const e=await j("/api/notebook/research/diagnostics");return Zx(e)},async createNotebookResearch(e){const t=await j("/api/notebook/research",{method:"POST",body:JSON.stringify(e)});return wt(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(wt):[],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(wt):[],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 ob(t)},async getNotebookResearch(e){const t=await j(`/api/notebook/research/${encodeURIComponent(e)}`);return wt(t.run)},async updateNotebookResearch(e,t){const n=await j(`/api/notebook/research/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});return wt(n.run)},async runNotebookResearch(e,t){const n=await j(`/api/notebook/research/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t??{})});return wt(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:wt(n.run),promotion:Uc(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:wt(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 vt?{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})})}},ib={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"},ab={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"},Wc={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"},L1={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"},N1={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"},lb={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Ui={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Wi=["source","transform","answer","consumption"],B1=["term","business_view","block","metric","dimension","domain","source_table","dbt_source","dbt_model","chart","notebook","dashboard","app"],F1=["source_table","dbt_source","dbt_model"],cb=["term","domain","business_view","metric","dimension","block"];[...cb];function db(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 ub(){const{state:e,dispatch:t}=ve(),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:`${he[3]}px ${he[4]}px`,borderBottom:`1px solid ${le("borderSubtle")}`},children:[s.jsx("div",{style:{fontSize:Fe.sm,fontWeight:ts.semibold},children:n?pb(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:Fe.md,padding:2,borderRadius:Lt.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:he[4]},children:n?s.jsx(fb,{context:n}):s.jsx(yb,{})})]})}function pb(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function fb({context:e}){return e.kind==="cell"?s.jsx(hb,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx(mb,{nodeId:e.nodeId}):s.jsx(gb,{name:e.name})}function hb({cellId:e}){const{state:t}=ve(),n=t.cells.find(r=>r.id===e);return n?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:he[3],fontSize:Fe.sm},children:[s.jsx(Ae,{label:"Type",children:n.type}),s.jsx(Ae,{label:"ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),s.jsxs(Ae,{label:"Length",children:[n.content.length," chars"]}),n.status&&s.jsx(Ae,{label:"Status",children:n.status})]}):s.jsx(Lr,{children:"No matching cell in the active notebook."})}function mb({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:he[3]},children:[s.jsx(Ae,{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:he[3]},children:[s.jsx(Ae,{label:"Name",children:i.name??e}),s.jsx(Ae,{label:"Type",children:Wc[i.type]??i.type}),i.domain&&s.jsx(Ae,{label:"Domain",children:i.domain}),i.owner&&s.jsx(Ae,{label:"Owner",children:i.owner}),i.status&&s.jsx(Ae,{label:"Status",children:i.status}),typeof l.termType=="string"&&s.jsx(Ae,{label:"Term Type",children:l.termType}),typeof l.description=="string"&&s.jsx(Ae,{label:"Description",children:l.description}),Array.isArray(l.identifiers)&&l.identifiers.length>0&&s.jsx(Ae,{label:"Identifiers",children:l.identifiers.map(String).join(", ")}),Array.isArray(l.synonyms)&&l.synonyms.length>0&&s.jsx(Ae,{label:"Synonyms",children:l.synonyms.map(String).join(", ")}),typeof l.businessOutcome=="string"&&s.jsx(Ae,{label:"Business Outcome",children:l.businessOutcome}),i.layer&&s.jsx(Ae,{label:"Layer",children:i.layer}),s.jsx(Ae,{label:"Upstream",children:t.incoming.length}),s.jsx(Ae,{label:"Downstream",children:t.outgoing.length}),(i.path||l.filePath)&&s.jsx(Ae,{label:"Path",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Fe.xs},children:i.path??l.filePath})})]})}function gb({name:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:he[3]},children:[s.jsx(Ae,{label:"Metric",children:e}),s.jsx(Lr,{children:"Definition, dimensions, and governance surface will render here."})]})}function Ae({label:e,children:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[s.jsx("div",{style:{fontSize:Fe.xs,color:le("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:ts.medium},children:e}),s.jsx("div",{style:{fontSize:Fe.sm,color:le("textPrimary")},children:t})]})}function Lr({children:e}){return s.jsx("div",{style:{fontSize:Fe.sm,color:le("textSecondary"),lineHeight:1.5,background:le("surfaceSunken"),border:`1px solid ${le("borderSubtle")}`,borderRadius:Lt.md,padding:he[3]},children:e})}function yb(){return s.jsx("div",{style:{fontSize:Fe.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"},Ki={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 Vi(e){if(typeof document>"u")return Ki[e];const t=Pn[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||Ki[e]}function xb(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Pn)return Vi(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:Vi(t)}}})}const Kt=xb(),ze={obsidian:Kt,paper:Kt,white:Kt,dark:Kt,light:Kt,midnight:Kt,arctic:Kt};function it(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 bb=it(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"})]}));it(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 vb=it(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"})]})),z1=it(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"})]}));it(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),s.jsx("path",{d:"M16 20l4 4"})]}));it(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 3v18h18"}),s.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]}));it(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"})]}));it(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 q1=it(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),s.jsx("circle",{cx:"18",cy:"17",r:"2"})]}));it(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));it(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"})]}));it(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 Kc=44,Vc=188,Hc="dql-activitybar-expanded";function Sb(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(Hc))==="1"}catch{return!1}}function kb(e){var t;try{(t=window.localStorage)==null||t.setItem(Hc,e?"1":"0")}catch{}}function Hi({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?Vc-12:Kc-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(gl,{content:e,side:"right",children:d})}function wb(){const{state:e,dispatch:t}=ve(),n=ze[e.themeMode],[r,o]=u.useState(Sb);u.useEffect(()=>{kb(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(Xy,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"ask",title:"Ask",icon:s.jsx(Wy,{size:16,strokeWidth:1.75}),active:e.mainView==="ask"}]},{label:"Build",items:[{key:"files",title:"Notebooks",icon:s.jsx(Ms,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"block_library",title:"Blocks",icon:s.jsx(bb,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(vb,{size:16}),active:e.mainView==="lineage"||e.mainView==="lineage_detail"}]},{label:"Govern",items:[{key:"domains",title:"Domains",icon:s.jsx(Jo,{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(px,{size:16,strokeWidth:1.75}),active:e.mainView==="settings"||e.mainView==="connection"}]}],a=[{key:"help",title:"Help",icon:s.jsx(ny,{size:16,strokeWidth:1.75}),active:e.mainView==="help",onClick:()=>t({type:"SET_MAIN_VIEW",view:"help"})}];return s.jsxs("div",{style:{width:r?Vc:Kc,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(gl,{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(Jg,{size:14,strokeWidth:2}):s.jsx(Yg,{size:14,strokeWidth:2})})})}),l.map((d,c)=>s.jsxs(De.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(Hi,{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(Hi,{title:d.title,icon:d.icon,active:d.active,expanded:r,onClick:d.onClick,t:n},d.key))]})}const jb=2e4,U1="application/dql-semantic-ref",Gi=new Map;let Vn=null;function Cb(e){N.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function Ji(e,t){const n=`${e}:${t.toLowerCase()}`,r=Gi.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 Gi.set(n,{items:a,expiresAt:Date.now()+jb}),a}function Gc(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 W1(e){Vn=e}function K1(e){Vn===e&&(Vn=null)}function Eb(e){return Vn?(Gc(Vn,e),!0):!1}function V1(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;Gc(e,t,r)}function Qi(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}}),Cb(e.name)}}}function Ab(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 H1=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 Ji("metric",a);return{from:d,options:c.map(f=>Qi(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 Ji("dimension",a);return{from:d,options:c.map(f=>Qi(f,d,n)),validFor:/^[\w-]*$/}}const l=/@([md][a-z_]*)?$/i.exec(r);return l?Ab(n-l[0].length):(e.explicit,null)};function G1(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 Tb=6,Rb=999,_b={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 we(e,t={}){const{variant:n="secondary",size:r="sm",active:o=!1,disabled:i=!1,pill:l=!1}=t,a=_b[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?Rb:Tb,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 Jc(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 $b({table:e,colors:t,size:n=13}){const r=Jc(e),o=t[r.tone],i={size:n,color:o,strokeWidth:2,style:{flexShrink:0}},l=r.kind==="csv"?s.jsx(ky,{...i}):r.kind==="json"?s.jsx(fy,{...i}):r.kind==="parquet"||r.kind==="staged"?s.jsx(Is,{...i}):r.kind==="view"?s.jsx(Lc,{...i}):s.jsx(tr,{...i});return s.jsx("span",{"aria-label":r.title,title:r.title,style:{display:"inline-flex"},children:l})}const Ob=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 Zo(e){const t=so(e);return e.kind==="metric"||e.kind==="measure"?`@metric(${t})`:`@dim(${t})`}function Qc(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 Ls(e,t){return!t||e.label.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||so(e).toLowerCase().includes(t)||Qc(e).toLowerCase().includes(t)?!0:(e.children??[]).some(n=>Ls(n,t))}function Yc(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:${Zo(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=Yc(o.children));return t}const ko={metric:{Icon:Py,tone:e=>e.accent},measure:{Icon:xx,tone:e=>e.accent},dimension:{Icon:wx,tone:e=>e.success},time_dimension:{Icon:oy,tone:e=>e.warning},entity:{Icon:Fg,tone:e=>e.textSecondary},segment:{Icon:$y,tone:e=>e.textMuted},hierarchy:{Icon:Sn,tone:e=>e.textMuted},pre_aggregation:{Icon:Is,tone:e=>e.textMuted},cube:{Icon:Jo,tone:e=>e.textSecondary},semantic_model:{Icon:Jo,tone:e=>e.textSecondary},saved_query:{Icon:Ng,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 Pb(e){var t;if(e.kind==="group"){const n=typeof((t=e.meta)==null?void 0:t.objectKind)=="string"?e.meta.objectKind:"";return ko[n]??ko.group}return ko[e.kind]}function Db({tree:e,themeMode:t,search:n="",onInsert:r,selectionMode:o=!1,selected:i=new Set,onToggleSelection:l,canSelect:a=()=>({allowed:!0})}){const d=ze[t],c=n.trim().toLowerCase(),f=Yc(e.children??[]).filter(p=>Ls(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(Xc,{node:p,t:d,q:c,onInsert:r,depth:0,selectionMode:o,selected:i,onToggleSelection:l,canSelect:a},p.id))})}function Xc({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=Ob.has(e.kind),g=Pb(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=Qc(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(Zo(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 ${Zo(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=>Ls(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(Ds,{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(Xc,{node:y,t,q:n,onInsert:r,depth:o+1,selectionMode:i,selected:l,onToggleSelection:a,canSelect:d},y.id))]})}function Mb(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 Ib(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 K;(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"})(K||(K={}));var dn;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(dn||(dn={}));class Lb{constructor(){Ee(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=>Nb(n,t)).join(`
408
-
409
- `)}}function Nb(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 Bb extends Error{constructor(n,r){super(n);Ee(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 Fb={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 zb(e){return Fb[e]??m.Identifier}const wo=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"]),qb={"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 Ub(e){return qb[e]??e}const jo=new Set(["dropdown","date_range","text","multi_select","range"]),Wb=new Set(["SELECT","WITH"]);class Nr{constructor(t,n){Ee(this,"source");Ee(this,"pos",0);Ee(this,"line",1);Ee(this,"column",1);Ee(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=zb(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 Kb=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"]),Vb=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 Hb(e){return Kb.has(e)}function Gb(e){return Vb.has(e)}class Jb{constructor(t,n){Ee(this,"tokens");Ee(this,"pos",0);Ee(this,"source");Ee(this,"file");Ee(this,"reporter");this.source=t,this.file=n,this.reporter=new Lb;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 Bb(`Parse errors in ${this.file??"<input>"}`,this.reporter.getErrors());return{kind:K.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);jo.has(n.value)||this.reporter.error(`Unknown filter type '${n.value}'. Valid types: ${[...jo].join(", ")}`,n.span,`Did you mean one of: ${[...jo].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:K.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:K.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:K.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:K.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());wo.has(i)||this.reporter.error(`Unknown chart type '${i}'. Valid types: ${[...wo].join(", ")}`,l,`Did you mean one of: ${[...wo].join(", ")}?`);const a=Ub(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:K.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:K.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:K.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:K.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:K.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:K.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:K.StringLiteral,value:t.value,span:t.span};if(this.check(m.NumberLiteral))return this.advance(),{kind:K.NumberLiteral,value:Number(t.value),span:t.span};if(this.check(m.BooleanLiteral))return this.advance(),{kind:K.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:K.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:K.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:K.NumberLiteral,value:-Number(r.value),span:this.makeSpan(n,r.span)}}return this.error(`Unexpected token '${t.value}'. Expected an expression.`),this.advance(),{kind:K.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:K.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:K.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:K.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:K.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:K.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:K.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:K.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!==K.ArrayLiteral?[]:t.elements.filter(n=>n.kind===K.StringLiteral).map(n=>n.value)}parseBlockDecl(t){var kt;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,O,T,L,I,V,X,J,W,D,$,Q,q,ee,H,B,ne,ce,re,ye,xe,Te,qe,Le,Se,ue,Ne,Ue,Oe,Me,et,mt,at,tt,Rt,zt,qt,Ut,F,te,be,fe,de;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 G=this.expect(m.StringLiteral).value;G==="semantic"||G==="custom"?i=G:(this.error(`Block type must be "semantic" or "custom", got "${G}". 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 se=this.parseArrayLiteral();se.kind===K.ArrayLiteral&&(a=se.elements.filter(G=>G.kind===K.StringLiteral).map(G=>G.value))}else if(this.check(m.DimensionsKeyword)){this.advance(),this.expect(m.Equals);const se=this.parseArrayLiteral();se.kind===K.ArrayLiteral&&(d=se.elements.filter(G=>G.kind===K.StringLiteral).map(G=>G.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 se=this.parseArrayLiteral();se.kind===K.ArrayLiteral&&(f=se.elements.filter(G=>G.kind===K.StringLiteral).map(G=>G.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 se=this.advance();this.expect(m.Equals),se.value==="pattern"?g=this.expect(m.StringLiteral).value:se.value==="grain"?S=this.expect(m.StringLiteral).value:se.value==="entities"?x=this.parseStringArrayValues():se.value==="outputs"?b=this.parseStringArrayValues():se.value==="allowedFilters"?k=this.parseStringArrayValues():se.value==="sourceSystems"?v=this.parseStringArrayValues():se.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 se=this.advance(),G=this.extractInterpolations(se.value,se.span);R={kind:K.SQLQuery,rawSQL:se.value,interpolations:G,span:se.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),$=this.expect(m.StringLiteral).value;else if(this.check(m.Identifier)&&this.current().value==="datalex_contract")this.advance(),this.expect(m.Equals),Q=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 se=this.advance();this.expect(m.Equals);const G=this.expect(m.NumberLiteral);se.value==="asked_times"?q=Number(G.value):se.value==="limit"?qt=Number(G.value):fe=Number(G.value)}else if(this.check(m.Identifier)&&Hb(this.current().value)){const se=this.advance();this.expect(m.Equals);const G=this.expect(m.StringLiteral);switch(se.value){case"first_asked":ee=G.value;break;case"last_asked":H=G.value;break;case"proposed_contract_id":B=G.value;break;case"proposed_domain":ne=G.value;break;case"proposed_entity":ce=G.value;break;case"source_question":re=G.value;break;case"source_block":ye=G.value;break;case"source_dql_kind":xe=G.value;break;case"source_dql_name":Te=G.value;break;case"source_dql_path":qe=G.value;break;case"source_dql_hash":Le=G.value;break;case"source_dql_time_dimension":Se=G.value;break;case"source_dql_granularity":ue=G.value;break;case"followup_kind":Ne=G.value;break;case"context_pack_id":Ue=G.value;break;case"route_intent":Oe=G.value;break;case"time_dimension":Me=G.value;break;case"granularity":et=G.value;break;case"draft_path":mt=G.value;break}}else if(this.check(m.Identifier)&&Gb(this.current().value)){const se=this.advance();this.expect(m.Equals);const G=this.parseStringArrayValues();switch(se.value){case"upstream_refs":at=G;break;case"requested_filters":tt=G;break;case"requested_dimensions":Rt=G;break;case"order_by":zt=G;break;case"source_dql_metrics":Ut=G;break;case"source_dql_dimensions":F=G;break;case"source_dql_filters":te=G;break;case"source_dql_order_by":be=G;break;case"validation_warnings":de=G;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 se=this.advance();if(this.expect(m.Equals),se.value==="llmContext")O=this.expect(m.StringLiteral).value;else if(se.value==="invariants"){const G=this.parseArrayLiteral();G.kind===K.ArrayLiteral&&(T=G.elements.filter(Re=>Re.kind===K.StringLiteral).map(Re=>Re.value))}else if(se.value==="examples"){this.expect(m.LeftBracket);const G=[];for(;!this.check(m.RightBracket)&&!this.isAtEnd();){this.expect(m.LeftBrace);let Re,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"?Re=nr.value:en.value==="sql"&&(wn=nr.value),this.check(m.Comma)&&this.advance()}this.expect(m.RightBrace),Re&&G.push(wn?{question:Re,sql:wn}:{question:Re}),this.check(m.Comma)&&this.advance()}this.expect(m.RightBracket),G.length>0&&(L=G)}else if(se.value==="businessOutcome")I=this.expect(m.StringLiteral).value;else if(se.value==="businessOwner")V=this.expect(m.StringLiteral).value;else if(se.value==="decisionUse")X=this.expect(m.StringLiteral).value;else if(se.value==="reviewCadence")J=this.expect(m.StringLiteral).value;else if(se.value==="businessRules"){const G=this.parseArrayLiteral();G.kind===K.ArrayLiteral&&(W=G.elements.filter(Re=>Re.kind===K.StringLiteral).map(Re=>Re.value))}else if(se.value==="caveats"){const G=this.parseArrayLiteral();G.kind===K.ArrayLiteral&&(D=G.elements.filter(Re=>Re.kind===K.StringLiteral).map(Re=>Re.value))}}else{if(this.check(m.Identifier)&&((kt=this.tokens[this.pos+1])==null?void 0:kt.type)===m.LeftBrace){const se=this.current().value;this.error(`Unexpected nested section '${se}' 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:K.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:O,invariants:T,examples:L,businessOutcome:I,businessOwner:V,decisionUse:X,reviewCadence:J,businessRules:W,caveats:D,status:$,datalexContract:Q,askedTimes:q,firstAsked:ee,lastAsked:H,proposedContractId:B,proposedDomain:ne,proposedEntity:ce,sourceQuestion:re,sourceBlock:ye,sourceDqlKind:xe,sourceDqlName:Te,sourceDqlPath:qe,sourceDqlHash:Le,sourceDqlTimeDimension:Se,sourceDqlGranularity:ue,followupKind:Ne,contextPackId:Ue,routeIntent:Oe,timeDimension:Me,granularity:et,draftPath:mt,upstreamRefs:at,requestedFilters:tt,requestedDimensions:Rt,orderBy:zt,limit:qt,sourceDqlMetrics:Ut,sourceDqlDimensions:F,sourceDqlFilters:te,sourceDqlOrderBy:be,sourceDqlLimit:fe,validationWarnings:de,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:K.SQLQuery,rawSQL:r.value,interpolations:o,span:r.span}}else n=this.parseSQLQuery();else this.check(m.Identifier)&&Wb.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:K.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:K.NamedArg,name:o.value,value:i,span:this.makeSpan(r,this.previousSpan())})}return this.expect(m.RightBrace),{kind:K.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:K.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:K.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:K.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:K.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:K.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:K.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===K.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:K.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:K.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 Qb(e,t){return new Jb(e,t).parse()}function Yb(e,t={}){const n=Qb(e);return Xb(n,t)}function Xb(e,t={}){const n={indentUnit:t.indent??" "},r=e.statements.map(o=>Zb(o,0,n)).join(`
421
-
422
- `).trimEnd();return t.finalNewline===!1?r:`${r}
423
- `}function P(e,t){return t.indentUnit.repeat(e)}function Zb(e,t,n){switch(e.kind){case K.Dashboard:return ev(e,t,n);case K.ChartCall:return Bs(e,t,n);case K.Workbook:return rv(e,t,n);case K.ImportDecl:return sv(e,t,n);case K.DomainDecl:return pv(e,t,n);case K.BlockDecl:return uv(e,t,n);case K.TermDecl:return fv(e,t,n);case K.BusinessViewDecl:return hv(e,t,n);case K.Digest:return tv(e,t,n);default:return""}}function ev(e,t,n){const r=[];r.push(...Ft(e.decorators,t,n)),r.push(`${P(t,n)}dashboard ${U(e.title)} {`);for(const o of e.body)r.push(Ns(o,t+1,n));return r.push(`${P(t,n)}}`),r.join(`
424
- `)}function tv(e,t,n){const r=[];r.push(...Ft(e.decorators,t,n)),r.push(`${P(t,n)}digest ${U(e.title)} {`),e.narrative&&r.push(nv(e.narrative,t+1,n));for(const o of e.body)r.push(Ns(o,t+1,n));return r.push(`${P(t,n)}}`),r.join(`
425
- `)}function nv(e,t,n){const r=[];r.push(`${P(t,n)}narrative {`);for(const o of e.properties)r.push(`${P(t+1,n)}${Fs(o)}`);return r.push(`${P(t,n)}}`),r.join(`
426
- `)}function rv(e,t,n){const r=[];r.push(...Ft(e.decorators,t,n)),r.push(`${P(t,n)}workbook ${U(e.title)} {`);for(const o of e.pages)r.push(ov(o,t+1,n));return r.push(`${P(t,n)}}`),r.join(`
427
- `)}function ov(e,t,n){const r=[];r.push(`${P(t,n)}page ${U(e.title)} {`);for(const o of e.body)r.push(Ns(o,t+1,n));return r.push(`${P(t,n)}}`),r.join(`
428
- `)}function Ns(e,t,n){switch(e.kind){case K.VariableDecl:return av(e,t,n);case K.ParamDecl:return lv(e,t,n);case K.ChartCall:return Bs(e,t,n);case K.FilterCall:return Zc(e,t,n);case K.UseDecl:return iv(e,t,n);case K.LayoutBlock:return cv(e,t,n);default:return""}}function sv(e,t,n){return`${P(t,n)}import { ${e.names.join(", ")} } from ${U(e.path)}`}function iv(e,t,n){const r=/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.name);return`${P(t,n)}use ${r?e.name:U(e.name)}`}function av(e,t,n){return`${P(t,n)}let ${e.name} = ${ut(e.initializer)}`}function lv(e,t,n){const r=`: ${e.paramType}`,o=e.defaultValue?` = ${ut(e.defaultValue)}`:"";return`${P(t,n)}param ${e.name}${r}${o}`}function Ft(e,t,n){return e.map(r=>{if(r.arguments.length===0)return`${P(t,n)}@${r.name}`;const o=r.arguments.map(i=>ut(i)).join(", ");return`${P(t,n)}@${r.name}(${o})`})}function Bs(e,t,n){return ed(`chart.${e.chartType}`,e.decorators,e.query,e.args,t,n)}function Zc(e,t,n){return ed(`filter.${e.filterType}`,[],e.query,e.args,t,n)}function ed(e,t,n,r,o,i){const l=[];l.push(...Ft(t,o,i)),l.push(`${P(o,i)}${e}(`);const a=[];n&&a.push(td(n,o+1,i));for(const d of r)a.push([`${P(o+1,i)}${Fs(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(`${P(o,i)})`),l.join(`
429
- `)}function cv(e,t,n){const r=[];r.push(`${P(t,n)}layout(columns = ${e.columns}) {`);for(const o of e.rows)r.push(dv(o,t+1,n));return r.push(`${P(t,n)}}`),r.join(`
430
- `)}function dv(e,t,n){const r=[];r.push(`${P(t,n)}row {`);for(const o of e.items){const i=o.node.kind===K.ChartCall?Bs(o.node,t+1,n):Zc(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(`${P(t,n)}}`),r.join(`
433
- `)}function uv(e,t,n){const r=[];if(r.push(...Ft(e.decorators,t,n)),r.push(`${P(t,n)}block ${U(e.name)} {`),e.domain&&r.push(`${P(t+1,n)}domain = ${U(e.domain)}`),e.blockType&&r.push(`${P(t+1,n)}type = ${U(e.blockType)}`),e.status&&r.push(`${P(t+1,n)}status = ${U(e.status)}`),e.description&&r.push(`${P(t+1,n)}description = ${U(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${P(t+1,n)}tags = [${e.tags.map(U).join(", ")}]`),e.owner&&r.push(`${P(t+1,n)}owner = ${U(e.owner)}`),e.termRefs&&e.termRefs.length>0&&r.push(`${P(t+1,n)}terms = [${e.termRefs.map(U).join(", ")}]`),e.pattern&&r.push(`${P(t+1,n)}pattern = ${U(e.pattern)}`),e.grain&&r.push(`${P(t+1,n)}grain = ${U(e.grain)}`),e.entities&&e.entities.length>0&&r.push(`${P(t+1,n)}entities = [${e.entities.map(U).join(", ")}]`),e.outputs&&e.outputs.length>0&&r.push(`${P(t+1,n)}outputs = [${e.outputs.map(U).join(", ")}]`),e.blockType!=="semantic"&&e.dimensions&&e.dimensions.length>0&&r.push(`${P(t+1,n)}dimensions = [${e.dimensions.map(U).join(", ")}]`),e.allowedFilters&&e.allowedFilters.length>0&&r.push(`${P(t+1,n)}allowedFilters = [${e.allowedFilters.map(U).join(", ")}]`),e.parameterPolicy&&e.parameterPolicy.length>0){r.push(`${P(t+1,n)}parameterPolicy {`);for(const o of e.parameterPolicy)r.push(`${P(t+2,n)}${o.name} = ${U(o.policy)}`);r.push(`${P(t+1,n)}}`)}if(e.filterBindings&&e.filterBindings.length>0){r.push(`${P(t+1,n)}filterBindings {`);for(const o of e.filterBindings)r.push(`${P(t+2,n)}${o.filter} = ${U(o.binding)}`);r.push(`${P(t+1,n)}}`)}if(e.sourceSystems&&e.sourceSystems.length>0&&r.push(`${P(t+1,n)}sourceSystems = [${e.sourceSystems.map(U).join(", ")}]`),e.replacementFor&&e.replacementFor.length>0&&r.push(`${P(t+1,n)}replacementFor = [${e.replacementFor.map(U).join(", ")}]`),e.llmContext&&r.push(`${P(t+1,n)}llmContext = ${U(e.llmContext)}`),e.businessOutcome&&r.push(`${P(t+1,n)}businessOutcome = ${U(e.businessOutcome)}`),e.businessOwner&&r.push(`${P(t+1,n)}businessOwner = ${U(e.businessOwner)}`),e.decisionUse&&r.push(`${P(t+1,n)}decisionUse = ${U(e.decisionUse)}`),e.reviewCadence&&r.push(`${P(t+1,n)}reviewCadence = ${U(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${P(t+1,n)}businessRules = [${e.businessRules.map(U).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${P(t+1,n)}caveats = [${e.caveats.map(U).join(", ")}]`),e.examples&&e.examples.length>0&&r.push(`${P(t+1,n)}examples = [${mv(e.examples)}]`),e.invariants&&e.invariants.length>0&&r.push(`${P(t+1,n)}invariants = [${e.invariants.map(U).join(", ")}]`),e.blockType==="semantic"){const o=e.metricsRef??(e.metricRef!==void 0?[e.metricRef]:[]);r.push(`${P(t+1,n)}metrics = [${o.map(U).join(", ")}]`),r.push(`${P(t+1,n)}dimensions = [${(e.dimensionsRef??[]).map(U).join(", ")}]`),e.timeDimension&&r.push(`${P(t+1,n)}time_dimension = ${U(e.timeDimension)}`),e.granularity&&r.push(`${P(t+1,n)}granularity = ${U(e.granularity)}`),e.requestedFilters&&e.requestedFilters.length>0&&r.push(`${P(t+1,n)}requested_filters = [${e.requestedFilters.map(U).join(", ")}]`),e.orderBy&&e.orderBy.length>0&&r.push(`${P(t+1,n)}order_by = [${e.orderBy.map(U).join(", ")}]`),e.limit!==void 0&&r.push(`${P(t+1,n)}limit = ${e.limit}`)}if(e.params){r.push(`${P(t+1,n)}params {`);for(const o of e.params.params){const i=o.paramType?`: ${o.paramType}`:"",l=o.initializer?` = ${ut(o.initializer)}`:"";r.push(`${P(t+2,n)}${o.name}${i}${l}`)}r.push(`${P(t+1,n)}}`)}if(e.query&&(r.push(`${P(t+1,n)}query = """`),r.push(...td(e.query,t+2,n)),r.push(`${P(t+1,n)}"""`)),e.visualization){r.push(`${P(t+1,n)}visualization {`);for(const o of e.visualization.properties)r.push(`${P(t+2,n)}${Fs(o)}`);r.push(`${P(t+1,n)}}`)}if(e.tests&&e.tests.length>0){r.push(`${P(t+1,n)}tests {`);for(const o of e.tests)r.push(`${P(t+2,n)}assert ${o.field} ${o.operator} ${ut(o.expected)}`);r.push(`${P(t+1,n)}}`)}return r.push(`${P(t,n)}}`),r.join(`
434
- `)}function pv(e,t,n){var o,i,l,a,d,c,f,p;const r=[];return r.push(...Ft(e.decorators,t,n)),r.push(`${P(t,n)}domain ${U(e.name)} {`),e.id&&r.push(`${P(t+1,n)}id = ${U(e.id)}`),e.parent&&r.push(`${P(t+1,n)}parent = ${U(e.parent)}`),e.owner&&r.push(`${P(t+1,n)}owner = ${U(e.owner)}`),e.businessOwner&&r.push(`${P(t+1,n)}businessOwner = ${U(e.businessOwner)}`),e.boundedContext&&r.push(`${P(t+1,n)}boundedContext = ${U(e.boundedContext)}`),e.sourceSystems&&e.sourceSystems.length>0&&r.push(`${P(t+1,n)}sourceSystems = [${e.sourceSystems.map(U).join(", ")}]`),e.primaryTerms&&e.primaryTerms.length>0&&r.push(`${P(t+1,n)}primaryTerms = [${e.primaryTerms.map(U).join(", ")}]`),e.reviewCadence&&r.push(`${P(t+1,n)}reviewCadence = ${U(e.reviewCadence)}`),e.tags&&e.tags.length>0&&r.push(`${P(t+1,n)}tags = [${e.tags.map(U).join(", ")}]`),e.businessOutcome&&r.push(`${P(t+1,n)}businessOutcome = ${U(e.businessOutcome)}`),e.description&&r.push(`${P(t+1,n)}description = ${U(e.description)}`),(o=e.inScope)!=null&&o.length&&r.push(`${P(t+1,n)}inScope = [${e.inScope.map(U).join(", ")}]`),(i=e.outOfScope)!=null&&i.length&&r.push(`${P(t+1,n)}outOfScope = [${e.outOfScope.map(U).join(", ")}]`),(l=e.dbtGroups)!=null&&l.length&&r.push(`${P(t+1,n)}dbtGroups = [${e.dbtGroups.map(U).join(", ")}]`),(a=e.dbtPaths)!=null&&a.length&&r.push(`${P(t+1,n)}dbtPaths = [${e.dbtPaths.map(U).join(", ")}]`),(d=e.dbtTags)!=null&&d.length&&r.push(`${P(t+1,n)}dbtTags = [${e.dbtTags.map(U).join(", ")}]`),(c=e.semanticDomains)!=null&&c.length&&r.push(`${P(t+1,n)}semanticDomains = [${e.semanticDomains.map(U).join(", ")}]`),(f=e.semanticTags)!=null&&f.length&&r.push(`${P(t+1,n)}semanticTags = [${e.semanticTags.map(U).join(", ")}]`),(p=e.exports)!=null&&p.length&&r.push(`${P(t+1,n)}exports = [${e.exports.map(U).join(", ")}]`),r.push(`${P(t,n)}}`),r.join(`
435
- `)}function fv(e,t,n){const r=[];return r.push(...Ft(e.decorators,t,n)),r.push(`${P(t,n)}term ${U(e.name)} {`),e.domain&&r.push(`${P(t+1,n)}domain = ${U(e.domain)}`),e.termType&&r.push(`${P(t+1,n)}type = ${U(e.termType)}`),e.status&&r.push(`${P(t+1,n)}status = ${U(e.status)}`),e.description&&r.push(`${P(t+1,n)}description = ${U(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${P(t+1,n)}tags = [${e.tags.map(U).join(", ")}]`),e.owner&&r.push(`${P(t+1,n)}owner = ${U(e.owner)}`),e.identifiers&&e.identifiers.length>0&&r.push(`${P(t+1,n)}identifiers = [${e.identifiers.map(U).join(", ")}]`),e.synonyms&&e.synonyms.length>0&&r.push(`${P(t+1,n)}synonyms = [${e.synonyms.map(U).join(", ")}]`),e.businessOutcome&&r.push(`${P(t+1,n)}businessOutcome = ${U(e.businessOutcome)}`),e.businessOwner&&r.push(`${P(t+1,n)}businessOwner = ${U(e.businessOwner)}`),e.decisionUse&&r.push(`${P(t+1,n)}decisionUse = ${U(e.decisionUse)}`),e.reviewCadence&&r.push(`${P(t+1,n)}reviewCadence = ${U(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${P(t+1,n)}businessRules = [${e.businessRules.map(U).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${P(t+1,n)}caveats = [${e.caveats.map(U).join(", ")}]`),r.push(`${P(t,n)}}`),r.join(`
436
- `)}function hv(e,t,n){const r=[];r.push(...Ft(e.decorators,t,n)),r.push(`${P(t,n)}business_view ${U(e.name)} {`),e.domain&&r.push(`${P(t+1,n)}domain = ${U(e.domain)}`),e.status&&r.push(`${P(t+1,n)}status = ${U(e.status)}`),e.description&&r.push(`${P(t+1,n)}description = ${U(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${P(t+1,n)}tags = [${e.tags.map(U).join(", ")}]`),e.owner&&r.push(`${P(t+1,n)}owner = ${U(e.owner)}`),e.termRefs&&e.termRefs.length>0&&r.push(`${P(t+1,n)}terms = [${e.termRefs.map(U).join(", ")}]`),e.businessOutcome&&r.push(`${P(t+1,n)}businessOutcome = ${U(e.businessOutcome)}`),e.businessOwner&&r.push(`${P(t+1,n)}businessOwner = ${U(e.businessOwner)}`),e.decisionUse&&r.push(`${P(t+1,n)}decisionUse = ${U(e.decisionUse)}`),e.reviewCadence&&r.push(`${P(t+1,n)}reviewCadence = ${U(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${P(t+1,n)}businessRules = [${e.businessRules.map(U).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${P(t+1,n)}caveats = [${e.caveats.map(U).join(", ")}]`),r.push(`${P(t+1,n)}includes {`);for(const o of e.includes)r.push(`${P(t+2,n)}${o.refType} ${U(o.name)}`);return r.push(`${P(t+1,n)}}`),r.push(`${P(t,n)}}`),r.join(`
437
- `)}function td(e,t,n){const r=e.rawSQL.replace(/^\n+|\s+$/g,"");if(!r.trim())return[`${P(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`${P(t,n)}${c}`})}function Fs(e){return`${e.name} = ${ut(e.value)}`}function mv(e){return e.map(t=>{const n=[`question = ${U(t.question)}`];return t.sql&&n.push(`sql = ${U(t.sql)}`),`{ ${n.join(", ")} }`}).join(", ")}function ut(e){switch(e.kind){case K.StringLiteral:return U(e.value);case K.NumberLiteral:return String(e.value);case K.BooleanLiteral:return e.value?"true":"false";case K.Identifier:return e.name;case K.ArrayLiteral:return`[${e.elements.map(t=>ut(t)).join(", ")}]`;case K.BinaryExpr:return`${ut(e.left)} ${e.operator} ${ut(e.right)}`;case K.IntervalExpr:return`INTERVAL ${U(e.value)}`;case K.FunctionCall:return`${e.callee}(${e.arguments.map(t=>ut(t)).join(", ")})`;case K.TemplateString:return U(e.parts.map(t=>typeof t=="string"?t:`{${ut(t)}}`).join(""));default:return""}}function U(e){return JSON.stringify(e)}function gv(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=xv(e.parameters??[]),l=[`block ${Pe(e.name)} {`,' type = "semantic"',` status = ${Pe(((c=e.status)==null?void 0:c.trim())||"draft")}`],a=yv(e.domain);a&&l.push(` domain = ${Pe(a)}`),(f=e.description)!=null&&f.trim()&&l.push(` description = ${Pe(e.description.trim())}`);const d=Cn(e.tags??[]);if(d.length>0&&l.push(` tags = [${d.map(Pe).join(", ")}]`),(p=e.owner)!=null&&p.trim()&&l.push(` owner = ${Pe(e.owner.trim())}`),l.push(` metrics = [${t.map(Pe).join(", ")}]`),l.push(` dimensions = [${n.map(Pe).join(", ")}]`),(h=e.timeDimension)!=null&&h.name.trim()&&(l.push(` time_dimension = ${Pe(e.timeDimension.name.trim())}`),e.timeDimension.granularity.trim()&&l.push(` granularity = ${Pe(e.timeDimension.granularity.trim())}`)),r.length>0&&l.push(` requested_filters = [${r.map(Pe).join(", ")}]`),o.length>0&&l.push(` order_by = [${o.map(Pe).join(", ")}]`),bv(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?` = ${nd(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} = ${Pe(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} = ${Pe(E.binding.trim())}`);l.push(" }")}}return(S=e.visualization)!=null&&S.chart.trim()&&(l.push(" visualization {"),l.push(` chart = ${Pe(e.visualization.chart.trim())}`),(x=e.visualization.x)!=null&&x.trim()&&l.push(` x = ${Yi(e.visualization.x.trim())}`),(b=e.visualization.y)!=null&&b.trim()&&l.push(` y = ${Yi(e.visualization.y.trim())}`),l.push(" }")),l.push("}"),Yb(`${l.join(`
439
- `)}
440
- `)}function yv(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 xv(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 bv(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function nd(e){return Array.isArray(e)?`[${e.map(nd).join(", ")}]`:typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":Pe(String(e??""))}function Pe(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Yi(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:Pe(e)}function vv(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 gv({name:i,status:"draft",metrics:n,dimensions:r}).trimEnd()}function Sv(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 kv(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=Sv(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 wv(e,t){const n={path:"",folders:new Map,files:[]};for(const o of e){const i=jv(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 jv(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 rd({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 Cv(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 Xi(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 Ev=[{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 He(e){return String(e??"").trim()||"uncategorized"}function dt(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 Av(e,t){return String((t==="dimension"||t==="time_dimension")&&e.reference||e.name)}function Tv(e,t,n){const r=Av(e,t),o=He(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)}:{},...dt(e).length>0?{semanticModelIds:dt(e).join(",")}:{},...e.owner?{owner:String(e.owner)}:{},...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags.join(",")}:{}}}}function jt(e,t,n,r,o){if(r.length===0)return null;const i=r.map(l=>Tv(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 Rv(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 dt(c))o.add(f);const i=c=>{const f=r.get(c);if(f)return He(f.domain);const p=n.find(h=>dt(h).includes(c));return He(p==null?void 0:p.domain)},l=new Set([...e.domains.map(He),...e.semanticModels.map(c=>He(c.domain)),...n.map(c=>He(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=Ev.flatMap(({collection:y,kind:M,label:O})=>{const T=e[y].filter(I=>{const V=dt(I);return V.length===1&&V[0]===v&&(y!=="dimensions"||!I.isTimeDimension)}),L=jt(`group:${c}:${v}:${M}`,O,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=>He(v.domain)===c&&dt(v).length>1),g=e.metrics.filter(v=>He(v.domain)===c&&dt(v).length===0),S=[jt(`group:${c}:unassigned-dimensions`,"Dimensions","dimension",e.dimensions.filter(v=>He(v.domain)===c&&dt(v).length===0&&!v.isTimeDimension),t),jt(`group:${c}:unassigned-time-dimensions`,"Time Dimensions","time_dimension",e.timeDimensions.filter(v=>He(v.domain)===c&&dt(v).length===0),t),jt(`group:${c}:unassigned-measures`,"Underlying measures","measure",e.measures.filter(v=>He(v.domain)===c&&dt(v).length===0),t),jt(`group:${c}:unassigned-entities`,"Entities","entity",e.entities.filter(v=>He(v.domain)===c&&dt(v).length===0),t)].filter(v=>!!v),x=[...p],b=jt(`group:${c}:cross-model-metrics`,"Cross-model metrics","metric",h,t);b&&x.push(b);const k=jt(`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=jt(`group:${c}:hierarchies`,"Hierarchies","hierarchy",e.hierarchies.filter(v=>He(v.domain)===c),t);C&&x.push(C);const E=jt(`group:${c}:saved-queries`,"Saved Queries","saved_query",e.savedQueries.filter(v=>He(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 _v(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 Zi=[{id:"notebooks",label:"Notebooks",icon:Ms},{id:"semantic",label:"Semantic",icon:Is},{id:"database",label:"Database",icon:tr},{id:"blocks",label:"Blocks",icon:Ps}],$v={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 Ov({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}=ve(),x=ze[g.themeMode],b=n?n.map(M=>Zi.find(O=>O.id===M)).filter(M=>!!M):Zi,[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=>{Eb(M)||S({type:"ADD_CELL",cell:Os("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:O,icon:T})=>{const L=k===M;return s.jsxs("button",{type:"button",onClick:()=>C(M),title:O,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:O})]},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(Bi,{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(Qy,{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(Bi,{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(ix,{size:14,strokeWidth:2})}):null]}),s.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:[k==="notebooks"&&t&&s.jsx(Dv,{t:x,onOpenFile:t,search:E,domain:w,onDomainChange:A}),k==="semantic"&&s.jsx(Nv,{t:x,search:E,onInsert:R,notebookMode:!r||!!o,onSemanticCompose:o}),k==="database"&&s.jsx(Bv,{t:x,search:E,onInsert:R}),k==="blocks"&&s.jsx(Fv,{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 Pv(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 Dv({t:e,onOpenFile:t,search:n,domain:r,onDomainChange:o}){var v;const{state:i,dispatch:l}=ve(),[a,d]=u.useState(null),[c,f]=u.useState(!1),[p,h]=u.useState(null),g=Cv(i.files),S=r&&!g.includes(r)?[r,...g]:g,x=Xi(i.files,"",r),b=Xi(i.files,n,r),k=wv(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(rd,{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(od,{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(Lv,{file:a,t:e,busy:c,error:p,onCancel:()=>{d(null),h(null)},onConfirm:()=>void E()}):null]})}function od({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(Mv,{node:l,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i},`notebook-folder:${l.path}`):s.jsx(Iv,{file:l.file,active:t===l.file.path,onOpenFile:n,onDelete:r,t:o,depth:i},l.file.path))})}function Mv({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(Bc,{size:13}):s.jsx(Bn,{size:13}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]}),l?s.jsx(od,{nodes:e.children,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i+1}):null]})}function Iv({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(Ms,{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(zc,{size:12})})]})}function Lv({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:we(t,{variant:"secondary",size:"md",disabled:n}),children:"Cancel"}),s.jsx("button",{type:"button",onClick:i,disabled:n,style:we(t,{variant:"danger",size:"md",disabled:n}),children:n?"Deleting…":"Delete notebook"})]})]})})}function Nv({t:e,search:t,onInsert:n,notebookMode:r,onSemanticCompose:o}){var Q;const{state:i,dispatch:l}=ve(),a=u.useMemo(()=>Rv(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,O]=u.useState(),T=new Map(i.semanticLayer.metrics.map(q=>[q.name,q])),L=()=>{l({type:"SET_SETTINGS_TAB",tab:"project"}),l({type:"SET_MAIN_VIEW",view:"settings"})};u.useEffect(()=>{let q=!0;return N.getConnections().then(ee=>{q&&O(ee.default?{target:"connection",connectionName:ee.default}:void 0)}).catch(()=>{q&&O(void 0)}),()=>{q=!1}},[]),u.useEffect(()=>{let q=!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(ee=>{if(!q)return;const H=new Set(ee.dimensions.map(B=>B.reference??B.name));S(H),b("ready"),C(ee.engine),h(B=>new Set(Array.from(B).filter(ne=>H.has(ne))))}).catch(ee=>{q&&(S(new Set),b("error"),C(null),h(new Set),y(ee instanceof vt?`${ee.code?`${ee.code}: `:""}${ee.message}`:ee instanceof Error?ee.message:"Semantic compatibility could not be verified."))}),()=>{q=!1}},[Array.from(c).sort().join("|")]);const I=u.useMemo(()=>!a||!r?a:_v(a,c.size,g,x),[a,r,c.size,g,x]),V=(q,ee)=>{A(null),y(null),(q==="metric"?f:h)(B=>{const ne=new Set(B);return ne.has(ee)?ne.delete(ee):ne.add(ee),ne})},X=(q,ee)=>{var H;if(q==="metric"){const B=(H=T.get(ee))==null?void 0:H.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(ee)?{allowed:!0}:{allowed:!1,reason:"This dimension has no governed join path to every selected metric."}:{allowed:!1,reason:"Checking compatibility…"}},J=new Set([...Array.from(c).map(q=>`metric:${q}`),...Array.from(p).map(q=>`dimension:${q}`)]),W=c.size>0&&x==="ready"&&!E,D=async()=>{if(c.size!==0){v(!0),y(null);try{const q=await N.previewSemanticBuilder({metrics:Array.from(c),dimensions:Array.from(p),executionTarget:M,limit:50});if("error"in q){A(null),y(q.error);return}A({sql:q.sql,rows:q.result.rowCount??q.result.rows.length,executionTarget:M,engine:q.engine})}catch(q){A(null),y(q instanceof vt?`${q.code?`${q.code}: `:""}${q.message}`:q instanceof Error?q.message:"The governed semantic preview could not run.")}finally{v(!1)}}},$=()=>{if(!W)return;const q=Array.from(c),ee=Array.from(p);if(o){o(q,ee),f(new Set),h(new Set),A(null),y(null);return}const H=vv(q,ee),B=Os("dql",H);B.executionTarget=(w==null?void 0:w.executionTarget)??M,B.dqlArtifact={source:H,kind:"semantic_block",metrics:q,dimensions:ee,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||(((Q=a.children)==null?void 0:Q.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 D(),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:$,disabled:!W,title:W?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:W?"pointer":"not-allowed",opacity:W?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(q=>q.execution&&q.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(Db,{tree:I,themeMode:i.themeMode,search:t,onInsert:n,selectionMode:r,selected:J,onToggleSelection:V,canSelect:X})]})}function Bv({t:e,search:t,onInsert:n}){const{state:r}=ve(),[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(Ds,{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($b,{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:Jc(c).label}),s.jsx("span",{style:{fontSize:10,color:e.textMuted,flexShrink:0},children:c.columns.length})]})]}),f&&c.columns.map(p=>{const h=Pv(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 Fv({t:e,search:t,domain:n,onDomainChange:r,onDeleteBlock:o,refreshKey:i}){const{state:l,dispatch:a}=ve(),[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=Mb(d),b=n,k=b&&!x.includes(b)?[b,...x]:x,C=Ib(d,b,t),E=u.useMemo(()=>kv(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(rd,{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(sd,{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 sd({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(zv,{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(De.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(Ds,{size:13,color:a.textMuted}):s.jsx(oo,{size:13,color:a.textMuted}),c?s.jsx(Bc,{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:id(d.children)})]}),c?s.jsx(sd,{nodes:d.children,depth:t+1,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:l,t:a}):null]},`folder:${d.path}`)})})}function id(e){return e.reduce((t,n)=>t+(n.kind==="block"?1:id(n.children)),0)}function zv({block:e,depth:t=0,t:n,onOpen:r,onDelete:o}){const i=String(e.status??"draft"),l=$v[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(Ps,{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(zc,{size:13})}):null]})}const br=(e,t)=>`https://cdn.simpleicons.org/${e}/${t}`,qv={duckdb:[br("duckdb","FFF000")],file:[br("duckdb","FFF000")],snowflake:[br("snowflake","29B5E8")],databricks:[br("databricks","FF3621")]},Uv={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"};function Wv({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=qv[e]??[],o=n??Uv[e]??"#888",[i,l]=u.useState(0);return r.length===0||i>=r.length?s.jsx(Wv,{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"}})}function Kv(e,t){return t.reindexRequired?{ok:!1,message:`Re-index did not complete — ${e.reason??"the catalog is still using a different embedding index"}.`}:e.upgraded?{ok:!0,message:`Catalog re-embedded with ${t.activeProviderId}.`}:{ok:!0,message:`No re-index needed — ${e.reason??"already current"}.`}}const vr="http://127.0.0.1:11434";function Vv({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,M]=u.useState(null),O=u.useCallback($=>{r($.settings.provider),i($.settings.endpoint||vr),a($.settings.model),p($.settings.apiKeySet),E({id:$.activeProviderId,semantic:$.semantic,reindexRequired:$.reindexRequired})},[]),T=u.useCallback(async $=>{try{const Q=await N.listEmbeddingModels($);g(Q.catalog),x(Q.installed),k(Q.ollamaReachable)}catch{}},[]);u.useEffect(()=>{(async()=>{try{const $=await N.getEmbeddingSettings();O($),await T($.settings.endpoint||vr)}catch($){R($ instanceof Error?$.message:String($))}})()},[O,T]);const L=async($,Q)=>{w($),R(null),M(null);try{await Q()}catch(q){R(q instanceof Error?q.message:String(q))}finally{w(null)}},I=($,Q)=>L("save",async()=>{const q=await N.saveEmbeddingSettings({provider:$,...$==="ollama"?{endpoint:o}:{},...Q?{model:Q}:{},...$==="openai"&&d?{apiKey:d}:{}});r($),a(Q),d&&(p(!0),c("")),E({id:q.activeProviderId,semantic:q.semantic,reindexRequired:q.reindexRequired}),t==null||t(q.semantic?"Semantic embeddings enabled. Re-index to apply them to your catalog.":"Using the offline hashed embedder — retrieval stays lexical.")}),V=n==="openai"?h.openai:h.ollama,X={border:`1px solid ${e.headerBorder}`,borderRadius:10,padding:14,background:e.cellBg,marginTop:14},J={fontSize:11,fontWeight:700,color:e.textMuted,textTransform:"uppercase",letterSpacing:"0.05em"},W={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%"},D=$=>({display:"inline-flex",alignItems:"center",gap:6,height:28,padding:"0 11px",borderRadius:6,border:`1px solid ${$?e.accent:e.btnBorder}`,background:$?e.accent:e.btnBg,color:$?"#fff":e.textSecondary,fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:e.font});return s.jsxs("div",{style:X,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(gx,{size:11}):s.jsx(hx,{size:11}),C.semantic?"Semantic":"Lexical only"]})]}),s.jsx("div",{style:{display:"flex",gap:6,marginTop:12,flexWrap:"wrap"},children:["hashed","ollama","openai"].map($=>s.jsx("button",{type:"button",onClick:()=>{r($),$==="hashed"&&I("hashed","")},style:{...D(n===$),textTransform:"capitalize"},children:$==="hashed"?"Offline (default)":$==="ollama"?"Ollama (local)":"OpenAI"},$))}),n==="ollama"&&s.jsxs("div",{style:{marginTop:12},children:[s.jsx("div",{style:J,children:"Ollama endpoint"}),s.jsxs("div",{style:{display:"flex",gap:6,marginTop:4,alignItems:"center"},children:[s.jsx("input",{value:o,onChange:$=>i($.target.value),onBlur:()=>void T(o),style:W,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:J,children:["API key ",f?"(stored — leave blank to keep)":""]}),s.jsx("input",{type:"password",value:d,onChange:$=>c($.target.value),style:{...W,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:J,children:"Model"}),s.jsx("div",{style:{display:"grid",gap:6,marginTop:6},children:V.map($=>{const Q=n==="openai"||S.includes($.model),q=l===$.model;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"9px 11px",borderRadius:8,border:`1px solid ${q?e.accent:e.btnBorder}`,background:q?`${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:$.model}),$.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:[$.dimensions," dims · ",$.size]})]}),s.jsx("div",{style:{fontSize:11.5,color:e.textSecondary,marginTop:3,lineHeight:1.45},children:$.description})]}),Q?s.jsx("button",{type:"button",onClick:()=>void I(n,$.model),disabled:v!==null,style:D(q),children:q?s.jsxs(s.Fragment,{children:[s.jsx(Kg,{size:12})," In use"]}):"Use this"}):s.jsx("button",{type:"button",disabled:v!==null||!b,onClick:()=>void L(`install:${$.model}`,async()=>{await N.installEmbeddingModel($.model,o),await T(o),await N.saveEmbeddingSettings({provider:"ollama",endpoint:o,model:$.model}),a($.model);const ee=await N.getEmbeddingSettings();O(ee),t==null||t(`${$.model} installed and selected. Re-index to apply it.`)}),style:D(!0),children:v===`install:${$.model}`?s.jsxs(s.Fragment,{children:[s.jsx(Fn,{size:12,className:"dql-spin"})," Installing…"]}):s.jsxs(s.Fragment,{children:[s.jsx(Ic,{size:12})," Install"]})})]},$.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 L("test",async()=>{const $=await N.testEmbeddingProvider();t==null||t(`${$.providerId} responded in ${$.elapsedMs} ms (${$.dimensions} dims).`)}),style:D(),children:[v==="test"?s.jsx(Fn,{size:12,className:"dql-spin"}):null," Test"]}),s.jsxs("button",{type:"button",disabled:v!==null,onClick:()=>void L("reindex",async()=>{const $=await N.reindexEmbeddings(),Q=await N.getEmbeddingSettings();O(Q);const q=Kv($,Q);M(q),t==null||t(q.message)}),style:D(C.reindexRequired),children:[v==="reindex"?s.jsx(Fn,{size:12,className:"dql-spin"}):s.jsx(Ir,{size:12}),v==="reindex"?"Re-indexing…":"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."}),v==="reindex"&&s.jsx("div",{role:"status",style:{fontSize:11.5,color:e.textSecondary,marginTop:8,lineHeight:1.5},children:"Rebuilding the local vector index. This page will update automatically when it finishes."}),y&&s.jsx("div",{role:y.ok?"status":"alert",style:{fontSize:11.5,color:y.ok?"var(--status-success)":"var(--status-error)",marginTop:8,lineHeight:1.5},children:y.message}),A&&s.jsx("div",{style:{fontSize:11.5,color:e.error,marginTop:8,lineHeight:1.5},children:A})]})}function Hv({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(ea(d).join(", "))},onChange:p=>{c(p.target.value),t(ea(p.target.value))}})}function ea(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Gv(e){var t;return((t=e.evaluation)==null?void 0:t.status)==="failed"?"Rerun checks & approve":"Run checks & approve"}function Jv(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 Qv(e,t,n){const r=n.trim();return{...e,[t]:r||void 0}}async function Yv(e,t){try{return await e()}finally{await t()}}const Xv=["claude-code","codex","anthropic","openai","gemini","ollama","custom-openai"],Zv=["claude-code","codex"],eS=["anthropic","openai","gemini","ollama","custom-openai"];function ad(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 Co({includeMemory:e=!0,embedded:t=!1,section:n,editorMode:r="settings",onProviderConfigured:o}){const{state:i}=ve(),l=ze[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,O,T]=await Promise.all([N.getSettingsEnvStatus(),N.getProviderSettings(),N.getRemoteMcpSettings(),e?N.listAgentMemory():Promise.resolve({memories:[]})]);d(y.groups),f(M.providers),S(O.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(iS,{configured:A,total:c.length||Xv.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(rS,{providers:c,cliStatus:p,t:l,onSaved:y=>f(y),onStatus:v,editorMode:r,onProviderConfigured:o}),s.jsx(Vv,{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(na,{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:Zv.map(y=>{const M=c.find(O=>O.id===y);return M?s.jsx(sa,{provider:M,cliStatus:p[y],t:l,onSaved:O=>f(O),onStatus:v},y):null})}),s.jsx(na,{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:eS.map(y=>{const M=c.find(O=>O.id===y);return M?s.jsx(sa,{provider:M,t:l,onSaved:O=>f(O),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(sS,{memories:x,t:l,onChange:b,onStatus:v}),s.jsx(oS,{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(ta,{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(aa,{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(ta,{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(aa,{group:y,t:l},y.id))})]})]})]})]})]})}function ta({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,V)=>V===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=cS(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(V=>Yt(V)));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=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"," / ",O," OpenAI connector",O===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:la(t,l==="form"),children:"Form"}),s.jsx("button",{type:"button",onClick:()=>E("json"),style:la(t,l==="json"),children:"JSON import"})]}),s.jsx("button",{type:"button",onClick:k,style:gt(t,!1),children:"Add MCP server"}),s.jsx("button",{type:"button",onClick:C,style:gt(t,!1),children:"Add OpenAI connector"}),s.jsx("button",{type:"button",onClick:R,disabled:h,style:gt(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(Eo,{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(Eo,{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(Eo,{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:gt(t,!1),children:"Format JSON"}),s.jsx("button",{type:"button",onClick:A,style:gt(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:gt(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(Hv,{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:da(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:da(T.providers,"anthropic",I.target.checked)})})," Anthropic"]})]})]},`${T.kind}-${T.name||L}`))})]})}function Eo({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 tS({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 na({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 ld(e){return e==="codex"?"codex":"claude"}function cd({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:gt(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:gt(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(tS,{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"}}],ra={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 nS(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 rS({providers:e,cliStatus:t,t:n,onSaved:r,onStatus:o,editorMode:i,onProviderConfigured:l}){var H;const a=e.find(B=>B.active&&B.configured),[d,c]=u.useState(()=>nS(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,O]=u.useState(!1),[T,L]=u.useState({state:"idle"}),[I,V]=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"),V({state:"idle"})},[x,b==null?void 0:b.baseUrl,b==null?void 0:b.model,b==null?void 0:b.reasoningEffort]);const X=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)})},J=()=>{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},W=async()=>{const B=J();if(B)return V({state:"done",ok:!1,message:B}),!1;V({state:"testing"});const ne=await N.testProviderSettings(x,{apiKey:k||void 0,baseUrl:E||void 0,model:w||void 0});return V({state:"done",ok:ne.ok,message:ne.message}),ne.ok},D=async()=>{O(!0);try{if(!await W()){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{O(!1)}},$=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(ye=>ye.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))}},Q={fontSize:11,fontWeight:650,color:n.textSecondary},q={...$e(n),borderRadius:8},ee=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(Fc,{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 X(),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:Q,children:"Provider"}),s.jsx("select",{value:f.key,onChange:B=>{c(B.target.value),g("subscription")},style:q,children:Ar.map(B=>s.jsx("option",{value:B.key,children:B.label},B.key))})]})}),s.jsxs("div",{children:[s.jsx("span",{style:{...Q,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:ra[B].label}),s.jsx("span",{style:{fontSize:10,color:n.textMuted},children:ra[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(cd,{oauthProvider:ld(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:$})}):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:Q,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:{...q,fontFamily:n.fontMono}})]}),(H=b==null?void 0:b.envVars)!=null&&H[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:Q,children:"Host"}),s.jsx("input",{value:E,onChange:B=>v(B.target.value),placeholder:"http://localhost:11434",style:{...q,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(oa,{providerId:x,provider:b,mode:S,baseUrl:E,setBaseUrl:v,model:w,setModel:A,reasoningEffort:R,setReasoningEffort:y,t:n,input:q,fieldLabel:Q})})]}):s.jsx("div",{style:{display:"grid",gap:10},children:s.jsx(oa,{providerId:x,provider:b,mode:S,baseUrl:E,setBaseUrl:v,model:w,setModel:A,reasoningEffort:R,setReasoningEffort:y,t:n,input:q,fieldLabel:Q})}),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:ee}),s.jsx("button",{type:"button",onClick:()=>void W(),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 D(),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 oa({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:ad(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 sa({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)},O=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:lS(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(cd,{oauthProvider:ld(e.id),label:e.label,model:p,setModel:h,cliStatus:t,command:e.command,loginCmd:A,t:n,onStatus:o,onConnected:O}):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:ad(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:gt(n,!0),children:e.active?"Save active provider":"Save and use"}),s.jsx("button",{type:"button",onClick:M,disabled:x||k,style:gt(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 Ke(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 ia(e){return[...new Map(e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean).map(t=>[t.toLowerCase(),t])).values()].slice(0,8)}function oS({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 O;a(y.id),t(null);try{const T=(O=f[y.id])==null?void 0:O.trim(),L=await Yv(()=>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,O)=>{var T;a(y.id),t(null);try{const L=await N.transitionAgentHint(y.id,{action:M,targetHintId:O,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:{...Ke(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 O=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(O.ok?`Certification research requested for "${y.title}". Approval of a hint did not certify an asset.`:O.error??"Could not request certification.")}catch(O){t(O instanceof Error?O.message:String(O))}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,O,T,L,I,V,X,J,W;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,(O=y.trace)!=null&&O.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(D=>`${D.kind}:${D.id}@${D.fingerprint.slice(0,10)}`).join(", "))||"none recorded"]}),s.jsxs("div",{children:[s.jsx("b",{children:"Graph connections:"})," ",(V=y.graphEdges)!=null&&V.length?y.graphEdges.map(D=>`${D.kind.replace(/_/g," ")} → ${D.targetName}`).join(" · "):"none materialized"]}),(X=y.lifecycleErrors)==null?void 0:X.map(D=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:[D.code,":"]})," ",D.message]},`${D.code}-${D.at}`)),y.evaluation?s.jsxs("div",{children:[s.jsxs("b",{children:["Evaluation ",y.evaluation.status,":"]}),y.evaluation.checks.map(D=>s.jsxs("div",{style:{color:D.passed?e.success:e.error},children:[D.passed?"✓":"✕"," ",D.name," — ",D.evidence]},D.name))]}):s.jsxs("div",{children:[s.jsx("b",{children:"Evaluation:"})," not run"]}),(J=y.inspection)==null?void 0:J.checks.map(D=>s.jsxs("div",{style:{color:D.passed?e.success:e.error},children:[D.passed?"✓":"✕"," live ",D.name," — ",D.evidence]},`live-${D.name}`)),(W=y.exclusions)==null?void 0:W.map((D,$)=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:["Excluded: ",D.reason]})," — ",D.detail]},`${D.reason}-${$}`))]})]})},R=y=>{var L,I,V,X,J,W;const M=((L=y.exclusions)==null?void 0:L.filter(D=>D.reason==="conflict"&&D.relatedHintId))??[],O=(h==null?void 0:h.id)===y.id,T=y.status==="approved"&&((I=y.evaluation)==null?void 0:I.status)==="passed"&&((V=y.inspection)==null?void 0:V.state)==="current"&&(((X=y.exclusions)==null?void 0:X.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:(J=y.exclusions)!=null&&J.length||((W=y.evaluation)==null?void 0:W.status)==="failed"?e.error:e.success},children:Jv(y)})]}),O?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:h.title,onChange:D=>g({...h,title:D.target.value}),placeholder:"Hint title",style:we(e,{size:"sm"})}),s.jsx("textarea",{value:h.guidance,onChange:D=>g({...h,guidance:D.target.value}),placeholder:"Guidance for matching questions",rows:3,style:{...we(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:Ke(h).category,onChange:D=>g({...h,lesson:{...Ke(h),category:D.target.value}}),style:we(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:Ke(h).intentExamples.join(`
446
- `),onChange:D=>g({...h,lesson:{...Ke(h),intentExamples:D.target.value.split(/\r?\n/)}}),onBlur:()=>g({...h,lesson:{...Ke(h),intentExamples:ia(Ke(h).intentExamples.join(`
447
- `))}}),placeholder:"Similar questions, one per line",rows:3,style:{...we(e,{size:"sm"}),resize:"vertical"}}),s.jsx("textarea",{value:Ke(h).avoid.join(`
448
- `),onChange:D=>g({...h,lesson:{...Ke(h),avoid:D.target.value.split(/\r?\n/)}}),onBlur:()=>g({...h,lesson:{...Ke(h),avoid:ia(Ke(h).avoid.join(`
449
- `))}}),placeholder:"Known mistakes to avoid, one per line",rows:2,style:{...we(e,{size:"sm"}),resize:"vertical"}}),s.jsx("input",{value:Ke(h).expectedOutcome??"",onChange:D=>g({...h,lesson:{...Ke(h),expectedOutcome:D.target.value||void 0}}),placeholder:"Expected outcome or result shape",style:we(e,{size:"sm"})})]})]}),s.jsx("textarea",{value:h.correctedSql??"",onChange:D=>g({...h,correctedSql:D.target.value}),placeholder:"Read-only corrected SQL",rows:5,style:{...we(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(([D,$])=>s.jsxs("label",{style:{display:"grid",gap:3,fontSize:10,color:e.textMuted},children:[$,s.jsx("input",{value:h.scope[D]??"",onChange:Q=>g({...h,scope:Qv(h.scope,D,Q.target.value)}),placeholder:`Optional ${$}`,style:we(e,{size:"sm"})})]},D))}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void k(),style:we(e,{variant:"primary",size:"sm",disabled:l===y.id}),children:"Save & recheck"}),s.jsx("button",{type:"button",onClick:()=>g(null),style:we(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:D=>p({...f,[y.id]:D.target.value}),placeholder:"Reviewer note or result assertion (required evidence when this surface cannot execute)",rows:2,style:{...we(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:we(e,{variant:"primary",size:"sm",disabled:l===y.id}),children:l===y.id?"Checking…":Gv(y)}),s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>g({...y,lesson:Ke(y)}),style:we(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:we(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:we(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:we(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:we(e,{variant:"danger",size:"sm",disabled:l===y.id}),children:"Retire"}),M.map(D=>s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void b(y,"supersede",D.relatedHintId),style:we(e,{size:"sm",disabled:l===y.id}),children:"Keep this; supersede conflict"},D.relatedHintId))]}):null,y.status==="retired"?s.jsx("button",{type:"button",disabled:l===y.id,onClick:()=>void b(y,"reopen"),style:we(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 sS({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 O=await N.listAgentMemory();n(O.memories)},g=async O=>{await N.deleteAgentMemory(O),await h(),r("Memory deleted.")},[S,x]=u.useState(!1),[b,k]=u.useState("all"),[C,E]=u.useState(null),v=O=>O==="project"?{label:"project",bg:"var(--accent-dim)",color:t.accent}:O==="user"?{label:"just me",bg:`${t.textMuted}1f`,color:t.textMuted}:{label:O,bg:"var(--status-success-bg)",color:"var(--status-success)"},w=e.filter(O=>b==="all"?!0:b==="project"?O.scope==="project":O.scope==="user"),A=O=>{E(O.id),i(O.scope),a(O.title),c(O.content),p(O.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 O=l.trim()||d.trim().slice(0,60);await N.saveAgentMemory({scope:o,title:O,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=(O,T)=>s.jsx("button",{type:"button",onClick:()=>k(O),style:{border:"none",borderRadius:5,padding:"4px 11px",fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:t.font,background:b===O?"var(--accent-dim)":"transparent",color:b===O?t.accent:t.textMuted},children:T},O);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:O=>c(O.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:O=>i(O.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:O=>p(O.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(O=>{const T=!["settings-ui","manual",""].includes(O.source),L=v(O.scope),I=T?`Saved from ${O.source}${typeof O.confidence=="number"?` · ${Math.round(O.confidence*100)}% confidence`:""}`:`Added by hand${O.tags.length?` · ${O.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:O.content||O.title}),s.jsx("div",{style:{fontSize:10.5,color:t.textMuted,marginTop:4},children:I})]}),s.jsx("button",{type:"button",title:"Edit",onClick:()=>A(O),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(O.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:"🗑"})]},O.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 aa({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(aS,{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 iS({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 aS({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 gt(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 la(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 lS(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=>ca({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=>ca({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 cS(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(...dS(t.tools)),Array.isArray(t.mcp_servers)&&n.push(...uS(t.mcp_servers)),Qt(t.mcpServers)&&n.push(...pS(t.mcpServers)),n.map(Yt)}function dS(e){return e.flatMap((t,n)=>{if(!Qt(t)||t.type!=="mcp")return[];const r=Ge(t,["connectorId","connector_id"]),o=Ge(t,["authorization"]);return r?[Yt({kind:"connector",name:Ge(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:Ge(t,["name","server_label","serverLabel"]),url:Ge(t,["url","server_url","serverUrl"]),authorizationToken:o??zs(t.headers),allowedTools:Hn(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]},"server",`tools[${n}]`)]})}function uS(e){return e.map((t,n)=>{const r=Fr(t,"server",`mcp_servers[${n}]`);return Yt({...r,authorizationToken:r.authorizationToken??(Qt(t)?Ge(t,["authorization_token"]):void 0),providers:["anthropic"]})})}function pS(e){return Object.entries(e).map(([t,n])=>{if(!Qt(n))throw new Error(`mcpServers.${t} must be an object.`);const r=Ge(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:zs(n.headers),enabled:n.enabled!==!1,trusted:n.trusted===!0,allowedTools:Hn(n,["allowedTools","allowed_tools"]),providers:dd(n,["providers"])??["openai","anthropic"]})})}function Fr(e,t,n){if(!Qt(e))throw new Error(`${n} must be an object.`);const r=Ge(e,["name","server_label","serverLabel"]);if(!r)throw new Error(`${n} needs a name.`);const o=Ge(e,["url","server_url","serverUrl"]),i=Ge(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:Ge(e,["description","server_description","serverDescription"]),authorizationToken:Ge(e,["authorizationToken","authorization","authorization_token"])??zs(e.headers),authorizationTokenEnv:Ge(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:dd(e,["providers"])}}function ca(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 Ge(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 dd(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 zs(e){if(!Qt(e))return;const t=Ge(e,["Authorization","authorization"]);return(t==null?void 0:t.replace(/^Bearer\s+/i,"").trim())||void 0}function da(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 Ao(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}const fS=e=>new Promise(t=>{window.setTimeout(t,e)});async function hS({jobId:e,loadStatus:t,onCompleted:n,onFailed:r,isCancelled:o=()=>!1,wait:i=fS,intervalMs:l=700}){for(;!o();){if(await i(l),o())return;const a=await t();if(o())return;const d=a.job;if(!d||d.id!==e)return;if(!(d.state==="queued"||d.state==="running")){d.state==="completed"?await n(a):d.state==="failed"&&await r(a);return}}}function mS(e){return/^(?:https?:\/\/|ssh:\/\/|git@|file:\/\/)/i.test(e.trim())}function gS(e){const t=e.trim();return t?mS(t)?{repoUrl:t}:{projectDir:t}:{}}const To={auto:"Auto",native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function yS({compact:e=!1,reapplyRequired:t=!1,onConfigured:n}){var Rt,zt,qt,Ut;const{state:r,dispatch:o}=ve(),i=ze[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(""),[O,T]=u.useState(""),[L,I]=u.useState(null),[V,X]=u.useState(null),[J,W]=u.useState(null),[D,$]=u.useState(""),[Q,q]=u.useState(!1),ee=u.useCallback(async()=>{const F=await N.getSemanticRuntimeSettings();return w(F),R(F.dbtCloud.host??""),M(F.dbtCloud.environmentId??""),T(""),F},[]),H=u.useCallback(async()=>{const F=await N.getMetricFlowInstallerStatus();return W(F),$(te=>te||F.recommendedAdapter||F.supportedAdapters[0]||""),F},[]),B=u.useCallback(async()=>{var de,kt,se;const[F,te]=await Promise.all([N.getOnboardingStatus(),N.getBlockStudioDbtStatus().catch(()=>null)]);a(F),x(F.preparation??null);const be=((de=F.dbt)==null?void 0:de.configured)===!0||!!(te!=null&&te.configured&&te.artifacts.manifest.exists);c(be);const fe=((kt=F.dbt)==null?void 0:kt.repoUrl)||((se=F.dbt)==null?void 0:se.projectDir)||(te==null?void 0:te.projectPath)||"";return p(be?fe:""),F},[]);u.useEffect(()=>{let F=!0;return B().catch(te=>F&&E({ok:!1,text:te instanceof Error?te.message:String(te)})).finally(()=>F&&k(null)),()=>{F=!1}},[B]),u.useEffect(()=>{let F=!0;return Promise.all([ee(),H()]).catch(te=>{F&&X({ok:!1,text:te instanceof Error?te.message:String(te)})}),()=>{F=!1}},[H,ee]),u.useEffect(()=>{const F=J==null?void 0:J.job;if(!F||F.state!=="queued"&&F.state!=="running")return;let te=!1;return hS({jobId:F.id,loadStatus:H,isCancelled:()=>te,onCompleted:async be=>{var de;await ee();const fe=await N.getSemanticLayer();te||(o({type:"SET_SEMANTIC_LAYER",layer:fe}),X({ok:!0,text:((de=be.job)==null?void 0:de.message)||"Local MetricFlow is installed and ready."}))},onFailed:be=>{var fe,de;te||X({ok:!1,text:((fe=be.job)==null?void 0:fe.error)||((de=be.job)==null?void 0:de.message)||"Local MetricFlow installation failed."})}}).catch(be=>{te||X({ok:!1,text:be instanceof Error?be.message:String(be)})}),()=>{te=!0}},[o,H,ee,(Rt=J==null?void 0:J.job)==null?void 0:Rt.id]),u.useEffect(()=>{if(!S||S.status!=="queued"&&S.status!=="running")return;let F=!0,te;const be=async()=>{try{const fe=await N.getOnboardingJob(S.id);if(!F)return;const de=Ao(fe);if(!de)return;x(de),de.status==="completed"?(await B(),F&&E({ok:!0,text:de.message||"dbt metadata and governed search indexes are ready."})):de.status==="failed"||de.status==="cancelled"?E({ok:!1,text:de.error||de.message||`dbt preparation ${de.status}.`}):te=window.setTimeout(()=>void be(),650)}catch(fe){F&&E({ok:!1,text:fe instanceof Error?fe.message:String(fe)})}};return te=window.setTimeout(()=>void be(),350),()=>{F=!1,te!==void 0&&window.clearTimeout(te)}},[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(gS(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}),te=Ao(F);te&&x(te);const be=await B();await H();const fe=be.preparation??te,de=`${h.counts.models??0} models · ${h.counts.sources??0} sources · ${h.counts.metrics??0} metrics`;E({ok:!0,text:(fe==null?void 0:fe.status)==="completed"?fe.message||`Connected ${h.projectName||h.projectDir}. Governed search is ready.`:fe?`Connected ${h.projectName||h.projectDir}. DQL is preparing ${de} for fast governed search in the background.`:`Applied ${h.projectName||h.projectDir}. ${de}.`}),n==null||n({name:h.projectName||"dbt project",path:h.projectDir,summary:de,readiness:(fe==null?void 0:fe.status)==="completed"?"ready":"preparing",readinessDetail:fe==null?void 0:fe.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({}),te=await N.refreshDbtOnboarding({expectedFingerprint:F.fingerprint}),be=Ao(te);be&&x(be);const de=(await B()).preparation??be;E({ok:!0,text:(de==null?void 0:de.status)==="completed"?de.message||"dbt artifacts and governed search indexes are ready.":de?"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)}},ye=()=>({preference:(v==null?void 0:v.preference)??"auto",dbtCloud:{host:A,environmentId:y,serviceToken:O}}),xe=async F=>{I("apply"),X(null);try{const te=await N.setSemanticRuntimePreference(F);w(te),X({ok:!0,text:`Preferred runtime set to ${To[F]??F}.`})}catch(te){X({ok:!1,text:te instanceof Error?te.message:String(te)})}finally{I(null)}},Te=async()=>{I("test"),X(null);try{const F=await N.testDbtCloudSemanticRuntime(ye());X({ok:F.ok,text:F.message||F.error||"dbt Cloud Semantic Layer test failed."})}finally{I(null)}},qe=async()=>{I("apply"),X(null);try{const F=await N.applyDbtCloudSemanticRuntime(ye());w(F),T(""),X({ok:!0,text:`${F.dbtCloud.testMessage||"dbt Cloud Semantic Layer tested."} Compilation is now bound to the active warehouse target.`})}catch(F){X({ok:!1,text:F instanceof Error?F.message:String(F)})}finally{I(null)}},Le=async()=>{if(!D){X({ok:!1,text:"Choose the warehouse adapter used by this dbt project."});return}q(!0),X(null);try{const F=await N.installMetricFlow(D);W(te=>te?{...te,job:F.job}:{job:F.job,recommendedAdapter:D,supportedAdapters:[D],projectConfigured:!0,semanticManifestFound:!1})}catch(F){X({ok:!1,text:F instanceof Error?F.message:String(F)})}finally{q(!1)}},Se=d,ue=(J==null?void 0:J.job)??null,Ne=Q||(ue==null?void 0:ue.state)==="queued"||(ue==null?void 0:ue.state)==="running",Ue=(ue==null?void 0:ue.state)==="failed",Oe=(S==null?void 0:S.status)==="queued"||(S==null?void 0:S.status)==="running",Me=(S==null?void 0:S.status)==="failed"||(S==null?void 0:S.status)==="cancelled",et=t?"Reapply required after DQL update":Me?"dbt project needs attention":Oe?"Preparing governed search":Se?"dbt project ready":"dbt project missing",mt=t?"Review the prefilled project, choose Preview, then Reapply project.":(S==null?void 0:S.message)??(Se?((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."),at={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"},tt={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)":Me?"var(--status-error-border)":Oe?"var(--status-info-border)":Se?"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)":Me?"var(--status-error)":Oe?"var(--status-info)":Se?"var(--status-success)":"var(--status-warning)",background:t?"var(--status-warning-bg)":Me?"var(--status-error-bg)":Oe?"var(--status-info-bg)":Se?"var(--status-success-bg)":"var(--status-warning-bg)"},children:t?s.jsx(Ir,{size:17}):Me?s.jsx(Zg,{size:17}):Oe?s.jsx(Fn,{className:"dql-dbt-preparing-icon",size:17}):Se?s.jsx(Mc,{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:et}),s.jsx("div",{style:{fontSize:11.5,color:Me?"var(--status-error)":i.textMuted,marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:mt}),Oe?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]}),Se&&!t?s.jsxs("button",{type:"button",onClick:()=>void re(),disabled:!!b,style:tt,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:at})]}),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:tt,children:b==="preview"?"Inspecting…":"Preview"}),h?s.jsx("button",{type:"button",onClick:()=>void ce(),disabled:!!b,style:{...tt,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=>{xe(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:To[v.runtime.active]??v.runtime.active}),v.preference&&v.preference!=="auto"&&v.preference!==v.runtime.active?` (preferred ${To[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:D,onChange:te=>$(te.target.value),disabled:Ne,style:{...at,width:160,height:32,fontFamily:i.font},children:((J==null?void 0:J.supportedAdapters)??[]).map(te=>s.jsx("option",{value:te,children:te==="postgres"?"PostgreSQL":te.charAt(0).toUpperCase()+te.slice(1)},te))}),s.jsxs("button",{type:"button",onClick:()=>void Le(),disabled:!Se||Ne||!D,style:{...tt,border:"none",background:i.accent,color:"#fff",opacity:!Se||Ne||!D?.55:1,cursor:!Se||Ne?"not-allowed":"pointer"},children:[Ne?s.jsx(Fn,{className:"dql-dbt-preparing-icon",size:12,style:{verticalAlign:-2,marginRight:6}}):s.jsx(Ic,{size:12,style:{verticalAlign:-2,marginRight:6}}),Ne?"Installing…":"Install local MetricFlow"]})]}),Se?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:Ue?"alert":"status",style:{fontSize:10.5,color:Ue?"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:Ue?"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:Ue?"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:at})]}),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:at})]}),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:O,onChange:F=>T(F.target.value),placeholder:(v==null?void 0:v.dbtCloud.serviceTokenPreview)||"Semantic Layer service token",autoComplete:"off",style:at}),s.jsx("span",{style:{fontSize:9.5,color:i.textMuted},children:"Requires Semantic Layer and Metadata permissions. Leave blank to preserve the stored token."})]}),V?s.jsx("div",{role:V.ok?"status":"alert",style:{fontSize:11,color:V.ok?"var(--status-success)":"var(--status-error)"},children:V.text}):null,s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void Te(),disabled:!!L,style:tt,children:L==="test"?"Testing…":"Test draft"}),s.jsx("button",{type:"button",onClick:()=>void qe(),disabled:!!L,style:{...tt,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 Ro(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 xS(e,t,n){return e.some(r=>r.catalogOrDatabase.toLowerCase()===t.toLowerCase()&&r.schemas.some(o=>o.toLowerCase()===n.toLowerCase()))}function bS(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 vS(e){return e.scopes.reduce((t,n)=>t+n.schemas.filter(r=>!r.inDbtProject).length,0)}const _o={duckdb:"DuckDB",file:"Local File / DuckDB",snowflake:"Snowflake",databricks:"Databricks"},Tr={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"},SS={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"}]}],qs=Object.fromEntries(io.map(e=>[e.driver,e])),kS=[{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 es(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 wS(e){return`${e.profileName}_${e.targetName}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"dbt_profile"}function jS(e){const t={};return Object.entries(e.connection??{}).forEach(([n,r])=>{n!=="driver"&&r!==void 0&&r!==null&&(t[es(n)]=String(r))}),t}function CS(e){const n=e.indexOf("/.dbt/");return n>=0?`~${e.slice(n)}`:e.split("/").slice(-3).join("/")}function ES(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 ua(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 AS(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 TS(e){const t=Object.keys(e);return t.find(n=>!Gn(e[n]))??t[0]}function ud({variant:e="panel",onConfigured:t}={}){var Xs,Zs,ei,ti;const{state:n,dispatch:r}=ve(),o=ze[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,O]=u.useState(!1),[T,L]=u.useState(null),[I,V]=u.useState([]),[X,J]=u.useState(!1),[W,D]=u.useState(null),[$,Q]=u.useState("dbt_relations"),[q,ee]=u.useState(""),[H,B]=u.useState(!1),[ne,ce]=u.useState(null),[re,ye]=u.useState(null),[xe,Te]=u.useState(!1),[qe,Le]=u.useState(""),[Se,ue]=u.useState("duckdb"),[Ne,Ue]=u.useState({}),[Oe,Me]=u.useState("duckdb"),[et,mt]=u.useState({}),at=u.useRef(null);u.useEffect(()=>{N.getConnections().then(_=>{d(_),_.metadataScope&&(Q(_.metadataScope.mode),ee(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;_&&(V(z.providers),J(((ae=oe.dbt)==null?void 0:ae.configured)===!0||!!(Z!=null&&Z.configured&&Z.artifacts.manifest.exists)),D(oe.preparation??null))}).catch(()=>{}),()=>{_=!1}},[i]),u.useEffect(()=>{if(!i||!W||W.status!=="queued"&&W.status!=="running")return;let _=!0,z;const oe=async()=>{var Z,ae,me;try{const Ie=await N.getOnboardingStatus();if(!_)return;D(Ie.preparation??null),J(((Z=Ie.dbt)==null?void 0:Z.configured)===!0),(((ae=Ie.preparation)==null?void 0:ae.status)==="queued"||((me=Ie.preparation)==null?void 0:me.status)==="running")&&(z=window.setTimeout(()=>void oe(),700))}catch{}};return z=window.setTimeout(()=>void oe(),500),()=>{_=!1,z!==void 0&&window.clearTimeout(z)}},[W==null?void 0:W.id,W==null?void 0:W.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(at.current!==oe)if(at.current=oe,z){Me(Mn(String(z.driver??z.type??"duckdb")));const ae={};Object.entries(z).forEach(([me,Ie])=>{me!=="driver"&&me!=="type"&&(ae[es(me)]=String(Ie??""))}),mt(ae)}else Me("duckdb"),mt({})},[a]);const tt=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)},Rt=_=>{d(z=>z&&{...z,metadataScope:_.scope,metadataStatus:_.status}),Q(_.scope.mode),ee(Sr(_.scope.selectedScopes??_.scope.scopes))},zt=async()=>{if(!(!(a!=null&&a.default)||!(p!=null&&p.ok))){Te(!0),ce("Finding databases/catalogs and schemas visible to this connection…");try{const _=await N.discoverConnectionMetadataScopes(a.default);ye(_),ce(_.message)}catch(_){ye(null),ce(_ instanceof Error?_.message:String(_))}finally{Te(!1)}}},qt=(_,z,oe)=>{const Z=bS(Ro(q),_,z,oe);ee(Sr(Z)),Q(((re==null?void 0:re.dbtScopes.length)??0)>0?"dbt_plus_selected":"selected_scopes")},Ut=async()=>{if(!(a!=null&&a.default))return;const _=Ro(q);if($==="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:$,...$==="dbt_relations"?{}:{scopes:_}});Rt(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)}},F=async()=>{if(a!=null&&a.default){B(!0),ce("Refreshing the applied metadata scope…");try{const _=await N.refreshConnectionMetadata(a.default);Rt(_),ce(`Refreshed · ${_.status.relationCount.toLocaleString()} relations · ${_.status.columnCount.toLocaleString()} columns`)}catch(_){ce(_ instanceof Error?_.message:String(_))}finally{B(!1)}}},te=(_,z)=>{S(_),b(!1),Le(_),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[es(Z)]=String(ae??""))}),Ue(oe)},be=()=>{b(!0),S(null),Le(""),ue("duckdb"),Ue({})},fe=()=>{S(null),b(!1)},de=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)}},kt=async _=>{if(!a)return!1;C(!0),v(null);const z=_.name.trim()||(_.previousName??"default"),oe={driver:_.driver},Z=qs[_.driver],ae=new Map(((Z==null?void 0:Z.fields)??[]).map(Be=>[Be.key,Be]));Object.entries(_.fields).forEach(([Be,We])=>{const ct=ae.get(Be);if((ct==null?void 0:ct.type)==="checkbox"){We!==""&&(oe[Be]=We==="true");return}const ar=We.trim();ar&&((ct==null?void 0:ct.type)==="number"&&!isNaN(Number(ar))?oe[Be]=Number(ar):oe[Be]=ar)});const me={...a.connections},Ie=a.default,tn={...a.connections};_.previousName&&_.previousName!==z&&delete tn[_.previousName],tn[z]=oe;const Ld=AS(tn,a.default,z,_.previousName);let ni=!1;try{await N.saveConnections(tn,Ld);const Be=await N.getConnections();d(Be),Be.metadataScope&&(Q(Be.metadataScope.mode),ee(Sr(Be.metadataScope.selectedScopes??Be.metadataScope.scopes))),ye(null),v("Saved. Testing connection..."),S(null),b(!1);try{f(!0);const We=await N.testConnection();if(h(We),ni=We.ok,We.ok)v("Test passed. Connection saved and activated."),t==null||t(We.message),setTimeout(()=>v(null),2e3);else{await N.saveConnections(me,Ie||void 0);const ct=await N.getConnections();d(ct),v(`Test failed. Previous connection preserved: ${We.message}`)}}catch(We){await N.saveConnections(me,Ie||void 0).catch(()=>{});const ct=await N.getConnections().catch(()=>null);ct&&d(ct),v(`Test failed. Previous connection preserved: ${We.message??"Connection failed"}`)}finally{f(!1)}}catch(Be){await N.saveConnections(me,Ie||void 0).catch(()=>{});const We=await N.getConnections().catch(()=>null);We&&d(We),v(`Test or save failed. Previous connection preserved: ${Be.message}`)}finally{C(!1)}return ni},se=_=>{const z=Mn(String(_.connection.driver??_.adapter??"duckdb")),oe=jS(_);h(null),(i||l)&&(Me(z),mt(oe)),b(!1),S(null),kt({name:wS(_),driver:z,fields:oe,previousName:null})},G=async()=>{const _=R.trim();if(!_){L("Enter a profiles.yml file or folder path.");return}O(!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{O(!1)}},Re=()=>kt({name:qe,driver:Se,fields:Ne,previousName:g}),wn=()=>kt({name:(a==null?void 0:a.default)||"default",driver:Oe,fields:et,previousName:(a==null?void 0:a.default)||null}),en=_=>{Me(_),mt({}),h(null)},nr=async _=>{if(!a)return;const z={...a.connections};delete z[_];const oe=_===a.default?TS(z):a.default;C(!0);try{await N.saveConnections(z,oe);const Z=await N.getConnections();d(Z),S(null)}finally{C(!1)}},Ad=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)??{},Td=(a==null?void 0:a.default)??"",Vs=(a==null?void 0:a.dbtProfiles)??[],Hs=Object.fromEntries(((a==null?void 0:a.connectorStatus)??[]).map(_=>[_.driver,_])),Gs=Object.keys(sr).length,ir=Gs>0,Rd=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=_===Td,ae=Tr[oe]??o.accent;return g===_?s.jsx(pa,{t:o,editName:qe,setEditName:Le,editDriver:Se,setEditDriver:ue,editFields:Ne,setEditFields:Ue,onSave:Re,onCancel:fe,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:_o[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:()=>Ad(_),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:()=>te(_,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(([me])=>me!=="driver"&&me!=="type").map(([me,Ie])=>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:me}),s.jsx("span",{style:{fontSize:11,color:o.textSecondary,fontFamily:o.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ES(me)?"••••••••":String(Ie)})]},me))})]},_)}),a!==null&&Gs===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."})]}),Js=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(),G())},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 G(),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]}),Qs=s.jsx(s.Fragment,{children:!x&&!g&&Vs.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:Vs.map(_=>{var me;const z=Mn(String(_.connection.driver??_.adapter)),oe=Tr[z]??o.accent,Z=_.missingFields.length===0,ae=((me=a==null?void 0:a.activeConnection)==null?void 0:me.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:[_o[z]??_.adapter," from ",CS(_.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:()=>se(_),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)})})]})}),_d=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:kS.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))})]})}),$d=s.jsx(s.Fragment,{children:x?s.jsx(pa,{t:o,editName:qe,setEditName:Le,editDriver:Se,setEditDriver:ue,editFields:Ne,setEditFields:Ue,onSave:Re,onCancel:fe,saving:k,isNew:!0}):s.jsxs("button",{onClick:be,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"]})}),Od=s.jsx(s.Fragment,{children:E&&s.jsx("div",{style:{fontSize:11,fontFamily:o.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:ua(E,o),background:`${ua(E,o)}12`},children:E})}),Pd=s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:tt,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]})]}),Dd=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=SS[_]??"",ae=Hs[_],me=(ae==null?void 0:ae.installed)??!0,Ie=(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:me?o.success:o.warning,letterSpacing:"0.05em",textTransform:"uppercase"},children:Ie?"Built in":me?"Installed":"Install required"}),!me&&s.jsx("button",{onClick:()=>de(_),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:_})]},_)})})]}),lt=!!(a&&Object.values(a.connections??{}).some(_=>!Gn(_))),_e=a==null?void 0:a.metadataStatus,Md=Ro(q),Id=lt?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 zt(),disabled:xe||H||!(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:xe||H||!(p!=null&&p.ok)?"not-allowed":"pointer",opacity:p!=null&&p.ok?1:.55,fontFamily:o.font},children:xe?"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)"," · ",vS(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=xS(Md,_.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||H,onChange:Z=>qt(_.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:$,onChange:_=>Q(_.target.value),disabled:H,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"})]})]}),$!=="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:q,onChange:_=>ee(_.target.value),disabled:H,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,_e?s.jsxs("div",{style:{fontSize:11.5,color:_e.state==="ready"?"var(--status-success)":"var(--status-warning)",fontFamily:o.font},children:[_e.state==="ready"?"Ready":_e.state==="stale"?"Refresh required":"Not synchronized"," · ",_e.relationCount.toLocaleString()," relations"," · ",_e.columnCount.toLocaleString()," columns",_e.capturedAt?` · ${new Date(_e.capturedAt).toLocaleString()}`:""]}):null,_e!=null&&_e.observedTarget?s.jsx("div",{style:{fontSize:10.5,color:o.textMuted,fontFamily:o.fontMono},children:[_e.observedTarget.accountOrWorkspace,_e.observedTarget.role,_e.observedTarget.warehouse,_e.observedTarget.defaultCatalogOrDatabase,_e.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 Ut(),disabled:H||!(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:H||!(p!=null&&p.ok)?"not-allowed":"pointer",opacity:H||!(p!=null&&p.ok)?.55:1,fontFamily:o.font},children:H?"Synchronizing…":"Apply and synchronize"}),s.jsx("button",{type:"button",onClick:()=>void F(),disabled:H||(_e==null?void 0:_e.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:H?"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,Ys=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:lt?"var(--status-success-bg)":"var(--status-warning-bg)",color:lt?"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:[_o[String(((Zs=(Xs=a==null?void 0:a.connections)==null?void 0:Xs[(a==null?void 0:a.default)??""])==null?void 0:Zs.driver)??"")]??((ti=(ei=a==null?void 0:a.connections)==null?void 0:ei[(a==null?void 0:a.default)??""])==null?void 0:ti.driver)??"No connection yet",lt?" · 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}`:lt?"Configured — run Test connection to verify.":"Add a connection below to get started."})]}),s.jsx("button",{type:"button",onClick:()=>void tt(),disabled:c||!lt,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:lt?"pointer":"not-allowed",fontFamily:o.font,flexShrink:0,opacity:lt?1:.55},children:c?"Testing…":"Test connection"})]}),s.jsxs("div",{style:{maxWidth:640},children:[Js,Qs]}),s.jsx(OS,{t:o,driver:Oe,fields:et,onDriverChange:en,onFieldsChange:mt,onSave:()=>void wn(),saving:k,saveMessage:E,connectorStatus:Hs[Oe],installing:w===Oe,onInstall:()=>void de(Oe)}),Id]});if(l)return Ys;if(i){const _=n.settingsTab,z=I.some(Z=>Z.configured&&Z.enabled),oe=(Z,ae,me,Ie)=>s.jsxs("button",{type:"button",onClick:me,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}),Ie]},ae);return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:_S}),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:(W==null?void 0:W.status)==="failed"?"var(--status-error)":(W==null?void 0:W.status)==="running"||(W==null?void 0:W.status)==="queued"?"var(--status-info)":X?"var(--status-success)":"var(--status-warning)"},title:(W==null?void 0:W.status)==="failed"?"Needs attention":(W==null?void 0:W.status)==="running"||(W==null?void 0:W.status)==="queued"?"Preparing":X?"Ready":"Missing"})),oe(_==="database","Database",()=>r({type:"SET_SETTINGS_TAB",tab:"database"}),s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:lt?"var(--status-success)":"var(--status-warning)"},title:lt?"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(RS,{dbtConfigured:X,dbtPreparation:W,databaseConfigured:lt,databaseTest:p,providers:I}):_==="project"?s.jsx(yS,{onConfigured:()=>{J(!0),N.getOnboardingStatus().then(Z=>D(Z.preparation??null)).catch(()=>{})}}):_==="advanced"?s.jsx(Co,{embedded:!0,section:"advanced"}):_==="database"?Ys:_==="ai"?s.jsx(Co,{embedded:!0,section:"providers",onProviderConfigured:Z=>V(ae=>ae.map(me=>me.id===Z.id?Z:{...me,active:!1}))}):s.jsx(Co,{embedded:!0,section:"memory"})})]})]})}return s.jsxs(_s,{title:"Connections",bodyPadding:12,children:[Rd,Js,Qs,_d,$d,Od,Pd,Dd]})}function RS({dbtConfigured:e,dbtPreparation:t,databaseConfigured:n,databaseTest:r,providers:o}){const{state:i,dispatch:l}=ve(),a=ze[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(Fc,{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(dx,{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(Mc,{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 _S=`
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 pa({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=qs[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 $S(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 fa=new Set(["filepath","httpPath","accessUrl"]);function OS({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=qs[t],S=(g==null?void 0:g.fields)??[],x=$S(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(PS,{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(ha,{t:e,field:v,value:n[v.key]??"",onChange:w=>E(v.key,w),fullWidth:fa.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(ha,{t:e,field:v,value:n[v.key]??"",onChange:w=>E(v.key,w),fullWidth:fa.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 PS({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 ha({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 DS=Object.freeze(Object.defineProperty({__proto__:null,ConnectionPanel:ud},Symbol.toStringTag,{value:"Module"}));function MS({type:e}){const t=ib[e]??"#8b949e";return s.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:Wc[e]??e,children:ab[e]??e.slice(0,4).toUpperCase()})}function IS({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 pd({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(MS,{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 LS=30,$o=200;function Ye(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 Oo({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 Ve({title:e,nodes:t,t:n,onSelect:r,secondaryFor:o}){const i=t.length>LS,[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(pd,{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 NS({variant:e="sidebar"}){const{state:t,dispatch:n}=ve(),r=ze[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 O=db(M);y[O].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(IS,{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(pd,{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(Oo,{Icon:Ug,label:"Business",value:A.businessNodes,detail:`${w.terms.length} terms · ${w.businessViews.length} views · ${A.businessEdges} edges`,t:r}),s.jsx(Oo,{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(Oo,{Icon:Vy,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:[Wi.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:lb[y],display:"inline-block"}}),Ui[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(Ve,{title:"Business Terms",nodes:w.terms,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Business Views",nodes:w.businessViews,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"DQL Blocks",nodes:w.blocks,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Metrics",nodes:w.metrics,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Dimensions",nodes:w.dimensions,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Dashboards",nodes:w.dashboards,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Notebooks",nodes:w.notebooks,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Apps",nodes:w.apps,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Charts",nodes:w.charts,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"dbt Models",nodes:w.dbtModels,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"dbt Sources",nodes:w.dbtSources,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Source Tables",nodes:w.tables,t:r,onSelect:C,secondaryFor:Ye}),s.jsx(Ve,{title:"Business Domains",nodes:w.domains,t:r,onSelect:C,secondaryFor:Ye})]}):s.jsx(s.Fragment,{children:Wi.map(y=>s.jsx(Ve,{title:Ui[y],nodes:R[y],t:r,onSelect:C},y))})]})]})}function BS({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:ga(r==null,l),children:"All"}),n&&s.jsx("button",{onClick:o,style:ga(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(FS,{report:t,t:l}),!a&&d&&s.jsx(US,{diff:e,t:l}),!a&&!d&&s.jsx("div",{style:{color:l.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function FS({report:e,t}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>s.jsx(zS,{change:n,t},r))})}function zS({change:e,t}){const{marker:n,color:r,label:o}=WS(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(qS,{field:l,t},a))})]})}function qS({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:ma(e.before)}),s.jsx("span",{style:{color:t.textMuted},children:" → "}),s.jsx("span",{style:{color:t.success},children:ma(e.after)})]})}function US({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:KS(n,t)},children:n||" "},r))})}function WS(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 ${Po(e.id,e.name)} [${e.cellType}]`};case"cell-removed":return{...n,label:`cell ${Po(e.id,e.name)} [${e.cellType}]`};case"cell-changed":return{...r,label:`cell ${Po(e.id,e.name)}`};case"notebook-changed":return{...r,label:"notebook"}}}function Po(e,t){return t?`"${t}" (${e.slice(0,8)})`:e.slice(0,8)}function ma(e,t=60){if(e==null)return"∅";const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}function ga(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 KS(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const VS=2e3,HS={modified:{label:"Modified",color:e=>e.warning,Icon:yy},added:{label:"Added",color:e=>e.success,Icon:Nc},deleted:{label:"Deleted",color:e=>e.error,Icon:Cy},renamed:{label:"Renamed",color:e=>e.accent,Icon:Pg},untracked:{label:"Untracked",color:e=>e.textMuted,Icon:vy}},ya=["modified","added","renamed","deleted","untracked"];function GS(e){const t=e.trim();return t==="??"?"untracked":t.startsWith("R")?"renamed":t.includes("D")?"deleted":t.includes("A")?"added":"modified"}function JS(){var A;const{state:e}=ve(),t=ze[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=>QS(M,y)?M:y)})},VS);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(Pc,{children:[s.jsx(Do,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),s.jsx(Do,{t,active:n==="log",onClick:()=>r("log"),children:"History"}),s.jsx(Do,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"})]});return s.jsxs(_s,{title:"Git",actions:v,toolbar:w,bodyPadding:12,children:[S&&!o&&!l&&s.jsx(Nn,{title:"Loading…"}),n==="status"&&o&&s.jsx(YS,{status:o,t}),n==="log"&&l&&s.jsx(n0,{log:l,t}),n==="diff"&&s.jsx(BS,{diff:d,diffReport:f,activeFilePath:E,diffPath:h,onScopeToFile:()=>g(E),onClearScope:()=>g(null),t})]})}function QS(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 YS({status:e,t}){const n=u.useMemo(()=>{const r={modified:[],added:[],deleted:[],renamed:[],untracked:[]};for(const o of e.changes)r[GS(o.status)].push(o);for(const o of ya)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(XS,{status:e,t}),e.changes.length===0?s.jsx(ZS,{t}):ya.map(r=>{const o=n[r];return o.length===0?null:s.jsx(e0,{group:r,items:o,t},r)})]}):s.jsx(fd,{t})}function XS({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:Mo(t.success,t),children:[s.jsx(Mg,{size:11,strokeWidth:2})," ",n]}),r>0&&s.jsxs("span",{title:`${r} commit(s) behind upstream`,style:Mo(t.warning,t),children:[s.jsx($g,{size:11,strokeWidth:2})," ",r]}),n===0&&r===0&&s.jsx("span",{style:{...Mo(t.textMuted,t),opacity:.7},children:"up to date"})]})}function ZS({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(my,{size:14,strokeWidth:1.75,color:e.success}),"Working tree clean"]})}function fd({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 e0({group:e,items:t,t:n}){const r=HS[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(t0,{change:l,t:n,color:o,divider:a<t.length-1},l.path))})]})}function t0({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 n0({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(Iy,{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(fd,{t})}function Do({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 Mo(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 r0(e){const{state:t,dispatch:n}=ve(),r=ze[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(Pc,{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(_s,{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(Oc,{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 o0={files:"Build",block_library:"Build",lineage:"Lineage",connection:"Connection",git:"Git",apps:"Apps"};function s0({onOpenFile:e}){const{state:t,dispatch:n}=ve(),r=ze[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:o0[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(Ov,{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(NS,{}),g==="connection"&&s.jsx(ud,{}),g==="git"&&s.jsx(JS,{}),g==="apps"&&s.jsx(r0,{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 hd=2;function i0(e,t={}){const n=t.version??hd,r=JSON.parse(e),{dqlnbVersion:o,...i}=r,l={dqlnbVersion:n,...i};return JSON.stringify(l,a0(),2)+`
482
- `}function a0(){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=xa[l],c=xa[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 xa={dqlnbVersion:0,version:1,title:2,metadata:3,cells:4,id:10,type:11,name:12,content:13};function l0(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:nt(),type:"markdown",content:`# ${l}`,status:"idle"}),a&&r.push({id:nt(),type:"dql",name:l.toLowerCase().replace(/\s+/g,"_"),content:a,status:"idle"})}return r.length===0&&r.push({id:nt(),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:nt(),type:"dql",content:e.trim(),status:"idle"}]}}}const c0=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 d0(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",o=Ho((n.cells||[]).map(a=>{const d=Object.fromEntries(Object.entries(a).filter(([c])=>!c0.has(c)));return{id:a.id||nt(),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:nt(),type:"sql",content:e,status:"idle"}]}}}function u0(e,t,n){const r={dqlnbVersion:hd,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 i0(JSON.stringify(r))}function p0(e,t){return e.endsWith(".dql")?l0(t):d0(t)}const md=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function J1(e){const t=new Set;for(const n of e.matchAll(md))t.add(n[1]);return[...t]}function f0(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 h0(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function m0(e,t){var c;const n=[...e.matchAll(md)];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],h0(x,b)),o.push(p);continue}if(!g.result||g.error||g.stale){i.push(p);continue}a.push(f0(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 gd(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 Q1(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 Ws(n,` metrics = [${r.map(o=>`"${It(o)}"`).join(", ")}]`)}function yd(e,t,n){const r=Array.from(new Set(n.filter(Boolean))),o=`${t} = [${r.map(l=>`"${It(l)}"`).join(", ")}]`,i=new RegExp(`\\b${t}\\s*=\\s*\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,o):Ws(e,` ${o}`)}function xd(e){const t=va(e,"parameterPolicy"),n=va(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 Us(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:wd(d[4]),p=d[2]?`${d[2]}${d[3]??""}`:g0(jd(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:x0(t.get(c)),...g?{binding:g}:{}}]})}function g0(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=>ba(i))?"date[]":o.length>0&&o.every(i=>zr(i))?"number[]":"string[]"}return n==="true"||n==="false"?"boolean":ba(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 bd(e){return e.default===void 0?"":jd(e.default)}function Y1(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 X1(e,t){const n=kd(t.name);if(!n)return e;const r=xd(e).filter(o=>o.name!==t.previousName&&o.name!==n).map(o=>({name:o.name,type:o.type,required:o.required,defaultText:bd(o),policy:o.policy}));return r.push({name:n,type:t.type,required:t.required,defaultText:t.defaultText??"",policy:t.policy}),vd(e,r)}function Z1(e,t){const n=xd(e).filter(r=>r.name!==t).map(r=>({name:r.name,type:r.type,required:r.required,defaultText:bd(r),policy:r.policy}));return vd(e,n)}function ek(e,t,n){const r=kd(t),o=n.trim();if(!r||!o)return e;const l=Us(e,"filterBindings").split(/\r?\n/).filter(a=>a.trim()&&!new RegExp(`^${r}\\s*=`).test(a.trim()));return l.push(`${r} = "${It(o)}"`),qr(e,"filterBindings",l.join(`
503
- `))}function vd(e,t){const n=t.map(i=>{const l=`${i.name}: ${i.type}`;return i.required?l:`${l} = ${Sd(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 Sd(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=>Sd(i,r)).join(", ")}]`}return`"${It(n)}"`}function kd(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 ba(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)}function Us(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 va(e,t){const n=new Map;for(const r of Us(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 wd(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("]")?y0(t.slice(1,-1)).map(wd):t}function y0(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 jd(e){return Array.isArray(e)?e.join(", "):String(e??"")}function x0(e){return e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:"dynamic"}function b0(e,t){const n=new Set(gd(e).requestedFilters),r=Array.from(new Set(t.filter(Boolean)));let o=yd(e,"requested_filters",r);return o=Io(o,"params",n,r,i=>`${i}: string`),o=Io(o,"parameterPolicy",n,r,i=>`${i} = "dynamic"`),o=Io(o,"filterBindings",n,r,i=>`${i} = "${It(i)}"`),o}function Io(e,t,n,r,o){const a=[...C0(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 Sa(e,t,n){const r=It(n),o=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return o.test(e)?e.replace(o,`$1"${r}"`):Ws(e,` ${t} = "${r}"`)}function tk(e,t){const n=new Set(t.filter(Boolean)),r=gd(e);let o=yd(e,"dimensions",r.dimensions.filter(i=>n.has(i)));return o=b0(o,r.requestedFilters.filter(i=>n.has(i))),r.timeDimension&&!n.has(r.timeDimension)&&(o=Sa(o,"time_dimension",""),o=Sa(o,"granularity","")),o}function It(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ws(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 v0(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 S0(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=k0(i),i.trim()||null}return null}function k0(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 nk(e){const t=Ks(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 w0(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 j0(e,t){const n=t.replace(/"/g,'\\"');return/^\s*block\s+"/i.test(e)?e.replace(/^(\s*block\s+)"[^"]+"/i,`$1"${n}"`):e}function rk(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 ok(e,t,n){const r=Array.from(new Set(n.map(l=>l.trim()).filter(Boolean))),o=`${t} = [${r.map(l=>`"${It(l)}"`).join(", ")}]`,i=new RegExp(`(\\b${t}\\s*=\\s*)\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,`$1[${r.map(l=>`"${It(l)}"`).join(", ")}]`):kn(e,` ${o}`)}function sk(e,t){const n=/visualization\s*\{[\s\S]*?\n\s*\}/i;if(!n.test(e)){const r=A0(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 C0(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 ik(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function ak(e,t){const n=Ks(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
524
- ${t}
525
- `;const r=n.query.trimEnd(),o=r?`${r}
526
- ${t}`:t;return E0(e,o)}function E0(e,t){if(!Ks(e))return e;const r=w0(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 Ks(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:ka(e,"visualization"),tests:ka(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 ka(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 A0(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 = "${T0(e.title)}"`),t.push("}"),t.join(`
530
- `)}function T0(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 wa(e,t){return t.filter(n=>n.datasetId&&(n.objectType==="dataset"||n.objectType==="staged_dataset")).filter(n=>Cd(n.name).test(e)).map(n=>({id:n.datasetId,alias:n.name,role:n.objectType==="staged_dataset"?"staged":"source",fingerprint:n.fileFingerprint}))}function R0(e,t){return t.filter(n=>n.source==="database").filter(n=>Cd(n.name).test(e)).map(n=>n.name)}function lk(e,t){const n=[];for(const r of e)for(const o of t){const i=_0(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 ck(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(O0)).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 dk(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 _0(e,t,n){const r=e.toLowerCase(),o=t.toLowerCase();if(r===o)return{score:100,reason:"Same column name"};const i=ja(r),l=ja(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"}:Ca(r).filter(d=>Ca(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 ja(e){return e.replace(/[^a-z0-9]/g,"").replace(/identifier$/,"id")}function Ca(e){return e.split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Cd(e){return new RegExp(`(?:^|[^a-zA-Z0-9_])(?:["\`])?${$0(e)}(?:["\`])?(?=$|[^a-zA-Z0-9_])`,"i")}function ln(e){return`"${e.replace(/"/g,'""')}"`}function $0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function O0(e){return typeof e=="string"?e:JSON.stringify(e)}const Vt=new Map,_t=new Map;function Lo(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 P0(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?S0(t):null}function D0(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 M0(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 vt({status:400,code:e,message:t,recoverable:!0,details:{phase:"preflight",...n}})}function kr(e){const t=e.error instanceof vt?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??M0(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 Ed(){const{state:e,dispatch:t}=ve(),n=u.useRef(e);n.current=e;const r=u.useCallback(async(a,d)=>{var R,y,M,O;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:P0(p);if(p.type!=="dql"&&!g)return{cellId:a,status:"skipped"};const S=Vt.get(a);S&&S.controller.abort();const x=Lo(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),_t.set(a,x);const v=()=>{var T;return((T=Vt.get(a))==null?void 0:T.runId)===x&&_t.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 V=new Date().toISOString(),X=kr({cell:p,runId:x,route:h,startedAt:b,completedAt:V,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:X,executionCount:w,stale:!1}}),t({type:"APPEND_QUERY_LOG",entry:{id:nt(),cellName:p.name??p.id,rows:0,time:X.durationMs,ts:new Date,...I==="cancelled"?{}:{error:T}}})),{cellId:a,runId:x,status:I,error:I==="cancelled"?void 0:T,execution:X}};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 ye=new Date().toISOString(),xe=Date.now()-k,Te={...re.result,executionTime:re.result.executionTime??xe,rowCount:re.result.rowCount??re.result.rows.length},qe=D0(re.chartConfig)??v0(p.content),Le={version:1,runId:x,cellId:a,route:h,status:"success",startedAt:b,completedAt:ye,durationMs:xe,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:Te,error:void 0,execution:Le,executionTarget:re.executionTarget??p.executionTarget,...qe?{chartConfig:qe}:{},executionCount:w,stale:!1}}),t({type:"APPEND_QUERY_LOG",entry:{id:nt(),cellName:re.blockName??p.name??p.id,rows:Te.rowCount??Te.rows.length,time:Te.executionTime??xe,ts:new Date}}),setTimeout(()=>{_t.get(a)===x&&(t({type:"UPDATE_CELL",id:a,updates:{status:"idle"}}),_t.delete(a))},2e3),{cellId:a,runId:x,status:"success",result:Te,execution:Le}}const T=wa(g,c.schemaTables),L=R0(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(ye=>ye.alias??ye.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(ye=>ye.alias??ye.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 V=m0(g,f);if(V.ambiguous.length>0){const re=`Ambiguous notebook dependency: ${V.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:V.ambiguous}))}if(V.unresolved.length>0){const re=`Notebook dependency result is unavailable: ${V.unresolved.join(", ")}. Run or repair the upstream cell before retrying this cell.`;return A(re,Rn("UPSTREAM_RESULT_UNAVAILABLE",re,{unresolvedReferences:V.unresolved}))}const X=await N.executeQuery(V.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 J=new Date().toISOString(),W=Date.now()-k,{executionTarget:D,compiledSql:$,executedSql:Q,targetBinding:q,executionReceipt:ee,...H}=X,B={...H,executionTime:H.executionTime??W,rowCount:H.rowCount??H.rows.length},ne=(I==null?void 0:I.target)==="local"?wa(V.sql,c.schemaTables):p.datasetRefs,ce={version:1,runId:x,cellId:a,route:h,status:"success",startedAt:b,completedAt:J,durationMs:W,executionTarget:D??I,compiledSql:$??V.sql,executedSql:Q??V.sql,targetBinding:q,executionReceipt:ee};return t({type:"UPDATE_CELL",id:a,updates:{status:"success",result:B,error:void 0,execution:ce,executionCount:w,stale:!1,datasetRefs:ne,executionTarget:D??I}}),t({type:"APPEND_QUERY_LOG",entry:{id:nt(),cellName:p.name??p.id,rows:B.rowCount??B.rows.length,time:B.executionTime??W,ts:new Date}}),setTimeout(()=>{_t.get(a)===x&&(t({type:"UPDATE_CELL",id:a,updates:{status:"idle"}}),_t.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{((O=Vt.get(a))==null?void 0:O.runId)===x&&Vt.delete(a)}},[t]),o=u.useCallback(async()=>{const a=n.current.cells,d=hg(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=Lo(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=$s(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=Lo(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),_t.get(a)===d.runId&&_t.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 Je(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function I0(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 L0(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(Je(l));continue}if(l.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${Je(l.slice(4))}</h3>`);continue}if(l.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${Je(l.slice(3))}</h2>`);continue}if(l.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${Je(l.slice(2))}</h1>`);continue}if(l.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${Je(l.slice(2))}</p></blockquote>`);continue}if(l.startsWith("- ")||l.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${Ea(l.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),l.trim()===""){n.push("<br>");continue}n.push(`<p>${Ea(l)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
541
- `)}function Ea(e){return Je(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function N0(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,i=t.map(a=>`<th>${Je(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"':""}>${Je(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 B0(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 F0(e){const t=B0(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">${Je(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">${I0(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 z0(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${L0(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${Je(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,i=`<pre class="cell-code"><code>${Je(r.content)}</code></pre>`;let l="";if(r.result&&r.result.rows.length>0){const a=F0(r.result),d=N0(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">⚠ ${Je(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>${Je(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">${Je(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 q0(e,t){const n=z0(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 U0({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 W0(){var ee;const{state:e,dispatch:t}=ve(),n=ze[e.themeMode],{executeAll:r}=Ed(),[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,O=e.mainView==="notebook",T=e.mainView==="notebook"||e.mainView==="block_studio",L=T&&!!e.activeFile,I={home:"Home",business_artifact:((ee=e.activeFile)==null?void 0:ee.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"},V=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 H(B){R.current&&!R.current.contains(B.target)&&A(!1)}return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[w]);const X=()=>{a(e.notebookTitle),i(!0)},J=()=>{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:j0(e.blockStudioDraft,l.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},W=u.useCallback(async()=>{var H;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"?((H=e.cells[0])==null?void 0:H.content)??"":u0(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 H=B=>{(B.metaKey||B.ctrlKey)&&B.key==="s"&&(B.preventDefault(),W())};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[W]),u.useEffect(()=>{if(!e.autoSave||!M||!e.activeFile||e.mainView==="block_studio")return;const H=setTimeout(()=>{W()},750);return()=>clearTimeout(H)},[e.autoSave,M,e.activeFile,e.cells,e.blockStudioDraft,W]);const D=[{mode:"obsidian",label:"Obsidian",glyph:"●",swatch:"#0d0e11"},{mode:"paper",label:"Paper",glyph:"☼",swatch:"#f7f4ed"},{mode:"white",label:"White",glyph:"○",swatch:"#ffffff"}],$=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode,Q=D.find(H=>H.mode===$)??D[0];u.useEffect(()=>{if(!b)return;const H=ne=>{C.current&&!C.current.contains(ne.target)&&k(!1)},B=ne=>{ne.key==="Escape"&&k(!1)};return document.addEventListener("mousedown",H),document.addEventListener("keydown",B),()=>{document.removeEventListener("mousedown",H),document.removeEventListener("keydown",B)}},[b]);const q={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(U0,{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:H=>a(H.target.value),onBlur:J,onKeyDown:H=>{H.key==="Enter"&&J(),H.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:X,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:[V,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:V||"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:O?r:void 0,disabled:!e.activeFile||!O,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),style:{...q,height:30,padding:"0 14px",borderRadius:999,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!O?.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(H=>!H),onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),title:`Theme: ${Q.label}`,"aria-haspopup":"true","aria-expanded":b,style:{...q,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:Q.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:Q.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:D.map(H=>{const B=H.mode===$;return s.jsxs("button",{role:"menuitemradio","aria-checked":B,onClick:()=>{t({type:"SET_THEME",mode:H.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:H.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{flex:1},children:H.label}),B&&s.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},H.mode)})})]}),e.appMode==="studio"&&L&&e.mainView!=="block_studio"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:W,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),title:"Save (Cmd+S)",style:{...q,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(V0,{}),"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(H=>!H)},disabled:!e.activeFile,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),title:"Share / export",style:{...q,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(K0,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{q0(e.notebookTitle||"dashboard",e.cells),A(!1)}})})]})]})]})}function K0({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 V0(){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 H0(e){return e.toTimeString().slice(0,8)}function G0(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function J0(){const{state:e,dispatch:t}=ve(),n=ze[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(Q0,{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(Aa,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(a=>s.jsx(Ta,{entry:a,t:n},a.id))),e.devPanelTab==="errors"&&(i.length===0?s.jsx(Aa,{t:n,message:"No errors."}):[...i].reverse().map(a=>s.jsx(Ta,{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 Q0({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 Aa({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 Ta({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:H0(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:G0(e.time)})]})]})}function Y0(){const{state:e,dispatch:t}=ve(),{executeAll:n}=Ed();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 X0=600;function Z0(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 Ra(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 e1(){var o;const{state:e}=ve(),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=Ra(e.cells);return}const l=Ra(e.cells);return l!==n.current&&(n.current=l,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const d=Z0(i,e.cells);N.saveRunSnapshot(i,d).catch(()=>{})},X0)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}const t1=u.lazy(()=>Ce(()=>import("./HomePage-DQSo-K4y.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.HomePage}))),n1=u.lazy(()=>Ce(()=>import("./AnalyticsHome-4TgtH6SB.js"),__vite__mapDeps([7,8,9,10,11,1,12,13,3,14,15,16,17,18,2,19,20,6])).then(e=>({default:e.AnalyticsHome}))),r1=u.lazy(()=>Ce(()=>import("./GlobalAiRail-B_MZsB0z.js"),__vite__mapDeps([21,9,10,11,1,12,13,3,14,15,16,17,18,2,19,22,23,24,6])).then(e=>({default:e.GlobalAiRail}))),o1=u.lazy(()=>Ce(()=>import("./NotebookEditor-D6RgLQw-.js"),__vite__mapDeps([25,4,2,5,26,27,28,11,9,10,1,12,13,3,14,15,16,17,18,19,8,29,30,6,31,32,22,23,24])).then(e=>({default:e.NotebookEditor}))),s1=u.lazy(()=>Ce(()=>import("./NewNotebookModal-xgaKB2kI.js"),__vite__mapDeps([33,4,15,6])).then(e=>({default:e.NewNotebookModal}))),i1=u.lazy(()=>Ce(()=>import("./NewBlockModal-BLtjuWGy.js"),__vite__mapDeps([34,6])).then(e=>({default:e.NewBlockModal}))),a1=u.lazy(()=>Ce(()=>import("./SetupOnboarding-DX2f53J2.js"),__vite__mapDeps([35,36,2,6])).then(e=>({default:e.SetupOnboarding}))),l1=u.lazy(()=>Ce(()=>import("./BlockStudio-DUXN3MKz.js"),__vite__mapDeps([37,26,27,11,29,30,6,31,9,10,1,12,13,3,14,15,16,17,18,2,19,22,23,24,38,39])).then(e=>({default:e.BlockStudio}))),c1=u.lazy(()=>Ce(()=>import("./BusinessArtifactView-D8FIgrkF.js"),__vite__mapDeps([40,29,30,6,31])).then(e=>({default:e.BusinessArtifactView}))),d1=u.lazy(()=>Ce(()=>import("./LineageDetailView-CZEx2r1H.js"),__vite__mapDeps([41,29,30,6,31,42,36,17])).then(e=>({default:e.LineageDetailView}))),u1=u.lazy(()=>Ce(()=>import("./LineageDAG-RdpWmGmR.js"),__vite__mapDeps([42,30,6,31])).then(e=>({default:e.LineageDAG}))),p1=u.lazy(()=>Ce(()=>import("./HelpDocsPage-Bc5pLakt.js"),__vite__mapDeps([43,6])).then(e=>({default:e.HelpDocsPage}))),f1=u.lazy(()=>Ce(()=>Promise.resolve().then(()=>DS),void 0).then(e=>({default:e.ConnectionPanel}))),h1=u.lazy(()=>Ce(()=>import("./GitPage-BS2sm9zh.js"),__vite__mapDeps([44,45,15,6])).then(e=>({default:e.GitPage}))),m1=u.lazy(()=>Ce(()=>import("./ReadinessPage-C8hATaT_.js"),__vite__mapDeps([46,1,47,48,13,3,2,6])).then(e=>({default:e.ReadinessPage}))),g1=u.lazy(()=>Ce(()=>import("./AgentLogPage-uvVs284-.js"),__vite__mapDeps([49,36,18,50,6])).then(e=>({default:e.AgentLogPage}))),y1=u.lazy(()=>Ce(()=>import("./GovernedContextPage-CNM5UCAH.js").then(e=>e.G),__vite__mapDeps([51,3,13,19,16,15])).then(e=>({default:e.GovernedContextPage}))),x1=u.lazy(()=>Ce(()=>import("./DbtFirstModelingPage-DR8hTZ95.js"),__vite__mapDeps([52,51,3,13,19,16,15,30,6,31,32,24,38,50,14])).then(e=>({default:e.DbtFirstModelingPage}))),b1=u.lazy(()=>Ce(()=>import("./AppsView-CnfNtk5W.js"),__vite__mapDeps([53,22,23,24,15,11,28,48,39,54,3,36,5,16,20,4,6])).then(e=>({default:e.AppsView}))),v1=u.lazy(()=>Ce(()=>import("./LineageDrawer-P7ZdOW8-.js"),__vite__mapDeps([55,29,30,6,31,38,15,23,14,54,45])).then(e=>({default:e.LineageDrawer}))),S1=u.lazy(()=>Ce(()=>import("./AiBuildDialog-DEUS19WF.js"),__vite__mapDeps([56,47,12,13,3,14,15,6])).then(e=>({default:e.AiBuildDialog})));function k1(){const{state:e,dispatch:t}=ve(),n=ze[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]),Y0(),e1(),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}=p0(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:[Os("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(W0,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(wb,{}),e.appMode==="studio"&&e.sidebarOpen&&!o&&s.jsx(s0,{onOpenFile:p}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:s.jsx(u.Suspense,{fallback:s.jsx(w1,{t:n}),children:e.mainView==="home"?s.jsx(t1,{}):e.mainView==="ask"?s.jsx(n1,{}):e.mainView==="business_artifact"?s.jsx(c1,{}):e.mainView==="lineage"?s.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s.jsx(u1,{})}):e.mainView==="lineage_detail"?s.jsx(d1,{}):e.mainView==="help"?s.jsx(p1,{}):e.mainView==="connection"||e.mainView==="settings"?s.jsx(j1,{children:s.jsx(f1,{variant:"page"})}):e.mainView==="git"?s.jsx(h1,{}):e.mainView==="readiness"?s.jsx(m1,{}):e.mainView==="skills"?s.jsx(y1,{initialTab:"skills"}):e.mainView==="domains"||e.mainView==="modeling"?s.jsx(x1,{}):e.mainView==="apps"?s.jsx(b1,{}):e.mainView==="agent_log"?s.jsx(C1,{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(g1,{})}):s.jsx(s.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?s.jsx(l1,{},"block-editor"):s.jsxs(s.Fragment,{children:[s.jsx(o1,{onOpenFile:p,registerCellRef:h}),e.appMode==="studio"&&s.jsx(J0,{})]})})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(u.Suspense,{fallback:null,children:s.jsx(v1,{})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(ub,{}),e.globalAi.open&&e.mainView==="apps"&&s.jsx(u.Suspense,{fallback:null,children:s.jsx(r1,{})})]}),e.newNotebookModalOpen&&s.jsx(u.Suspense,{fallback:null,children:s.jsx(s1,{onFileOpened:p})}),e.newBlockModalOpen&&s.jsx(u.Suspense,{fallback:null,children:s.jsx(i1,{onFileOpened:p})}),s.jsx(Rx,{open:i,onClose:()=>l(!1)}),s.jsx(u.Suspense,{fallback:null,children:s.jsx(S1,{})}),e.setupOpen&&s.jsx(u.Suspense,{fallback:s.jsx(_a,{t:n}),children:s.jsx(a1,{launch:a!=null&&a.shouldOpen?a:void 0,onAcknowledged:()=>d(g=>g&&{...g,shouldOpen:!1,reason:null})})}),!c&&s.jsx(_a,{t:n})]})}function w1({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 _a({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 j1({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 C1({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 E1(){const{state:e,dispatch:t}=ve(),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 A1(){const{state:e,dispatch:t}=ve(),n=ze[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]),E1(),s.jsx(Hd,{theme:e.themeMode,applyGlobal:!0,children:s.jsx(of,{delayDuration:200,skipDelayDuration:400,children:s.jsx(k1,{})})})}function T1(){return s.jsx(kg,{children:s.jsx(A1,{})})}Wd.createRoot(document.getElementById("root")).render(s.jsx(T1,{}));export{Co as $,X1 as A,Ps as B,ny as C,tr as D,Y1 as E,fy as F,Sn as G,Ed as H,dk as I,Hv as J,wa as K,Fn as L,R0 as M,Gy as N,bb as O,ix as P,z1 as Q,De as R,Fc as S,zc as T,q1 as U,G1 as V,U1 as W,Bc as X,Ir as Y,yS as Z,ud as _,N as a,Jo as a0,nk as a1,Ov as a2,ik as a3,ak as a4,w0 as a5,j0 as a6,rk as a7,Q1 as a8,yd as a9,oy as aA,rd as aB,dy as aC,Ic as aD,p0 as aE,Zg as aF,Ce as aG,zy as aH,Lc as aI,hx as aJ,yy as aK,Qo as aL,ek as aM,Oc as aN,ok as aa,E0 as ab,C0 as ac,tk as ad,Sa as ae,sk as af,qr as ag,gv as ah,Bi as ai,V1 as aj,H1 as ak,K1 as al,W1 as am,Wc as an,N1 as ao,B1 as ap,F1 as aq,cb as ar,db as as,L1 as at,Wi as au,Wy as av,$g as aw,Mg as ax,Iy as ay,$y as az,Ds as b,we as c,oo as d,Mc as e,Kg as f,Y as g,gx as h,S0 as i,s as j,Ms as k,J1 as l,Os as m,ib as n,ab as o,ck as p,xd as q,u as r,lk as s,ze as t,ve as u,bd as v,Z1 as w,b0 as x,gd as y,g0 as z};