@duckcodeailabs/dql-cli 1.14.1 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/assets/dql-notebook/assets/{AgentLogPage-BPz-UWFh.js → AgentLogPage-DKbGpRQS.js} +1 -1
  2. package/dist/assets/dql-notebook/assets/{AiBuildDialog-BEl53WA_.js → AiBuildDialog-DPSu0Mly.js} +1 -1
  3. package/dist/assets/dql-notebook/assets/{AiBuildResult-B4yfGTTZ.js → AiBuildResult-1uaGnpi1.js} +1 -1
  4. package/dist/assets/dql-notebook/assets/{AiSidePanel-CSZAAvuD.js → AiSidePanel-BwMREwa7.js} +1 -1
  5. package/dist/assets/dql-notebook/assets/{AnalyticsHome-D5P6Ujwi.js → AnalyticsHome-BGfey_ve.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AppsView-DQOwU9Cg.js → AppsView-CM1tPywy.js} +4 -4
  7. package/dist/assets/dql-notebook/assets/{BlockStudio-B4ap0GdY.js → BlockStudio--S6WFVO4.js} +1 -1
  8. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-BIfNI-0S.js → BusinessArtifactView-BEAJ-yNW.js} +1 -1
  9. package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-D72byb2g.js → DbtFirstModelingPage-CNyU5MBX.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/{GitPage-lQb1uXH2.js → GitPage-IcydAai3.js} +1 -1
  11. package/dist/assets/dql-notebook/assets/{GlobalAiRail-CVECf6Xj.js → GlobalAiRail-CSKW-5eD.js} +1 -1
  12. package/dist/assets/dql-notebook/assets/{GovernedContextPage-trOyMCY6.js → GovernedContextPage-CFen0eFT.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/{HelpDocsPage-D8hLS5lE.js → HelpDocsPage-D0D9UCIz.js} +1 -1
  14. package/dist/assets/dql-notebook/assets/{HomePage-eIkfBIep.js → HomePage-CmSxapR3.js} +1 -1
  15. package/dist/assets/dql-notebook/assets/{LineageDAG-CSqcbDrE.js → LineageDAG-BGUcIt1B.js} +1 -1
  16. package/dist/assets/dql-notebook/assets/{LineageDetailView-DJZZjZu-.js → LineageDetailView-Dx48Zfzb.js} +1 -1
  17. package/dist/assets/dql-notebook/assets/{LineageDrawer-BcIipIc3.js → LineageDrawer-zaBfSLZO.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-CviIf8PN.js → LineagePathBreadcrumb-CTZJp4_r.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-vH_MY_Ju.js → MiniLineageGraph-CdivNR1S.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/{NewBlockModal-DbCQg-pj.js → NewBlockModal-DMBFB7nE.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/{NewNotebookModal-5Vp6XiuK.js → NewNotebookModal-DsC9CWlW.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{NotebookEditor-DjqJS44s.js → NotebookEditor-hs-kw8v9.js} +1 -1
  23. package/dist/assets/dql-notebook/assets/{ReadinessPage-BHGrC5ho.js → ReadinessPage-DJ83cMik.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{SetupOnboarding-BfS9Tdx-.js → SetupOnboarding-B1Pu_Bvv.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{SkillsPage-BFH21wSj.js → SkillsPage-BHKDay8n.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{TrustBadge-zm6g_SxZ.js → TrustBadge-BkyGgob2.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-BYdrTaEW.js +89 -0
  28. package/dist/assets/dql-notebook/assets/{answer-to-notebook-DPhxIEzF.js → answer-to-notebook-DmNiuLQA.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{arrow-left-DNEb86Xc.js → arrow-left--1rsrxm8.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{arrow-right-DpPWbwaD.js → arrow-right-D5TdqY1G.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/{book-open-text-D7s5jo4X.js → book-open-text-Bw7nHbzg.js} +1 -1
  32. package/dist/assets/dql-notebook/assets/{circle-x-Db3dXKg7.js → circle-x-DLe6NNM4.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{dagre.esm-C7pppQ1a.js → dagre.esm-CW5QZdBt.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{external-link-BxwXitO_.js → external-link-C9Q97sA3.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{grip-vertical-Dt4lkWRi.js → grip-vertical-CztvkIgo.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{index-DKo-bwNw.js → index-zHHzDn6l.js} +127 -127
  37. package/dist/assets/dql-notebook/assets/{link-2-Dfo2P6wi.js → link-2-CiKAvumL.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/{list-tree-DiTmIWAL.js → list-tree-BtnP2nQ5.js} +1 -1
  39. package/dist/assets/dql-notebook/assets/{minimize-2-CMTAkPzL.js → minimize-2-TSFGxcCP.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/{panel-right-open-DwYr7FW4.js → panel-right-open-BfXIUWy0.js} +1 -1
  41. package/dist/assets/dql-notebook/assets/{play-BXhHYQ4x.js → play-DVbSFJHD.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{rotate-ccw-BNi6F8pl.js → rotate-ccw-D_cesDcX.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{semantic-fields-CNOGysAy.js → semantic-fields-CoVStdYB.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{sliders-horizontal-Ec5MUMUW.js → sliders-horizontal-l7xV9K5A.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{star-B9leDkp_.js → star-CSBS0H3b.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{triangle-alert-BefTYCzx.js → triangle-alert-BTrnyY4q.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{upload-SPiOM2tQ.js → upload-sySLq9zb.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-C4foXeiQ.js → usePersistedAgentThreadId-CzwgGdus.js} +1 -1
  49. package/dist/assets/dql-notebook/assets/{user-round-comGmyw-.js → user-round-ChlgXi9j.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{wand-sparkles-BffR4dF8.js → wand-sparkles-CGw0ytyT.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{workflow-ChmPTEzH.js → workflow-C_RltiK5.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{wrench-DovaG_ze.js → wrench-D-wLfeu0.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/{x-nRx91AgW.js → x-B28hIJIC.js} +1 -1
  54. package/dist/assets/dql-notebook/index.html +1 -1
  55. package/dist/commands/agent-eval-cassette.d.ts +97 -6
  56. package/dist/commands/agent-eval-cassette.d.ts.map +1 -1
  57. package/dist/commands/agent-eval-cassette.js +165 -22
  58. package/dist/commands/agent-eval-cassette.js.map +1 -1
  59. package/dist/commands/agent-eval-runtime.d.ts +14 -2
  60. package/dist/commands/agent-eval-runtime.d.ts.map +1 -1
  61. package/dist/commands/agent-eval-runtime.js +12 -2
  62. package/dist/commands/agent-eval-runtime.js.map +1 -1
  63. package/dist/commands/agent.d.ts +9 -3
  64. package/dist/commands/agent.d.ts.map +1 -1
  65. package/dist/commands/agent.js +126 -49
  66. package/dist/commands/agent.js.map +1 -1
  67. package/dist/commands/compile.d.ts +13 -1
  68. package/dist/commands/compile.d.ts.map +1 -1
  69. package/dist/commands/compile.js +36 -4
  70. package/dist/commands/compile.js.map +1 -1
  71. package/dist/commands/sync.d.ts.map +1 -1
  72. package/dist/commands/sync.js +11 -3
  73. package/dist/commands/sync.js.map +1 -1
  74. package/dist/llm/providers/dql-agent-provider.d.ts +28 -1
  75. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  76. package/dist/llm/providers/dql-agent-provider.js +272 -22
  77. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  78. package/dist/llm/types.d.ts +29 -1
  79. package/dist/llm/types.d.ts.map +1 -1
  80. package/dist/local-runtime.d.ts +16 -1
  81. package/dist/local-runtime.d.ts.map +1 -1
  82. package/dist/local-runtime.js +824 -66
  83. package/dist/local-runtime.js.map +1 -1
  84. package/dist/package.json +10 -10
  85. package/package.json +10 -10
  86. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel--oxmjlgr.js +0 -88
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/HomePage-eIkfBIep.js","assets/TrustBadge-zm6g_SxZ.js","assets/arrow-right-DpPWbwaD.js","assets/triangle-alert-BefTYCzx.js","assets/book-open-text-D7s5jo4X.js","assets/workflow-ChmPTEzH.js","assets/react-CRB3T2We.js","assets/AnalyticsHome-D5P6Ujwi.js","assets/answer-to-notebook-DPhxIEzF.js","assets/UnifiedAgentRunPanel--oxmjlgr.js","assets/usePersistedAgentThreadId-C4foXeiQ.js","assets/AiBuildResult-B4yfGTTZ.js","assets/user-round-comGmyw-.js","assets/rotate-ccw-BNi6F8pl.js","assets/wrench-DovaG_ze.js","assets/x-nRx91AgW.js","assets/list-tree-DiTmIWAL.js","assets/minimize-2-CMTAkPzL.js","assets/star-B9leDkp_.js","assets/GlobalAiRail-CVECf6Xj.js","assets/AiSidePanel-CSZAAvuD.js","assets/NotebookEditor-DjqJS44s.js","assets/LineagePathBreadcrumb-CviIf8PN.js","assets/codemirror-DXt7RW72.js","assets/semantic-fields-CNOGysAy.js","assets/MiniLineageGraph-vH_MY_Ju.js","assets/dagre.esm-C7pppQ1a.js","assets/dagre-BZV40eAE.css","assets/link-2-Dfo2P6wi.js","assets/upload-SPiOM2tQ.js","assets/NewNotebookModal-5Vp6XiuK.js","assets/NewBlockModal-DbCQg-pj.js","assets/SetupOnboarding-BfS9Tdx-.js","assets/arrow-left-DNEb86Xc.js","assets/BlockStudio-B4ap0GdY.js","assets/play-BXhHYQ4x.js","assets/panel-right-open-DwYr7FW4.js","assets/BusinessArtifactView-BIfNI-0S.js","assets/LineageDetailView-DJZZjZu-.js","assets/LineageDAG-CSqcbDrE.js","assets/HelpDocsPage-D8hLS5lE.js","assets/GitPage-lQb1uXH2.js","assets/external-link-BxwXitO_.js","assets/ReadinessPage-BHGrC5ho.js","assets/ai-build-bus-1BR770pY.js","assets/wand-sparkles-BffR4dF8.js","assets/AgentLogPage-BPz-UWFh.js","assets/circle-x-Db3dXKg7.js","assets/GovernedContextPage-trOyMCY6.js","assets/SkillsPage-BFH21wSj.js","assets/DbtFirstModelingPage-D72byb2g.js","assets/sliders-horizontal-Ec5MUMUW.js","assets/AppsView-DQOwU9Cg.js","assets/grip-vertical-Dt4lkWRi.js","assets/LineageDrawer-BcIipIc3.js","assets/AiBuildDialog-BEl53WA_.js"])))=>i.map(i=>d[i]);
2
- var Rf=Object.defineProperty;var ec=e=>{throw TypeError(e)};var Of=(e,t,n)=>t in e?Rf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pe=(e,t,n)=>Of(e,typeof t!="symbol"?t+"":t,n),Ms=(e,t,n)=>t.has(e)||ec("Cannot "+n);var R=(e,t,n)=>(Ms(e,t,"read from private field"),n?n.call(e):t.get(e)),le=(e,t,n)=>t.has(e)?ec("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Z=(e,t,n,r)=>(Ms(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),fe=(e,t,n)=>(Ms(e,t,"access private method"),n);var $o=(e,t,n,r)=>({set _(o){Z(e,t,o,n)},get _(){return R(e,t,r)}});import{r as Xl,a as Zl,g as ed}from"./react-CRB3T2We.js";function _f(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 a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).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 Ls={exports:{}},Fr={};/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/HomePage-CmSxapR3.js","assets/TrustBadge-BkyGgob2.js","assets/arrow-right-D5TdqY1G.js","assets/triangle-alert-BTrnyY4q.js","assets/book-open-text-Bw7nHbzg.js","assets/workflow-C_RltiK5.js","assets/react-CRB3T2We.js","assets/AnalyticsHome-BGfey_ve.js","assets/answer-to-notebook-DmNiuLQA.js","assets/UnifiedAgentRunPanel-BYdrTaEW.js","assets/usePersistedAgentThreadId-CzwgGdus.js","assets/AiBuildResult-1uaGnpi1.js","assets/user-round-ChlgXi9j.js","assets/rotate-ccw-D_cesDcX.js","assets/wrench-D-wLfeu0.js","assets/x-B28hIJIC.js","assets/list-tree-BtnP2nQ5.js","assets/minimize-2-TSFGxcCP.js","assets/star-CSBS0H3b.js","assets/GlobalAiRail-CSKW-5eD.js","assets/AiSidePanel-BwMREwa7.js","assets/NotebookEditor-hs-kw8v9.js","assets/LineagePathBreadcrumb-CTZJp4_r.js","assets/codemirror-DXt7RW72.js","assets/semantic-fields-CoVStdYB.js","assets/MiniLineageGraph-CdivNR1S.js","assets/dagre.esm-CW5QZdBt.js","assets/dagre-BZV40eAE.css","assets/link-2-CiKAvumL.js","assets/upload-sySLq9zb.js","assets/NewNotebookModal-DsC9CWlW.js","assets/NewBlockModal-DMBFB7nE.js","assets/SetupOnboarding-B1Pu_Bvv.js","assets/arrow-left--1rsrxm8.js","assets/BlockStudio--S6WFVO4.js","assets/play-DVbSFJHD.js","assets/panel-right-open-BfXIUWy0.js","assets/BusinessArtifactView-BEAJ-yNW.js","assets/LineageDetailView-Dx48Zfzb.js","assets/LineageDAG-BGUcIt1B.js","assets/HelpDocsPage-D0D9UCIz.js","assets/GitPage-IcydAai3.js","assets/external-link-C9Q97sA3.js","assets/ReadinessPage-DJ83cMik.js","assets/ai-build-bus-1BR770pY.js","assets/wand-sparkles-CGw0ytyT.js","assets/AgentLogPage-DKbGpRQS.js","assets/circle-x-DLe6NNM4.js","assets/GovernedContextPage-CFen0eFT.js","assets/SkillsPage-BHKDay8n.js","assets/DbtFirstModelingPage-CNyU5MBX.js","assets/sliders-horizontal-l7xV9K5A.js","assets/AppsView-CM1tPywy.js","assets/grip-vertical-CztvkIgo.js","assets/LineageDrawer-zaBfSLZO.js","assets/AiBuildDialog-DPSu0Mly.js"])))=>i.map(i=>d[i]);
2
+ var Of=Object.defineProperty;var ec=e=>{throw TypeError(e)};var _f=(e,t,n)=>t in e?Of(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pe=(e,t,n)=>_f(e,typeof t!="symbol"?t+"":t,n),Ms=(e,t,n)=>t.has(e)||ec("Cannot "+n);var R=(e,t,n)=>(Ms(e,t,"read from private field"),n?n.call(e):t.get(e)),le=(e,t,n)=>t.has(e)?ec("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Z=(e,t,n,r)=>(Ms(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),fe=(e,t,n)=>(Ms(e,t,"access private method"),n);var $o=(e,t,n,r)=>({set _(o){Z(e,t,o,n)},get _(){return R(e,t,r)}});import{r as Zl,a as ed,g as td}from"./react-CRB3T2We.js";function Pf(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 a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).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 Ls={exports:{}},Fr={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.min.js
5
5
  *
@@ -7,8 +7,8 @@ var Rf=Object.defineProperty;var ec=e=>{throw TypeError(e)};var Of=(e,t,n)=>t in
7
7
  *
8
8
  * This source code is licensed under the MIT license found in the
9
9
  * LICENSE file in the root directory of this source tree.
10
- */var tc;function Pf(){if(tc)return Fr;tc=1;var e=Xl(),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 a(c,l,u){var h,d={},f=null,m=null;u!==void 0&&(f=""+u),l.key!==void 0&&(f=""+l.key),l.ref!==void 0&&(m=l.ref);for(h in l)r.call(l,h)&&!i.hasOwnProperty(h)&&(d[h]=l[h]);if(c&&c.defaultProps)for(h in l=c.defaultProps,l)d[h]===void 0&&(d[h]=l[h]);return{$$typeof:t,type:c,key:f,ref:m,props:d,_owner:o.current}}return Fr.Fragment=n,Fr.jsx=a,Fr.jsxs=a,Fr}var nc;function If(){return nc||(nc=1,Ls.exports=Pf()),Ls.exports}var s=If(),Mo={},rc;function Df(){if(rc)return Mo;rc=1;var e=Zl();return Mo.createRoot=e.createRoot,Mo.hydrateRoot=e.hydrateRoot,Mo}var $f=Df(),p=Xl();const qe=ed(p),td=_f({__proto__:null,default:qe},[p]);var vo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Dn,cn,mr,ql,Mf=(ql=class extends vo{constructor(){super();le(this,Dn);le(this,cn);le(this,mr);Z(this,mr,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){R(this,cn)||this.setEventListener(R(this,mr))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,cn))==null||t.call(this),Z(this,cn,void 0))}setEventListener(t){var n;Z(this,mr,t),(n=R(this,cn))==null||n.call(this),Z(this,cn,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){R(this,Dn)!==t&&(Z(this,Dn,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof R(this,Dn)=="boolean"?R(this,Dn):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Dn=new WeakMap,cn=new WeakMap,mr=new WeakMap,ql),Hi=new Mf,Lf={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ln,Vi,Ul,Nf=(Ul=class{constructor(){le(this,ln,Lf);le(this,Vi,!1)}setTimeoutProvider(e){Z(this,ln,e)}setTimeout(e,t){return R(this,ln).setTimeout(e,t)}clearTimeout(e){R(this,ln).clearTimeout(e)}setInterval(e,t){return R(this,ln).setInterval(e,t)}clearInterval(e){R(this,ln).clearInterval(e)}},ln=new WeakMap,Vi=new WeakMap,Ul),Pn=new Nf;function Bf(e){setTimeout(e,0)}var Ff=typeof window>"u"||"Deno"in globalThis;function at(){}function zf(e,t){return typeof e=="function"?e(t):e}function mi(e){return typeof e=="number"&&e>=0&&e!==1/0}function nd(e,t){return Math.max(e+(t||0)-Date.now(),0)}function gn(e,t){return typeof e=="function"?e(t):e}function ht(e,t){return typeof e=="function"?e(t):e}function oc(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Gi(a,t.options))return!1}else if(!Ar(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||i&&!i(t))}function sc(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(oo(t.options.mutationKey)!==oo(i))return!1}else if(!Ar(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gi(e,t){return((t==null?void 0:t.queryKeyHashFn)||oo)(e)}function oo(e){return JSON.stringify(e,(t,n)=>yi(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Ar(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t)){for(let r=0;r<t.length;r++)if(!Ar(e[r],t[r]))return!1;return!0}const n=Object.keys(t);for(const r of n)if(!Ar(e[r],t[r]))return!1;return!0}return!1}var qf=Object.prototype.hasOwnProperty;function rd(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=ic(e)&&ic(t);if(!r&&!(yi(e)&&yi(t)))return t;const i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),c=a.length,l=r?new Array(c):{};let u=0;for(let h=0;h<c;h++){const d=r?h:a[h],f=e[d],m=t[d];if(f===m){l[d]=f,(r?h<i:qf.call(e,d))&&u++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){l[d]=m;continue}const S=rd(f,m,n+1);l[d]=S,S===f&&u++}return i===c&&u===i?e:l}function gi(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function ic(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function yi(e){if(!ac(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!ac(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ac(e){return Object.prototype.toString.call(e)==="[object Object]"}function Uf(e){return new Promise(t=>{Pn.setTimeout(t,e)})}function bi(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?rd(e,t):t}function Wf(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Kf(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Qi=Symbol();function od(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===Qi?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function sd(e,t){return typeof e=="function"?e(...t):!!e}function Vf(e,t,n){let r=!1,o;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(o??(o=t()),r||(r=!0,o.aborted?n():o.addEventListener("abort",n,{once:!0})),o)}),e}var so=(()=>{let e=()=>Ff;return{isServer(){return e()},setIsServer(t){e=t}}})();function xi(){let e,t;const n=new Promise((o,i)=>{e=o,t=i});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}var Hf=Bf;function Gf(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=Hf;const i=c=>{t?e.push(c):o(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&o(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var Ue=Gf(),gr,dn,yr,Wl,Qf=(Wl=class extends vo{constructor(){super();le(this,gr,!0);le(this,dn);le(this,yr);Z(this,yr,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){R(this,dn)||this.setEventListener(R(this,yr))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,dn))==null||t.call(this),Z(this,dn,void 0))}setEventListener(t){var n;Z(this,yr,t),(n=R(this,dn))==null||n.call(this),Z(this,dn,t(this.setOnline.bind(this)))}setOnline(t){R(this,gr)!==t&&(Z(this,gr,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return R(this,gr)}},gr=new WeakMap,dn=new WeakMap,yr=new WeakMap,Wl),os=new Qf;function Jf(e){return Math.min(1e3*2**e,3e4)}function id(e){return(e??"online")==="online"?os.isOnline():!0}var vi=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function ad(e){let t=!1,n=0,r;const o=xi(),i=()=>o.status!=="pending",a=v=>{var b;if(!i()){const w=new vi(v);f(w),(b=e.onCancel)==null||b.call(e,w)}},c=()=>{t=!0},l=()=>{t=!1},u=()=>Hi.isFocused()&&(e.networkMode==="always"||os.isOnline())&&e.canRun(),h=()=>id(e.networkMode)&&e.canRun(),d=v=>{i()||(r==null||r(),o.resolve(v))},f=v=>{i()||(r==null||r(),o.reject(v))},m=()=>new Promise(v=>{var b;r=w=>{(i()||u())&&v(w)},(b=e.onPause)==null||b.call(e)}).then(()=>{var v;r=void 0,i()||(v=e.onContinue)==null||v.call(e)}),S=()=>{if(i())return;let v;const b=n===0?e.initialPromise:void 0;try{v=b??e.fn()}catch(w){v=Promise.reject(w)}Promise.resolve(v).then(d).catch(w=>{var P;if(i())return;const j=e.retry??(so.isServer()?0:3),C=e.retryDelay??Jf,x=typeof C=="function"?C(n,w):C,E=j===!0||typeof j=="number"&&n<j||typeof j=="function"&&j(n,w);if(t||!E){f(w);return}n++,(P=e.onFail)==null||P.call(e,n,w),Uf(x).then(()=>u()?void 0:m()).then(()=>{t?f(w):S()})})};return{promise:o,status:()=>o.status,cancel:a,continue:()=>(r==null||r(),o),cancelRetry:c,continueRetry:l,canStart:h,start:()=>(h()?S():m().then(S),o)}}var $n,Kl,cd=(Kl=class{constructor(){le(this,$n)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),mi(this.gcTime)&&Z(this,$n,Pn.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(so.isServer()?1/0:300*1e3))}clearGcTimeout(){R(this,$n)!==void 0&&(Pn.clearTimeout(R(this,$n)),Z(this,$n,void 0))}},$n=new WeakMap,Kl);function Yf(e){return{onFetch:(t,n)=>{var h,d,f,m,S;const r=t.options,o=(f=(d=(h=t.fetchOptions)==null?void 0:h.meta)==null?void 0:d.fetchMore)==null?void 0:f.direction,i=((m=t.state.data)==null?void 0:m.pages)||[],a=((S=t.state.data)==null?void 0:S.pageParams)||[];let c={pages:[],pageParams:[]},l=0;const u=async()=>{let v=!1;const b=C=>{Vf(C,()=>t.signal,()=>v=!0)},w=od(t.options,t.fetchOptions),j=async(C,x,E)=>{if(v)return Promise.reject(t.signal.reason);if(x==null&&C.pages.length)return Promise.resolve(C);const A=(()=>{const O={client:t.client,queryKey:t.queryKey,pageParam:x,direction:E?"backward":"forward",meta:t.options.meta};return b(O),O})(),g=await w(A),{maxPages:I}=t.options,T=E?Kf:Wf;return{pages:T(C.pages,g,I),pageParams:T(C.pageParams,x,I)}};if(o&&i.length){const C=o==="backward",x=C?Xf:cc,E={pages:i,pageParams:a},P=x(r,E);c=await j(E,P,C)}else{const C=e??i.length;do{const x=l===0?a[0]??r.initialPageParam:cc(r,c);if(l>0&&x==null)break;c=await j(c,x),l++}while(l<C)}return c};t.options.persister?t.fetchFn=()=>{var v,b;return(b=(v=t.options).persister)==null?void 0:b.call(v,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function cc(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Xf(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var br,Mn,xr,xt,Ln,Le,mo,Nn,ft,ld,Gt,Vl,Zf=(Vl=class extends cd{constructor(t){super();le(this,ft);le(this,br);le(this,Mn);le(this,xr);le(this,xt);le(this,Ln);le(this,Le);le(this,mo);le(this,Nn);Z(this,Nn,!1),Z(this,mo,t.defaultOptions),this.setOptions(t.options),this.observers=[],Z(this,Ln,t.client),Z(this,xt,R(this,Ln).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Z(this,Mn,dc(this.options)),this.state=t.state??R(this,Mn),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return R(this,br)}get promise(){var t;return(t=R(this,Le))==null?void 0:t.promise}setOptions(t){if(this.options={...R(this,mo),...t},t!=null&&t._type&&Z(this,br,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=dc(this.options);n.data!==void 0&&(this.setState(lc(n.data,n.dataUpdatedAt)),Z(this,Mn,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&R(this,xt).remove(this)}setData(t,n){const r=bi(this.state.data,t,this.options);return fe(this,ft,Gt).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){fe(this,ft,Gt).call(this,{type:"setState",state:t})}cancel(t){var r,o;const n=(r=R(this,Le))==null?void 0:r.promise;return(o=R(this,Le))==null||o.cancel(t),n?n.then(at).catch(at):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return R(this,Mn)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ht(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Qi||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>gn(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!nd(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,Le))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,Le))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),R(this,xt).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(R(this,Le)&&(R(this,Nn)||fe(this,ft,ld).call(this)?R(this,Le).cancel({revert:!0}):R(this,Le).cancelRetry()),this.scheduleGc()),R(this,xt).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||fe(this,ft,Gt).call(this,{type:"invalidate"})}async fetch(t,n){var u,h,d,f,m,S,v,b,w,j,C;if(this.state.fetchStatus!=="idle"&&((u=R(this,Le))==null?void 0:u.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(R(this,Le))return R(this,Le).continueRetry(),R(this,Le).promise}if(t&&this.setOptions(t),!this.options.queryFn){const x=this.observers.find(E=>E.options.queryFn);x&&this.setOptions(x.options)}const r=new AbortController,o=x=>{Object.defineProperty(x,"signal",{enumerable:!0,get:()=>(Z(this,Nn,!0),r.signal)})},i=()=>{const x=od(this.options,n),P=(()=>{const A={client:R(this,Ln),queryKey:this.queryKey,meta:this.meta};return o(A),A})();return Z(this,Nn,!1),this.options.persister?this.options.persister(x,P,this):x(P)},c=(()=>{const x={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:R(this,Ln),state:this.state,fetchFn:i};return o(x),x})(),l=R(this,br)==="infinite"?Yf(this.options.pages):this.options.behavior;l==null||l.onFetch(c,this),Z(this,xr,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=c.fetchOptions)==null?void 0:h.meta))&&fe(this,ft,Gt).call(this,{type:"fetch",meta:(d=c.fetchOptions)==null?void 0:d.meta}),Z(this,Le,ad({initialPromise:n==null?void 0:n.initialPromise,fn:c.fetchFn,onCancel:x=>{x instanceof vi&&x.revert&&this.setState({...R(this,xr),fetchStatus:"idle"}),r.abort()},onFail:(x,E)=>{fe(this,ft,Gt).call(this,{type:"failed",failureCount:x,error:E})},onPause:()=>{fe(this,ft,Gt).call(this,{type:"pause"})},onContinue:()=>{fe(this,ft,Gt).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{const x=await R(this,Le).start();if(x===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(x),(m=(f=R(this,xt).config).onSuccess)==null||m.call(f,x,this),(v=(S=R(this,xt).config).onSettled)==null||v.call(S,x,this.state.error,this),x}catch(x){if(x instanceof vi){if(x.silent)return R(this,Le).promise;if(x.revert){if(this.state.data===void 0)throw x;return this.state.data}}throw fe(this,ft,Gt).call(this,{type:"error",error:x}),(w=(b=R(this,xt).config).onError)==null||w.call(b,x,this),(C=(j=R(this,xt).config).onSettled)==null||C.call(j,this.state.data,x,this),x}finally{this.scheduleGc()}}},br=new WeakMap,Mn=new WeakMap,xr=new WeakMap,xt=new WeakMap,Ln=new WeakMap,Le=new WeakMap,mo=new WeakMap,Nn=new WeakMap,ft=new WeakSet,ld=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Gt=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...dd(r.data,this.options),fetchMeta:t.meta??null};case"success":const o={...r,...lc(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Z(this,xr,t.manual?o:void 0),o;case"error":const i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Ue.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),R(this,xt).notify({query:this,type:"updated",action:t})})},Vl);function dd(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:id(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function lc(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function dc(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var it,he,go,Xe,Bn,vr,Qt,un,yo,Sr,wr,Fn,zn,pn,kr,Se,Hr,Si,wi,ki,Ci,ji,Ei,Ti,ud,Hl,eh=(Hl=class extends vo{constructor(t,n){super();le(this,Se);le(this,it);le(this,he);le(this,go);le(this,Xe);le(this,Bn);le(this,vr);le(this,Qt);le(this,un);le(this,yo);le(this,Sr);le(this,wr);le(this,Fn);le(this,zn);le(this,pn);le(this,kr,new Set);this.options=n,Z(this,it,t),Z(this,un,null),Z(this,Qt,xi()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(R(this,he).addObserver(this),uc(R(this,he),this.options)?fe(this,Se,Hr).call(this):this.updateResult(),fe(this,Se,Ci).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ai(R(this,he),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ai(R(this,he),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,fe(this,Se,ji).call(this),fe(this,Se,Ei).call(this),R(this,he).removeObserver(this)}setOptions(t){const n=this.options,r=R(this,he);if(this.options=R(this,it).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ht(this.options.enabled,R(this,he))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");fe(this,Se,Ti).call(this),R(this,he).setOptions(this.options),n._defaulted&&!gi(this.options,n)&&R(this,it).getQueryCache().notify({type:"observerOptionsUpdated",query:R(this,he),observer:this});const o=this.hasListeners();o&&pc(R(this,he),r,this.options,n)&&fe(this,Se,Hr).call(this),this.updateResult(),o&&(R(this,he)!==r||ht(this.options.enabled,R(this,he))!==ht(n.enabled,R(this,he))||gn(this.options.staleTime,R(this,he))!==gn(n.staleTime,R(this,he)))&&fe(this,Se,Si).call(this);const i=fe(this,Se,wi).call(this);o&&(R(this,he)!==r||ht(this.options.enabled,R(this,he))!==ht(n.enabled,R(this,he))||i!==R(this,pn))&&fe(this,Se,ki).call(this,i)}getOptimisticResult(t){const n=R(this,it).getQueryCache().build(R(this,it),t),r=this.createResult(n,t);return nh(this,r)&&(Z(this,Xe,r),Z(this,vr,this.options),Z(this,Bn,R(this,he).state)),r}getCurrentResult(){return R(this,Xe)}trackResult(t,n){return new Proxy(t,{get:(r,o)=>(this.trackProp(o),n==null||n(o),o==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&R(this,Qt).status==="pending"&&R(this,Qt).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,o))})}trackProp(t){R(this,kr).add(t)}getCurrentQuery(){return R(this,he)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=R(this,it).defaultQueryOptions(t),r=R(this,it).getQueryCache().build(R(this,it),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return fe(this,Se,Hr).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),R(this,Xe)))}createResult(t,n){var I;const r=R(this,he),o=this.options,i=R(this,Xe),a=R(this,Bn),c=R(this,vr),u=t!==r?t.state:R(this,go),{state:h}=t;let d={...h},f=!1,m;if(n._optimisticResults){const T=this.hasListeners(),O=!T&&uc(t,n),_=T&&pc(t,r,n,o);(O||_)&&(d={...d,...dd(h.data,t.options)}),n._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:S,errorUpdatedAt:v,status:b}=d;m=d.data;let w=!1;if(n.placeholderData!==void 0&&m===void 0&&b==="pending"){let T;i!=null&&i.isPlaceholderData&&n.placeholderData===(c==null?void 0:c.placeholderData)?(T=i.data,w=!0):T=typeof n.placeholderData=="function"?n.placeholderData((I=R(this,wr))==null?void 0:I.state.data,R(this,wr)):n.placeholderData,T!==void 0&&(b="success",m=bi(i==null?void 0:i.data,T,n),f=!0)}if(n.select&&m!==void 0&&!w)if(i&&m===(a==null?void 0:a.data)&&n.select===R(this,yo))m=R(this,Sr);else try{Z(this,yo,n.select),m=n.select(m),m=bi(i==null?void 0:i.data,m,n),Z(this,Sr,m),Z(this,un,null)}catch(T){Z(this,un,T)}R(this,un)&&(S=R(this,un),m=R(this,Sr),v=Date.now(),b="error");const j=d.fetchStatus==="fetching",C=b==="pending",x=b==="error",E=C&&j,P=m!==void 0,g={status:b,fetchStatus:d.fetchStatus,isPending:C,isSuccess:b==="success",isError:x,isInitialLoading:E,isLoading:E,data:m,dataUpdatedAt:d.dataUpdatedAt,error:S,errorUpdatedAt:v,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:j,isRefetching:j&&!C,isLoadingError:x&&!P,isPaused:d.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:x&&P,isStale:Ji(t,n),refetch:this.refetch,promise:R(this,Qt),isEnabled:ht(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const T=g.data!==void 0,O=g.status==="error"&&!T,_=G=>{O?G.reject(g.error):T&&G.resolve(g.data)},M=()=>{const G=Z(this,Qt,g.promise=xi());_(G)},q=R(this,Qt);switch(q.status){case"pending":t.queryHash===r.queryHash&&_(q);break;case"fulfilled":(O||g.data!==q.value)&&M();break;case"rejected":(!O||g.error!==q.reason)&&M();break}}return g}updateResult(){const t=R(this,Xe),n=this.createResult(R(this,he),this.options);if(Z(this,Bn,R(this,he).state),Z(this,vr,this.options),R(this,Bn).data!==void 0&&Z(this,wr,R(this,he)),gi(n,t))return;Z(this,Xe,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:o}=this.options,i=typeof o=="function"?o():o;if(i==="all"||!i&&!R(this,kr).size)return!0;const a=new Set(i??R(this,kr));return this.options.throwOnError&&a.add("error"),Object.keys(R(this,Xe)).some(c=>{const l=c;return R(this,Xe)[l]!==t[l]&&a.has(l)})};fe(this,Se,ud).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&fe(this,Se,Ci).call(this)}},it=new WeakMap,he=new WeakMap,go=new WeakMap,Xe=new WeakMap,Bn=new WeakMap,vr=new WeakMap,Qt=new WeakMap,un=new WeakMap,yo=new WeakMap,Sr=new WeakMap,wr=new WeakMap,Fn=new WeakMap,zn=new WeakMap,pn=new WeakMap,kr=new WeakMap,Se=new WeakSet,Hr=function(t){fe(this,Se,Ti).call(this);let n=R(this,he).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(at)),n},Si=function(){fe(this,Se,ji).call(this);const t=gn(this.options.staleTime,R(this,he));if(so.isServer()||R(this,Xe).isStale||!mi(t))return;const r=nd(R(this,Xe).dataUpdatedAt,t)+1;Z(this,Fn,Pn.setTimeout(()=>{R(this,Xe).isStale||this.updateResult()},r))},wi=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(R(this,he)):this.options.refetchInterval)??!1},ki=function(t){fe(this,Se,Ei).call(this),Z(this,pn,t),!(so.isServer()||ht(this.options.enabled,R(this,he))===!1||!mi(R(this,pn))||R(this,pn)===0)&&Z(this,zn,Pn.setInterval(()=>{(this.options.refetchIntervalInBackground||Hi.isFocused())&&fe(this,Se,Hr).call(this)},R(this,pn)))},Ci=function(){fe(this,Se,Si).call(this),fe(this,Se,ki).call(this,fe(this,Se,wi).call(this))},ji=function(){R(this,Fn)!==void 0&&(Pn.clearTimeout(R(this,Fn)),Z(this,Fn,void 0))},Ei=function(){R(this,zn)!==void 0&&(Pn.clearInterval(R(this,zn)),Z(this,zn,void 0))},Ti=function(){const t=R(this,it).getQueryCache().build(R(this,it),this.options);if(t===R(this,he))return;const n=R(this,he);Z(this,he,t),Z(this,go,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},ud=function(t){Ue.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(R(this,Xe))}),R(this,it).getQueryCache().notify({query:R(this,he),type:"observerResultsUpdated"})})},Hl);function th(e,t){return ht(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&ht(t.retryOnMount,e)===!1)}function uc(e,t){return th(e,t)||e.state.data!==void 0&&Ai(e,t,t.refetchOnMount)}function Ai(e,t,n){if(ht(t.enabled,e)!==!1&&gn(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ji(e,t)}return!1}function pc(e,t,n,r){return(e!==t||ht(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ji(e,n)}function Ji(e,t){return ht(t.enabled,e)!==!1&&e.isStaleByTime(gn(t.staleTime,e))}function nh(e,t){return!gi(e.getCurrentResult(),t)}var bo,Lt,He,qn,Nt,on,Gl,rh=(Gl=class extends cd{constructor(t){super();le(this,Nt);le(this,bo);le(this,Lt);le(this,He);le(this,qn);Z(this,bo,t.client),this.mutationId=t.mutationId,Z(this,He,t.mutationCache),Z(this,Lt,[]),this.state=t.state||oh(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){R(this,Lt).includes(t)||(R(this,Lt).push(t),this.clearGcTimeout(),R(this,He).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Z(this,Lt,R(this,Lt).filter(n=>n!==t)),this.scheduleGc(),R(this,He).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){R(this,Lt).length||(this.state.status==="pending"?this.scheduleGc():R(this,He).remove(this))}continue(){var t;return((t=R(this,qn))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P,A;const n=()=>{fe(this,Nt,on).call(this,{type:"continue"})},r={client:R(this,bo),meta:this.options.meta,mutationKey:this.options.mutationKey};Z(this,qn,ad({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(g,I)=>{fe(this,Nt,on).call(this,{type:"failed",failureCount:g,error:I})},onPause:()=>{fe(this,Nt,on).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>R(this,He).canRun(this)}));const o=this.state.status==="pending",i=!R(this,qn).canStart();try{if(o)n();else{fe(this,Nt,on).call(this,{type:"pending",variables:t,isPaused:i}),R(this,He).config.onMutate&&await R(this,He).config.onMutate(t,this,r);const I=await((c=(a=this.options).onMutate)==null?void 0:c.call(a,t,r));I!==this.state.context&&fe(this,Nt,on).call(this,{type:"pending",context:I,variables:t,isPaused:i})}const g=await R(this,qn).start();return await((u=(l=R(this,He).config).onSuccess)==null?void 0:u.call(l,g,t,this.state.context,this,r)),await((d=(h=this.options).onSuccess)==null?void 0:d.call(h,g,t,this.state.context,r)),await((m=(f=R(this,He).config).onSettled)==null?void 0:m.call(f,g,null,this.state.variables,this.state.context,this,r)),await((v=(S=this.options).onSettled)==null?void 0:v.call(S,g,null,t,this.state.context,r)),fe(this,Nt,on).call(this,{type:"success",data:g}),g}catch(g){try{await((w=(b=R(this,He).config).onError)==null?void 0:w.call(b,g,t,this.state.context,this,r))}catch(I){Promise.reject(I)}try{await((C=(j=this.options).onError)==null?void 0:C.call(j,g,t,this.state.context,r))}catch(I){Promise.reject(I)}try{await((E=(x=R(this,He).config).onSettled)==null?void 0:E.call(x,void 0,g,this.state.variables,this.state.context,this,r))}catch(I){Promise.reject(I)}try{await((A=(P=this.options).onSettled)==null?void 0:A.call(P,void 0,g,t,this.state.context,r))}catch(I){Promise.reject(I)}throw fe(this,Nt,on).call(this,{type:"error",error:g}),g}finally{R(this,He).runNext(this)}}},bo=new WeakMap,Lt=new WeakMap,He=new WeakMap,qn=new WeakMap,Nt=new WeakSet,on=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Ue.batch(()=>{R(this,Lt).forEach(r=>{r.onMutationUpdate(t)}),R(this,He).notify({mutation:this,type:"updated",action:t})})},Gl);function oh(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Jt,Ot,xo,Ql,sh=(Ql=class extends vo{constructor(t={}){super();le(this,Jt);le(this,Ot);le(this,xo);this.config=t,Z(this,Jt,new Set),Z(this,Ot,new Map),Z(this,xo,0)}build(t,n,r){const o=new rh({client:t,mutationCache:this,mutationId:++$o(this,xo)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){R(this,Jt).add(t);const n=Lo(t);if(typeof n=="string"){const r=R(this,Ot).get(n);r?r.push(t):R(this,Ot).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(R(this,Jt).delete(t)){const n=Lo(t);if(typeof n=="string"){const r=R(this,Ot).get(n);if(r)if(r.length>1){const o=r.indexOf(t);o!==-1&&r.splice(o,1)}else r[0]===t&&R(this,Ot).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Lo(t);if(typeof n=="string"){const r=R(this,Ot).get(n),o=r==null?void 0:r.find(i=>i.state.status==="pending");return!o||o===t}else return!0}runNext(t){var r;const n=Lo(t);if(typeof n=="string"){const o=(r=R(this,Ot).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(o==null?void 0:o.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ue.batch(()=>{R(this,Jt).forEach(t=>{this.notify({type:"removed",mutation:t})}),R(this,Jt).clear(),R(this,Ot).clear()})}getAll(){return Array.from(R(this,Jt))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>sc(n,r))}findAll(t={}){return this.getAll().filter(n=>sc(t,n))}notify(t){Ue.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Ue.batch(()=>Promise.all(t.map(n=>n.continue().catch(at))))}},Jt=new WeakMap,Ot=new WeakMap,xo=new WeakMap,Ql);function Lo(e){var t;return(t=e.options.scope)==null?void 0:t.id}var Bt,Jl,ih=(Jl=class extends vo{constructor(t={}){super();le(this,Bt);this.config=t,Z(this,Bt,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gi(o,n);let a=this.get(i);return a||(a=new Zf({client:t,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(a)),a}add(t){R(this,Bt).has(t.queryHash)||(R(this,Bt).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=R(this,Bt).get(t.queryHash);n&&(t.destroy(),n===t&&R(this,Bt).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Ue.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return R(this,Bt).get(t)}getAll(){return[...R(this,Bt).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>oc(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>oc(t,r)):n}notify(t){Ue.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Ue.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Ue.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Bt=new WeakMap,Jl),Ae,fn,hn,Cr,jr,mn,Er,Tr,Yl,ah=(Yl=class{constructor(e={}){le(this,Ae);le(this,fn);le(this,hn);le(this,Cr);le(this,jr);le(this,mn);le(this,Er);le(this,Tr);Z(this,Ae,e.queryCache||new ih),Z(this,fn,e.mutationCache||new sh),Z(this,hn,e.defaultOptions||{}),Z(this,Cr,new Map),Z(this,jr,new Map),Z(this,mn,0)}mount(){$o(this,mn)._++,R(this,mn)===1&&(Z(this,Er,Hi.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ae).onFocus())})),Z(this,Tr,os.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ae).onOnline())})))}unmount(){var e,t;$o(this,mn)._--,R(this,mn)===0&&((e=R(this,Er))==null||e.call(this),Z(this,Er,void 0),(t=R(this,Tr))==null||t.call(this),Z(this,Tr,void 0))}isFetching(e){return R(this,Ae).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return R(this,fn).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ae).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=R(this,Ae).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(gn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return R(this,Ae).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),o=R(this,Ae).get(r.queryHash),i=o==null?void 0:o.state.data,a=zf(t,i);if(a!==void 0)return R(this,Ae).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Ue.batch(()=>R(this,Ae).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ae).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=R(this,Ae);Ue.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=R(this,Ae);return Ue.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Ue.batch(()=>R(this,Ae).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(at).catch(at)}invalidateQueries(e,t={}){return Ue.batch(()=>(R(this,Ae).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Ue.batch(()=>R(this,Ae).findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(at)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(at)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=R(this,Ae).build(this,t);return n.isStaleByTime(gn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(at).catch(at)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(at).catch(at)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return os.isOnline()?R(this,fn).resumePausedMutations():Promise.resolve()}getQueryCache(){return R(this,Ae)}getMutationCache(){return R(this,fn)}getDefaultOptions(){return R(this,hn)}setDefaultOptions(e){Z(this,hn,e)}setQueryDefaults(e,t){R(this,Cr).set(oo(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...R(this,Cr).values()],n={};return t.forEach(r=>{Ar(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){R(this,jr).set(oo(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...R(this,jr).values()],n={};return t.forEach(r=>{Ar(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...R(this,hn).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gi(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Qi&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...R(this,hn).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){R(this,Ae).clear(),R(this,fn).clear()}},Ae=new WeakMap,fn=new WeakMap,hn=new WeakMap,Cr=new WeakMap,jr=new WeakMap,mn=new WeakMap,Er=new WeakMap,Tr=new WeakMap,Yl),pd=p.createContext(void 0),Yi=e=>{const t=p.useContext(pd);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},ch=({client:e,children:t})=>(p.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),s.jsx(pd.Provider,{value:e,children:t})),fd=p.createContext(!1),lh=()=>p.useContext(fd);fd.Provider;function dh(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var uh=p.createContext(dh()),ph=()=>p.useContext(uh),fh=(e,t,n)=>{const r=n!=null&&n.state.error&&typeof e.throwOnError=="function"?sd(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},hh=e=>{p.useEffect(()=>{e.clearReset()},[e])},mh=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||sd(n,[e.error,r])),gh=e=>{if(e.suspense){const n=o=>o==="static"?o:Math.max(o??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...o)=>n(r(...o)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},yh=(e,t)=>e.isLoading&&e.isFetching&&!t,bh=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,fc=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function xh(e,t,n){var m,S,v,b;const r=lh(),o=ph(),i=Yi(),a=i.defaultQueryOptions(e);(S=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||S.call(m,a);const c=i.getQueryCache().get(a.queryHash),l=e.subscribed!==!1;a._optimisticResults=r?"isRestoring":l?"optimistic":void 0,gh(a),fh(a,o,c),hh(o);const u=!i.getQueryCache().get(a.queryHash),[h]=p.useState(()=>new t(i,a)),d=h.getOptimisticResult(a),f=!r&&l;if(p.useSyncExternalStore(p.useCallback(w=>{const j=f?h.subscribe(Ue.batchCalls(w)):at;return h.updateResult(),j},[h,f]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),p.useEffect(()=>{h.setOptions(a)},[a,h]),bh(a,d))throw fc(a,h,o);if(mh({result:d,errorResetBoundary:o,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw d.error;if((b=(v=i.getDefaultOptions().queries)==null?void 0:v._experimental_afterQuery)==null||b.call(v,a,d),a.experimental_prefetchInRender&&!so.isServer()&&yh(d,r)){const w=u?fc(a,h,o):c==null?void 0:c.promise;w==null||w.catch(at).finally(()=>{h.updateResult()})}return a.notifyOnChangeProps?d:h.trackResult(d)}function Ri(e,t){return xh(e,eh)}const ye={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"},be={1:"4px",2:"8px",3:"12px",4:"16px"},wn={sm:"4px",md:"6px",lg:"8px"},Ze={xs:"11px",sm:"12px",md:"14px"},Xi={medium:"500",semibold:"600"},io={overlay:1e3,modal:1100,popover:1200,tooltip:1300},Ns={surfaceBase:ye.gray1000,surfaceRaised:ye.gray975,surfaceElevated:ye.gray950,surfaceOverlay:"rgba(0,0,0,0.7)",surfaceHover:ye.gray900,surfaceActive:"#1f2d3d",surfaceSunken:ye.gray1000,borderSubtle:"#21262d",borderDefault:"#30363d",borderStrong:"#484f58",borderFocus:ye.blue500,textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",textDisabled:"#32383f",textInverse:ye.gray1000,accent:ye.blue500,accentHover:ye.blue400,accentMuted:"rgba(56,139,253,0.15)",accentContrast:"#ffffff",success:ye.green500,warning:ye.yellow500,danger:ye.red500,info:ye.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)"},No={surfaceBase:ye.gray0,surfaceRaised:ye.gray50,surfaceElevated:ye.gray0,surfaceOverlay:"rgba(0,0,0,0.4)",surfaceHover:ye.gray100,surfaceActive:"#dbeafe",surfaceSunken:ye.gray50,borderSubtle:ye.gray100,borderDefault:ye.gray200,borderStrong:ye.gray300,borderFocus:ye.blue600,textPrimary:"#1f2328",textSecondary:ye.gray600,textMuted:ye.gray400,textDisabled:ye.gray300,textInverse:ye.gray0,accent:ye.blue600,accentHover:ye.blue700,accentMuted:"rgba(9,105,218,0.12)",accentContrast:"#ffffff",success:ye.green600,warning:ye.yellow600,danger:ye.red600,info:ye.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)"},vh={obsidian:Ns,paper:No,white:No,dark:Ns,light:No,midnight:Ns,arctic:No};function hd(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function hc(e){const t={};for(const[n,r]of Object.entries(e))t[hd(n)]=r;return t}function pe(e){return`var(${hd(e)})`}const Sh=p.createContext(null);function wh({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[i,a]=p.useState(t),c=e??i,l=vh[c],u=p.useCallback(f=>{e===void 0&&a(f),n==null||n(f)},[e,n]);p.useEffect(()=>{if(!r)return;const f=hc(l),m=document.documentElement;for(const[S,v]of Object.entries(f))m.style.setProperty(S,v);return m.setAttribute("data-theme",c),()=>{for(const S of Object.keys(f))m.style.removeProperty(S);m.removeAttribute("data-theme")}},[r,c,l]);const h=p.useMemo(()=>({theme:c,tokens:l,setTheme:u}),[c,l,u]),d=r?void 0:hc(l);return s.jsx(Sh.Provider,{value:h,children:s.jsx("div",{"data-theme":c,style:d,children:o})})}function de(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 mc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function bs(...e){return t=>{let n=!1;const r=e.map(o=>{const i=mc(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():mc(e[o],null)}}}}function Oe(...e){return p.useCallback(bs(...e),e)}function kh(e,t){const n=p.createContext(t),r=i=>{const{children:a,...c}=i,l=p.useMemo(()=>c,Object.values(c));return s.jsx(n.Provider,{value:l,children:a})};r.displayName=e+"Provider";function o(i){const a=p.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[r,o]}function kn(e,t=[]){let n=[];function r(i,a){const c=p.createContext(a),l=n.length;n=[...n,a];const u=d=>{var w;const{scope:f,children:m,...S}=d,v=((w=f==null?void 0:f[e])==null?void 0:w[l])||c,b=p.useMemo(()=>S,Object.values(S));return s.jsx(v.Provider,{value:b,children:m})};u.displayName=i+"Provider";function h(d,f){var v;const m=((v=f==null?void 0:f[e])==null?void 0:v[l])||c,S=p.useContext(m);if(S)return S;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,h]}const o=()=>{const i=n.map(a=>p.createContext(a));return function(c){const l=(c==null?void 0:c[e])||i;return p.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return o.scopeName=e,[r,Ch(o,...t)]}function Ch(...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 a=r.reduce((c,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...c,...d}},{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var Zi=Zl();const jh=ed(Zi);function Rr(e){const t=Eh(e),n=p.forwardRef((r,o)=>{const{children:i,...a}=r,c=p.Children.toArray(i),l=c.find(Ah);if(l){const u=l.props.children,h=c.map(d=>d===l?p.Children.count(u)>1?p.Children.only(null):p.isValidElement(u)?u.props.children:null:d);return s.jsx(t,{...a,ref:o,children:p.isValidElement(u)?p.cloneElement(u,void 0,h):null})}return s.jsx(t,{...a,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Eh(e){const t=p.forwardRef((n,r)=>{const{children:o,...i}=n;if(p.isValidElement(o)){const a=Oh(o),c=Rh(i,o.props);return o.type!==p.Fragment&&(c.ref=r?bs(r,a):a),p.cloneElement(o,c)}return p.Children.count(o)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var md=Symbol("radix.slottable");function Th(e){const t=({children:n})=>s.jsx(s.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=md,t}function Ah(e){return p.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===md}function Rh(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]=(...c)=>{const l=i(...c);return o(...c),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Oh(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 _h=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Te=_h.reduce((e,t)=>{const n=Rr(`Primitive.${t}`),r=p.forwardRef((o,i)=>{const{asChild:a,...c}=o,l=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(l,{...c,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function gd(e,t){e&&Zi.flushSync(()=>e.dispatchEvent(t))}function yn(e){const t=p.useRef(e);return p.useEffect(()=>{t.current=e}),p.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function Ph(e,t=globalThis==null?void 0:globalThis.document){const n=yn(e);p.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 Ih="DismissableLayer",Oi="dismissableLayer.update",Dh="dismissableLayer.pointerDownOutside",$h="dismissableLayer.focusOutside",gc,yd=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),So=p.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:a,onDismiss:c,...l}=e,u=p.useContext(yd),[h,d]=p.useState(null),f=(h==null?void 0:h.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,m]=p.useState({}),S=Oe(t,A=>d(A)),v=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),w=v.indexOf(b),j=h?v.indexOf(h):-1,C=u.layersWithOutsidePointerEventsDisabled.size>0,x=j>=w,E=Nh(A=>{const g=A.target,I=[...u.branches].some(T=>T.contains(g));!x||I||(o==null||o(A),a==null||a(A),A.defaultPrevented||c==null||c())},f),P=Bh(A=>{const g=A.target;[...u.branches].some(T=>T.contains(g))||(i==null||i(A),a==null||a(A),A.defaultPrevented||c==null||c())},f);return Ph(A=>{j===u.layers.size-1&&(r==null||r(A),!A.defaultPrevented&&c&&(A.preventDefault(),c()))},f),p.useEffect(()=>{if(h)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(gc=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(h)),u.layers.add(h),yc(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=gc)}},[h,f,n,u]),p.useEffect(()=>()=>{h&&(u.layers.delete(h),u.layersWithOutsidePointerEventsDisabled.delete(h),yc())},[h,u]),p.useEffect(()=>{const A=()=>m({});return document.addEventListener(Oi,A),()=>document.removeEventListener(Oi,A)},[]),s.jsx(Te.div,{...l,ref:S,style:{pointerEvents:C?x?"auto":"none":void 0,...e.style},onFocusCapture:de(e.onFocusCapture,P.onFocusCapture),onBlurCapture:de(e.onBlurCapture,P.onBlurCapture),onPointerDownCapture:de(e.onPointerDownCapture,E.onPointerDownCapture)})});So.displayName=Ih;var Mh="DismissableLayerBranch",Lh=p.forwardRef((e,t)=>{const n=p.useContext(yd),r=p.useRef(null),o=Oe(t,r);return p.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),s.jsx(Te.div,{...e,ref:o})});Lh.displayName=Mh;function Nh(e,t=globalThis==null?void 0:globalThis.document){const n=yn(e),r=p.useRef(!1),o=p.useRef(()=>{});return p.useEffect(()=>{const i=c=>{if(c.target&&!r.current){let l=function(){bd(Dh,n,u,{discrete:!0})};const u={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Bh(e,t=globalThis==null?void 0:globalThis.document){const n=yn(e),r=p.useRef(!1);return p.useEffect(()=>{const o=i=>{i.target&&!r.current&&bd($h,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 yc(){const e=new CustomEvent(Oi);document.dispatchEvent(e)}function bd(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?gd(o,i):o.dispatchEvent(i)}var bn=globalThis!=null&&globalThis.document?p.useLayoutEffect:()=>{},Fh=td[" useId ".trim().toString()]||(()=>{}),zh=0;function to(e){const[t,n]=p.useState(Fh());return bn(()=>{n(r=>r??String(zh++))},[e]),t?`radix-${t}`:""}const qh=["top","right","bottom","left"],xn=Math.min,mt=Math.max,ss=Math.round,Bo=Math.floor,Wt=e=>({x:e,y:e}),Uh={left:"right",right:"left",bottom:"top",top:"bottom"};function _i(e,t,n){return mt(e,xn(t,n))}function Yt(e,t){return typeof e=="function"?e(t):e}function Xt(e){return e.split("-")[0]}function Dr(e){return e.split("-")[1]}function ea(e){return e==="x"?"y":"x"}function ta(e){return e==="y"?"height":"width"}function Ut(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function na(e){return ea(Ut(e))}function Wh(e,t,n){n===void 0&&(n=!1);const r=Dr(e),o=na(e),i=ta(o);let a=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=is(a)),[a,is(a)]}function Kh(e){const t=is(e);return[Pi(e),t,Pi(t)]}function Pi(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const bc=["left","right"],xc=["right","left"],Vh=["top","bottom"],Hh=["bottom","top"];function Gh(e,t,n){switch(e){case"top":case"bottom":return n?t?xc:bc:t?bc:xc;case"left":case"right":return t?Vh:Hh;default:return[]}}function Qh(e,t,n,r){const o=Dr(e);let i=Gh(Xt(e),n==="start",r);return o&&(i=i.map(a=>a+"-"+o),t&&(i=i.concat(i.map(Pi)))),i}function is(e){const t=Xt(e);return Uh[t]+e.slice(t.length)}function Jh(e){return{top:0,right:0,bottom:0,left:0,...e}}function xd(e){return typeof e!="number"?Jh(e):{top:e,right:e,bottom:e,left:e}}function as(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 vc(e,t,n){let{reference:r,floating:o}=e;const i=Ut(t),a=na(t),c=ta(a),l=Xt(t),u=i==="y",h=r.x+r.width/2-o.width/2,d=r.y+r.height/2-o.height/2,f=r[c]/2-o[c]/2;let m;switch(l){case"top":m={x:h,y:r.y-o.height};break;case"bottom":m={x:h,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:d};break;case"left":m={x:r.x-o.width,y:d};break;default:m={x:r.x,y:r.y}}switch(Dr(t)){case"start":m[a]-=f*(n&&u?-1:1);break;case"end":m[a]+=f*(n&&u?-1:1);break}return m}async function Yh(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:i,rects:a,elements:c,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:h="viewport",elementContext:d="floating",altBoundary:f=!1,padding:m=0}=Yt(t,e),S=xd(m),b=c[f?d==="floating"?"reference":"floating":d],w=as(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(c.floating)),boundary:u,rootBoundary:h,strategy:l})),j=d==="floating"?{x:r,y:o,width:a.floating.width,height:a.floating.height}:a.reference,C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c.floating)),x=await(i.isElement==null?void 0:i.isElement(C))?await(i.getScale==null?void 0:i.getScale(C))||{x:1,y:1}:{x:1,y:1},E=as(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:j,offsetParent:C,strategy:l}):j);return{top:(w.top-E.top+S.top)/x.y,bottom:(E.bottom-w.bottom+S.bottom)/x.y,left:(w.left-E.left+S.left)/x.x,right:(E.right-w.right+S.right)/x.x}}const Xh=50,Zh=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:a}=n,c=a.detectOverflow?a:{...a,detectOverflow:Yh},l=await(a.isRTL==null?void 0:a.isRTL(t));let u=await a.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:d}=vc(u,r,l),f=r,m=0;const S={};for(let v=0;v<i.length;v++){const b=i[v];if(!b)continue;const{name:w,fn:j}=b,{x:C,y:x,data:E,reset:P}=await j({x:h,y:d,initialPlacement:r,placement:f,strategy:o,middlewareData:S,rects:u,platform:c,elements:{reference:e,floating:t}});h=C??h,d=x??d,S[w]={...S[w],...E},P&&m<Xh&&(m++,typeof P=="object"&&(P.placement&&(f=P.placement),P.rects&&(u=P.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:o}):P.rects),{x:h,y:d}=vc(u,f,l)),v=-1)}return{x:h,y:d,placement:f,strategy:o,middlewareData:S}},em=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:a,elements:c,middlewareData:l}=t,{element:u,padding:h=0}=Yt(e,t)||{};if(u==null)return{};const d=xd(h),f={x:n,y:r},m=na(o),S=ta(m),v=await a.getDimensions(u),b=m==="y",w=b?"top":"left",j=b?"bottom":"right",C=b?"clientHeight":"clientWidth",x=i.reference[S]+i.reference[m]-f[m]-i.floating[S],E=f[m]-i.reference[m],P=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let A=P?P[C]:0;(!A||!await(a.isElement==null?void 0:a.isElement(P)))&&(A=c.floating[C]||i.floating[S]);const g=x/2-E/2,I=A/2-v[S]/2-1,T=xn(d[w],I),O=xn(d[j],I),_=T,M=A-v[S]-O,q=A/2-v[S]/2+g,G=_i(_,q,M),J=!l.arrow&&Dr(o)!=null&&q!==G&&i.reference[S]/2-(q<_?T:O)-v[S]/2<0,H=J?q<_?q-_:q-M:0;return{[m]:f[m]+H,data:{[m]:G,centerOffset:q-G-H,...J&&{alignmentOffset:H}},reset:J}}}),tm=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:i,rects:a,initialPlacement:c,platform:l,elements:u}=t,{mainAxis:h=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:v=!0,...b}=Yt(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const w=Xt(o),j=Ut(c),C=Xt(c)===c,x=await(l.isRTL==null?void 0:l.isRTL(u.floating)),E=f||(C||!v?[is(c)]:Kh(c)),P=S!=="none";!f&&P&&E.push(...Qh(c,v,S,x));const A=[c,...E],g=await l.detectOverflow(t,b),I=[];let T=((r=i.flip)==null?void 0:r.overflows)||[];if(h&&I.push(g[w]),d){const q=Wh(o,a,x);I.push(g[q[0]],g[q[1]])}if(T=[...T,{placement:o,overflows:I}],!I.every(q=>q<=0)){var O,_;const q=(((O=i.flip)==null?void 0:O.index)||0)+1,G=A[q];if(G&&(!(d==="alignment"?j!==Ut(G):!1)||T.every(L=>Ut(L.placement)===j?L.overflows[0]>0:!0)))return{data:{index:q,overflows:T},reset:{placement:G}};let J=(_=T.filter(H=>H.overflows[0]<=0).sort((H,L)=>H.overflows[1]-L.overflows[1])[0])==null?void 0:_.placement;if(!J)switch(m){case"bestFit":{var M;const H=(M=T.filter(L=>{if(P){const $=Ut(L.placement);return $===j||$==="y"}return!0}).map(L=>[L.placement,L.overflows.filter($=>$>0).reduce(($,X)=>$+X,0)]).sort((L,$)=>L[1]-$[1])[0])==null?void 0:M[0];H&&(J=H);break}case"initialPlacement":J=c;break}if(o!==J)return{reset:{placement:J}}}return{}}}};function Sc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function wc(e){return qh.some(t=>e[t]>=0)}const nm=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:o="referenceHidden",...i}=Yt(e,t);switch(o){case"referenceHidden":{const a=await r.detectOverflow(t,{...i,elementContext:"reference"}),c=Sc(a,n.reference);return{data:{referenceHiddenOffsets:c,referenceHidden:wc(c)}}}case"escaped":{const a=await r.detectOverflow(t,{...i,altBoundary:!0}),c=Sc(a,n.floating);return{data:{escapedOffsets:c,escaped:wc(c)}}}default:return{}}}}},vd=new Set(["left","top"]);async function rm(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),a=Xt(n),c=Dr(n),l=Ut(n)==="y",u=vd.has(a)?-1:1,h=i&&l?-1:1,d=Yt(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:S}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return c&&typeof S=="number"&&(m=c==="end"?S*-1:S),l?{x:m*h,y:f*u}:{x:f*u,y:m*h}}const om=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:i,placement:a,middlewareData:c}=t,l=await rm(t,e);return a===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:i+l.y,data:{...l,placement:a}}}}},sm=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:a=!0,crossAxis:c=!1,limiter:l={fn:w=>{let{x:j,y:C}=w;return{x:j,y:C}}},...u}=Yt(e,t),h={x:n,y:r},d=await i.detectOverflow(t,u),f=Ut(Xt(o)),m=ea(f);let S=h[m],v=h[f];if(a){const w=m==="y"?"top":"left",j=m==="y"?"bottom":"right",C=S+d[w],x=S-d[j];S=_i(C,S,x)}if(c){const w=f==="y"?"top":"left",j=f==="y"?"bottom":"right",C=v+d[w],x=v-d[j];v=_i(C,v,x)}const b=l.fn({...t,[m]:S,[f]:v});return{...b,data:{x:b.x-n,y:b.y-r,enabled:{[m]:a,[f]:c}}}}}},im=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:a}=t,{offset:c=0,mainAxis:l=!0,crossAxis:u=!0}=Yt(e,t),h={x:n,y:r},d=Ut(o),f=ea(d);let m=h[f],S=h[d];const v=Yt(c,t),b=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:0,crossAxis:0,...v};if(l){const C=f==="y"?"height":"width",x=i.reference[f]-i.floating[C]+b.mainAxis,E=i.reference[f]+i.reference[C]-b.mainAxis;m<x?m=x:m>E&&(m=E)}if(u){var w,j;const C=f==="y"?"width":"height",x=vd.has(Xt(o)),E=i.reference[d]-i.floating[C]+(x&&((w=a.offset)==null?void 0:w[d])||0)+(x?0:b.crossAxis),P=i.reference[d]+i.reference[C]+(x?0:((j=a.offset)==null?void 0:j[d])||0)-(x?b.crossAxis:0);S<E?S=E:S>P&&(S=P)}return{[f]:m,[d]:S}}}},am=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:i,platform:a,elements:c}=t,{apply:l=()=>{},...u}=Yt(e,t),h=await a.detectOverflow(t,u),d=Xt(o),f=Dr(o),m=Ut(o)==="y",{width:S,height:v}=i.floating;let b,w;d==="top"||d==="bottom"?(b=d,w=f===(await(a.isRTL==null?void 0:a.isRTL(c.floating))?"start":"end")?"left":"right"):(w=d,b=f==="end"?"top":"bottom");const j=v-h.top-h.bottom,C=S-h.left-h.right,x=xn(v-h[b],j),E=xn(S-h[w],C),P=!t.middlewareData.shift;let A=x,g=E;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(g=C),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=j),P&&!f){const T=mt(h.left,0),O=mt(h.right,0),_=mt(h.top,0),M=mt(h.bottom,0);m?g=S-2*(T!==0||O!==0?T+O:mt(h.left,h.right)):A=v-2*(_!==0||M!==0?_+M:mt(h.top,h.bottom))}await l({...t,availableWidth:g,availableHeight:A});const I=await a.getDimensions(c.floating);return S!==I.width||v!==I.height?{reset:{rects:!0}}:{}}}};function xs(){return typeof window<"u"}function $r(e){return Sd(e)?(e.nodeName||"").toLowerCase():"#document"}function gt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Kt(e){var t;return(t=(Sd(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Sd(e){return xs()?e instanceof Node||e instanceof gt(e).Node:!1}function Pt(e){return xs()?e instanceof Element||e instanceof gt(e).Element:!1}function Zt(e){return xs()?e instanceof HTMLElement||e instanceof gt(e).HTMLElement:!1}function kc(e){return!xs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof gt(e).ShadowRoot}function wo(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=It(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&o!=="inline"&&o!=="contents"}function cm(e){return/^(table|td|th)$/.test($r(e))}function vs(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const lm=/transform|translate|scale|rotate|perspective|filter/,dm=/paint|layout|strict|content/,Rn=e=>!!e&&e!=="none";let Bs;function ra(e){const t=Pt(e)?It(e):e;return Rn(t.transform)||Rn(t.translate)||Rn(t.scale)||Rn(t.rotate)||Rn(t.perspective)||!oa()&&(Rn(t.backdropFilter)||Rn(t.filter))||lm.test(t.willChange||"")||dm.test(t.contain||"")}function um(e){let t=vn(e);for(;Zt(t)&&!Or(t);){if(ra(t))return t;if(vs(t))return null;t=vn(t)}return null}function oa(){return Bs==null&&(Bs=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Bs}function Or(e){return/^(html|body|#document)$/.test($r(e))}function It(e){return gt(e).getComputedStyle(e)}function Ss(e){return Pt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function vn(e){if($r(e)==="html")return e;const t=e.assignedSlot||e.parentNode||kc(e)&&e.host||Kt(e);return kc(t)?t.host:t}function wd(e){const t=vn(e);return Or(t)?e.ownerDocument?e.ownerDocument.body:e.body:Zt(t)&&wo(t)?t:wd(t)}function ao(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=wd(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),a=gt(o);if(i){const c=Ii(a);return t.concat(a,a.visualViewport||[],wo(o)?o:[],c&&n?ao(c):[])}else return t.concat(o,ao(o,[],n))}function Ii(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function kd(e){const t=It(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Zt(e),i=o?e.offsetWidth:n,a=o?e.offsetHeight:r,c=ss(n)!==i||ss(r)!==a;return c&&(n=i,r=a),{width:n,height:r,$:c}}function sa(e){return Pt(e)?e:e.contextElement}function pr(e){const t=sa(e);if(!Zt(t))return Wt(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=kd(t);let a=(i?ss(n.width):n.width)/r,c=(i?ss(n.height):n.height)/o;return(!a||!Number.isFinite(a))&&(a=1),(!c||!Number.isFinite(c))&&(c=1),{x:a,y:c}}const pm=Wt(0);function Cd(e){const t=gt(e);return!oa()||!t.visualViewport?pm:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function fm(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==gt(e)?!1:t}function Wn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=sa(e);let a=Wt(1);t&&(r?Pt(r)&&(a=pr(r)):a=pr(e));const c=fm(i,n,r)?Cd(i):Wt(0);let l=(o.left+c.x)/a.x,u=(o.top+c.y)/a.y,h=o.width/a.x,d=o.height/a.y;if(i){const f=gt(i),m=r&&Pt(r)?gt(r):r;let S=f,v=Ii(S);for(;v&&r&&m!==S;){const b=pr(v),w=v.getBoundingClientRect(),j=It(v),C=w.left+(v.clientLeft+parseFloat(j.paddingLeft))*b.x,x=w.top+(v.clientTop+parseFloat(j.paddingTop))*b.y;l*=b.x,u*=b.y,h*=b.x,d*=b.y,l+=C,u+=x,S=gt(v),v=Ii(S)}}return as({width:h,height:d,x:l,y:u})}function ws(e,t){const n=Ss(e).scrollLeft;return t?t.left+n:Wn(Kt(e)).left+n}function jd(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ws(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function hm(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i=o==="fixed",a=Kt(r),c=t?vs(t.floating):!1;if(r===a||c&&i)return n;let l={scrollLeft:0,scrollTop:0},u=Wt(1);const h=Wt(0),d=Zt(r);if((d||!d&&!i)&&(($r(r)!=="body"||wo(a))&&(l=Ss(r)),d)){const m=Wn(r);u=pr(r),h.x=m.x+r.clientLeft,h.y=m.y+r.clientTop}const f=a&&!d&&!i?jd(a,l):Wt(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+h.x+f.x,y:n.y*u.y-l.scrollTop*u.y+h.y+f.y}}function mm(e){return Array.from(e.getClientRects())}function gm(e){const t=Kt(e),n=Ss(e),r=e.ownerDocument.body,o=mt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=mt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+ws(e);const c=-n.scrollTop;return It(r).direction==="rtl"&&(a+=mt(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:a,y:c}}const Cc=25;function ym(e,t){const n=gt(e),r=Kt(e),o=n.visualViewport;let i=r.clientWidth,a=r.clientHeight,c=0,l=0;if(o){i=o.width,a=o.height;const h=oa();(!h||h&&t==="fixed")&&(c=o.offsetLeft,l=o.offsetTop)}const u=ws(r);if(u<=0){const h=r.ownerDocument,d=h.body,f=getComputedStyle(d),m=h.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,S=Math.abs(r.clientWidth-d.clientWidth-m);S<=Cc&&(i-=S)}else u<=Cc&&(i+=u);return{width:i,height:a,x:c,y:l}}function bm(e,t){const n=Wn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Zt(e)?pr(e):Wt(1),a=e.clientWidth*i.x,c=e.clientHeight*i.y,l=o*i.x,u=r*i.y;return{width:a,height:c,x:l,y:u}}function jc(e,t,n){let r;if(t==="viewport")r=ym(e,n);else if(t==="document")r=gm(Kt(e));else if(Pt(t))r=bm(t,n);else{const o=Cd(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return as(r)}function Ed(e,t){const n=vn(e);return n===t||!Pt(n)||Or(n)?!1:It(n).position==="fixed"||Ed(n,t)}function xm(e,t){const n=t.get(e);if(n)return n;let r=ao(e,[],!1).filter(c=>Pt(c)&&$r(c)!=="body"),o=null;const i=It(e).position==="fixed";let a=i?vn(e):e;for(;Pt(a)&&!Or(a);){const c=It(a),l=ra(a);!l&&c.position==="fixed"&&(o=null),(i?!l&&!o:!l&&c.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||wo(a)&&!l&&Ed(e,a))?r=r.filter(h=>h!==a):o=c,a=vn(a)}return t.set(e,r),r}function vm(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const a=[...n==="clippingAncestors"?vs(t)?[]:xm(t,this._c):[].concat(n),r],c=jc(t,a[0],o);let l=c.top,u=c.right,h=c.bottom,d=c.left;for(let f=1;f<a.length;f++){const m=jc(t,a[f],o);l=mt(m.top,l),u=xn(m.right,u),h=xn(m.bottom,h),d=mt(m.left,d)}return{width:u-d,height:h-l,x:d,y:l}}function Sm(e){const{width:t,height:n}=kd(e);return{width:t,height:n}}function wm(e,t,n){const r=Zt(t),o=Kt(t),i=n==="fixed",a=Wn(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=Wt(0);function u(){l.x=ws(o)}if(r||!r&&!i)if(($r(t)!=="body"||wo(o))&&(c=Ss(t)),r){const m=Wn(t,!0,i,t);l.x=m.x+t.clientLeft,l.y=m.y+t.clientTop}else o&&u();i&&!r&&o&&u();const h=o&&!r&&!i?jd(o,c):Wt(0),d=a.left+c.scrollLeft-l.x-h.x,f=a.top+c.scrollTop-l.y-h.y;return{x:d,y:f,width:a.width,height:a.height}}function Fs(e){return It(e).position==="static"}function Ec(e,t){if(!Zt(e)||It(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Kt(e)===n&&(n=n.ownerDocument.body),n}function Td(e,t){const n=gt(e);if(vs(e))return n;if(!Zt(e)){let o=vn(e);for(;o&&!Or(o);){if(Pt(o)&&!Fs(o))return o;o=vn(o)}return n}let r=Ec(e,t);for(;r&&cm(r)&&Fs(r);)r=Ec(r,t);return r&&Or(r)&&Fs(r)&&!ra(r)?n:r||um(e)||n}const km=async function(e){const t=this.getOffsetParent||Td,n=this.getDimensions,r=await n(e.floating);return{reference:wm(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Cm(e){return It(e).direction==="rtl"}const jm={convertOffsetParentRelativeRectToViewportRelativeRect:hm,getDocumentElement:Kt,getClippingRect:vm,getOffsetParent:Td,getElementRects:km,getClientRects:mm,getDimensions:Sm,getScale:pr,isElement:Pt,isRTL:Cm};function Ad(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Em(e,t){let n=null,r;const o=Kt(e);function i(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function a(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:h,top:d,width:f,height:m}=u;if(c||t(),!f||!m)return;const S=Bo(d),v=Bo(o.clientWidth-(h+f)),b=Bo(o.clientHeight-(d+m)),w=Bo(h),C={rootMargin:-S+"px "+-v+"px "+-b+"px "+-w+"px",threshold:mt(0,xn(1,l))||1};let x=!0;function E(P){const A=P[0].intersectionRatio;if(A!==l){if(!x)return a();A?a(!1,A):r=setTimeout(()=>{a(!1,1e-7)},1e3)}A===1&&!Ad(u,e.getBoundingClientRect())&&a(),x=!1}try{n=new IntersectionObserver(E,{...C,root:o.ownerDocument})}catch{n=new IntersectionObserver(E,C)}n.observe(e)}return a(!0),i}function Tm(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=sa(e),h=o||i?[...u?ao(u):[],...t?ao(t):[]]:[];h.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),i&&w.addEventListener("resize",n)});const d=u&&c?Em(u,n):null;let f=-1,m=null;a&&(m=new ResizeObserver(w=>{let[j]=w;j&&j.target===u&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var C;(C=m)==null||C.observe(t)})),n()}),u&&!l&&m.observe(u),t&&m.observe(t));let S,v=l?Wn(e):null;l&&b();function b(){const w=Wn(e);v&&!Ad(v,w)&&n(),v=w,S=requestAnimationFrame(b)}return n(),()=>{var w;h.forEach(j=>{o&&j.removeEventListener("scroll",n),i&&j.removeEventListener("resize",n)}),d==null||d(),(w=m)==null||w.disconnect(),m=null,l&&cancelAnimationFrame(S)}}const Am=om,Rm=sm,Om=tm,_m=am,Pm=nm,Tc=em,Im=im,Dm=(e,t,n)=>{const r=new Map,o={platform:jm,...n},i={...o.platform,_c:r};return Zh(e,t,{...o,platform:i})};var $m=typeof document<"u",Mm=function(){},Xo=$m?p.useLayoutEffect:Mm;function cs(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(!cs(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)&&!cs(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Rd(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Ac(e,t){const n=Rd(e);return Math.round(t*n)/n}function zs(e){const t=p.useRef(e);return Xo(()=>{t.current=e}),t}function Lm(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:a}={},transform:c=!0,whileElementsMounted:l,open:u}=e,[h,d]=p.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=p.useState(r);cs(f,r)||m(r);const[S,v]=p.useState(null),[b,w]=p.useState(null),j=p.useCallback(L=>{L!==P.current&&(P.current=L,v(L))},[]),C=p.useCallback(L=>{L!==A.current&&(A.current=L,w(L))},[]),x=i||S,E=a||b,P=p.useRef(null),A=p.useRef(null),g=p.useRef(h),I=l!=null,T=zs(l),O=zs(o),_=zs(u),M=p.useCallback(()=>{if(!P.current||!A.current)return;const L={placement:t,strategy:n,middleware:f};O.current&&(L.platform=O.current),Dm(P.current,A.current,L).then($=>{const X={...$,isPositioned:_.current!==!1};q.current&&!cs(g.current,X)&&(g.current=X,Zi.flushSync(()=>{d(X)}))})},[f,t,n,O,_]);Xo(()=>{u===!1&&g.current.isPositioned&&(g.current.isPositioned=!1,d(L=>({...L,isPositioned:!1})))},[u]);const q=p.useRef(!1);Xo(()=>(q.current=!0,()=>{q.current=!1}),[]),Xo(()=>{if(x&&(P.current=x),E&&(A.current=E),x&&E){if(T.current)return T.current(x,E,M);M()}},[x,E,M,T,I]);const G=p.useMemo(()=>({reference:P,floating:A,setReference:j,setFloating:C}),[j,C]),J=p.useMemo(()=>({reference:x,floating:E}),[x,E]),H=p.useMemo(()=>{const L={position:n,left:0,top:0};if(!J.floating)return L;const $=Ac(J.floating,h.x),X=Ac(J.floating,h.y);return c?{...L,transform:"translate("+$+"px, "+X+"px)",...Rd(J.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:$,top:X}},[n,c,J.floating,h.x,h.y]);return p.useMemo(()=>({...h,update:M,refs:G,elements:J,floatingStyles:H}),[h,M,G,J,H])}const Nm=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?Tc({element:r.current,padding:o}).fn(n):{}:r?Tc({element:r,padding:o}).fn(n):{}}}},Bm=(e,t)=>{const n=Am(e);return{name:n.name,fn:n.fn,options:[e,t]}},Fm=(e,t)=>{const n=Rm(e);return{name:n.name,fn:n.fn,options:[e,t]}},zm=(e,t)=>({fn:Im(e).fn,options:[e,t]}),qm=(e,t)=>{const n=Om(e);return{name:n.name,fn:n.fn,options:[e,t]}},Um=(e,t)=>{const n=_m(e);return{name:n.name,fn:n.fn,options:[e,t]}},Wm=(e,t)=>{const n=Pm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Km=(e,t)=>{const n=Nm(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Vm="Arrow",Od=p.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...i}=e;return s.jsx(Te.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"})})});Od.displayName=Vm;var Hm=Od;function Gm(e){const[t,n]=p.useState(void 0);return bn(()=>{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 a,c;if("borderBoxSize"in i){const l=i.borderBoxSize,u=Array.isArray(l)?l[0]:l;a=u.inlineSize,c=u.blockSize}else a=e.offsetWidth,c=e.offsetHeight;n({width:a,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var ia="Popper",[_d,Mr]=kn(ia),[Qm,Pd]=_d(ia),Id=e=>{const{__scopePopper:t,children:n}=e,[r,o]=p.useState(null);return s.jsx(Qm,{scope:t,anchor:r,onAnchorChange:o,children:n})};Id.displayName=ia;var Dd="PopperAnchor",$d=p.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Pd(Dd,n),a=p.useRef(null),c=Oe(t,a),l=p.useRef(null);return p.useEffect(()=>{const u=l.current;l.current=(r==null?void 0:r.current)||a.current,u!==l.current&&i.onAnchorChange(l.current)}),r?null:s.jsx(Te.div,{...o,ref:c})});$d.displayName=Dd;var aa="PopperContent",[Jm,Ym]=_d(aa),Md=p.forwardRef((e,t)=>{var ce,ke,xe,De,We,Be;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:i="center",alignOffset:a=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:h=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:S,...v}=e,b=Pd(aa,n),[w,j]=p.useState(null),C=Oe(t,Ee=>j(Ee)),[x,E]=p.useState(null),P=Gm(x),A=(P==null?void 0:P.width)??0,g=(P==null?void 0:P.height)??0,I=r+(i!=="center"?"-"+i:""),T=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},O=Array.isArray(u)?u:[u],_=O.length>0,M={padding:T,boundary:O.filter(Zm),altBoundary:_},{refs:q,floatingStyles:G,placement:J,isPositioned:H,middlewareData:L}=Lm({strategy:"fixed",placement:I,whileElementsMounted:(...Ee)=>Tm(...Ee,{animationFrame:m==="always"}),elements:{reference:b.anchor},middleware:[Bm({mainAxis:o+g,alignmentAxis:a}),l&&Fm({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?zm():void 0,...M}),l&&qm({...M}),Um({...M,apply:({elements:Ee,rects:ge,availableWidth:Je,availableHeight:tt})=>{const{width:Fe,height:Ke}=ge.reference,bt=Ee.floating.style;bt.setProperty("--radix-popper-available-width",`${Je}px`),bt.setProperty("--radix-popper-available-height",`${tt}px`),bt.setProperty("--radix-popper-anchor-width",`${Fe}px`),bt.setProperty("--radix-popper-anchor-height",`${Ke}px`)}}),x&&Km({element:x,padding:c}),eg({arrowWidth:A,arrowHeight:g}),f&&Wm({strategy:"referenceHidden",...M})]}),[$,X]=Bd(J),W=yn(S);bn(()=>{H&&(W==null||W())},[H,W]);const te=(ce=L.arrow)==null?void 0:ce.x,F=(ke=L.arrow)==null?void 0:ke.y,K=((xe=L.arrow)==null?void 0:xe.centerOffset)!==0,[oe,ee]=p.useState();return bn(()=>{w&&ee(window.getComputedStyle(w).zIndex)},[w]),s.jsx("div",{ref:q.setFloating,"data-radix-popper-content-wrapper":"",style:{...G,transform:H?G.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:oe,"--radix-popper-transform-origin":[(De=L.transformOrigin)==null?void 0:De.x,(We=L.transformOrigin)==null?void 0:We.y].join(" "),...((Be=L.hide)==null?void 0:Be.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:s.jsx(Jm,{scope:n,placedSide:$,onArrowChange:E,arrowX:te,arrowY:F,shouldHideArrow:K,children:s.jsx(Te.div,{"data-side":$,"data-align":X,...v,ref:C,style:{...v.style,animation:H?void 0:"none"}})})})});Md.displayName=aa;var Ld="PopperArrow",Xm={top:"bottom",right:"left",bottom:"top",left:"right"},Nd=p.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,i=Ym(Ld,r),a=Xm[i.placedSide];return s.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]: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(Hm,{...o,ref:n,style:{...o.style,display:"block"}})})});Nd.displayName=Ld;function Zm(e){return e!==null}var eg=e=>({name:"transformOrigin",options:e,fn(t){var b,w,j;const{placement:n,rects:r,middlewareData:o}=t,a=((b=o.arrow)==null?void 0:b.centerOffset)!==0,c=a?0:e.arrowWidth,l=a?0:e.arrowHeight,[u,h]=Bd(n),d={start:"0%",center:"50%",end:"100%"}[h],f=(((w=o.arrow)==null?void 0:w.x)??0)+c/2,m=(((j=o.arrow)==null?void 0:j.y)??0)+l/2;let S="",v="";return u==="bottom"?(S=a?d:`${f}px`,v=`${-l}px`):u==="top"?(S=a?d:`${f}px`,v=`${r.floating.height+l}px`):u==="right"?(S=`${-l}px`,v=a?d:`${m}px`):u==="left"&&(S=`${r.floating.width+l}px`,v=a?d:`${m}px`),{data:{x:S,y:v}}}});function Bd(e){const[t,n="center"]=e.split("-");return[t,n]}var tg=Id,ks=$d,ca=Md,la=Nd,ng="Portal",ko=p.forwardRef((e,t)=>{var c;const{container:n,...r}=e,[o,i]=p.useState(!1);bn(()=>i(!0),[]);const a=n||o&&((c=globalThis==null?void 0:globalThis.document)==null?void 0:c.body);return a?jh.createPortal(s.jsx(Te.div,{...r,ref:t}),a):null});ko.displayName=ng;function rg(e,t){return p.useReducer((n,r)=>t[n][r]??n,e)}var kt=e=>{const{present:t,children:n}=e,r=og(t),o=typeof n=="function"?n({present:r.isPresent}):p.Children.only(n),i=Oe(r.ref,sg(o));return typeof n=="function"||r.isPresent?p.cloneElement(o,{ref:i}):null};kt.displayName="Presence";function og(e){const[t,n]=p.useState(),r=p.useRef(null),o=p.useRef(e),i=p.useRef("none"),a=e?"mounted":"unmounted",[c,l]=rg(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const u=Fo(r.current);i.current=c==="mounted"?u:"none"},[c]),bn(()=>{const u=r.current,h=o.current;if(h!==e){const f=i.current,m=Fo(u);e?l("MOUNT"):m==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(h&&f!==m?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),bn(()=>{if(t){let u;const h=t.ownerDocument.defaultView??window,d=m=>{const v=Fo(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&v&&(l("ANIMATION_END"),!o.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",u=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},f=m=>{m.target===t&&(i.current=Fo(r.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{h.clearTimeout(u),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:p.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function Fo(e){return(e==null?void 0:e.animationName)||"none"}function sg(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 ig=td[" useInsertionEffect ".trim().toString()]||bn;function da({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,i,a]=ag({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:o;{const h=p.useRef(e!==void 0);p.useEffect(()=>{const d=h.current;d!==c&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${c?"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.`),h.current=c},[c,r])}const u=p.useCallback(h=>{var d;if(c){const f=cg(h)?h(e):h;f!==e&&((d=a.current)==null||d.call(a,f))}else i(h)},[c,e,i,a]);return[l,u]}function ag({defaultProp:e,onChange:t}){const[n,r]=p.useState(e),o=p.useRef(n),i=p.useRef(t);return ig(()=>{i.current=t},[t]),p.useEffect(()=>{var a;o.current!==n&&((a=i.current)==null||a.call(i,n),o.current=n)},[n,o]),[n,r,i]}function cg(e){return typeof e=="function"}var lg=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"}),dg="VisuallyHidden",Fd=p.forwardRef((e,t)=>s.jsx(Te.span,{...e,ref:t,style:{...lg,...e.style}}));Fd.displayName=dg;var ug=Fd,[Cs]=kn("Tooltip",[Mr]),js=Mr(),zd="TooltipProvider",pg=700,Di="tooltip.open",[fg,ua]=Cs(zd),qd=e=>{const{__scopeTooltip:t,delayDuration:n=pg,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,a=p.useRef(!0),c=p.useRef(!1),l=p.useRef(0);return p.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),s.jsx(fg,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:p.useCallback(()=>{window.clearTimeout(l.current),a.current=!1},[]),onClose:p.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>a.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:p.useCallback(u=>{c.current=u},[]),disableHoverableContent:o,children:i})};qd.displayName=zd;var co="Tooltip",[hg,Co]=Cs(co),Ud=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:a,delayDuration:c}=e,l=ua(co,e.__scopeTooltip),u=js(t),[h,d]=p.useState(null),f=to(),m=p.useRef(0),S=a??l.disableHoverableContent,v=c??l.delayDuration,b=p.useRef(!1),[w,j]=da({prop:r,defaultProp:o??!1,onChange:A=>{A?(l.onOpen(),document.dispatchEvent(new CustomEvent(Di))):l.onClose(),i==null||i(A)},caller:co}),C=p.useMemo(()=>w?b.current?"delayed-open":"instant-open":"closed",[w]),x=p.useCallback(()=>{window.clearTimeout(m.current),m.current=0,b.current=!1,j(!0)},[j]),E=p.useCallback(()=>{window.clearTimeout(m.current),m.current=0,j(!1)},[j]),P=p.useCallback(()=>{window.clearTimeout(m.current),m.current=window.setTimeout(()=>{b.current=!0,j(!0),m.current=0},v)},[v,j]);return p.useEffect(()=>()=>{m.current&&(window.clearTimeout(m.current),m.current=0)},[]),s.jsx(tg,{...u,children:s.jsx(hg,{scope:t,contentId:f,open:w,stateAttribute:C,trigger:h,onTriggerChange:d,onTriggerEnter:p.useCallback(()=>{l.isOpenDelayedRef.current?P():x()},[l.isOpenDelayedRef,P,x]),onTriggerLeave:p.useCallback(()=>{S?E():(window.clearTimeout(m.current),m.current=0)},[E,S]),onOpen:x,onClose:E,disableHoverableContent:S,children:n})})};Ud.displayName=co;var $i="TooltipTrigger",Wd=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Co($i,n),i=ua($i,n),a=js(n),c=p.useRef(null),l=Oe(t,c,o.onTriggerChange),u=p.useRef(!1),h=p.useRef(!1),d=p.useCallback(()=>u.current=!1,[]);return p.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),s.jsx(ks,{asChild:!0,...a,children:s.jsx(Te.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:l,onPointerMove:de(e.onPointerMove,f=>{f.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:de(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:de(e.onPointerDown,()=>{o.open&&o.onClose(),u.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:de(e.onFocus,()=>{u.current||o.onOpen()}),onBlur:de(e.onBlur,o.onClose),onClick:de(e.onClick,o.onClose)})})});Wd.displayName=$i;var pa="TooltipPortal",[mg,gg]=Cs(pa,{forceMount:void 0}),Kd=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,i=Co(pa,t);return s.jsx(mg,{scope:t,forceMount:n,children:s.jsx(kt,{present:n||i.open,children:s.jsx(ko,{asChild:!0,container:o,children:r})})})};Kd.displayName=pa;var _r="TooltipContent",Vd=p.forwardRef((e,t)=>{const n=gg(_r,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,a=Co(_r,e.__scopeTooltip);return s.jsx(kt,{present:r||a.open,children:a.disableHoverableContent?s.jsx(Hd,{side:o,...i,ref:t}):s.jsx(yg,{side:o,...i,ref:t})})}),yg=p.forwardRef((e,t)=>{const n=Co(_r,e.__scopeTooltip),r=ua(_r,e.__scopeTooltip),o=p.useRef(null),i=Oe(t,o),[a,c]=p.useState(null),{trigger:l,onClose:u}=n,h=o.current,{onPointerInTransitChange:d}=r,f=p.useCallback(()=>{c(null),d(!1)},[d]),m=p.useCallback((S,v)=>{const b=S.currentTarget,w={x:S.clientX,y:S.clientY},j=wg(w,b.getBoundingClientRect()),C=kg(w,j),x=Cg(v.getBoundingClientRect()),E=Eg([...C,...x]);c(E),d(!0)},[d]);return p.useEffect(()=>()=>f(),[f]),p.useEffect(()=>{if(l&&h){const S=b=>m(b,h),v=b=>m(b,l);return l.addEventListener("pointerleave",S),h.addEventListener("pointerleave",v),()=>{l.removeEventListener("pointerleave",S),h.removeEventListener("pointerleave",v)}}},[l,h,m,f]),p.useEffect(()=>{if(a){const S=v=>{const b=v.target,w={x:v.clientX,y:v.clientY},j=(l==null?void 0:l.contains(b))||(h==null?void 0:h.contains(b)),C=!jg(w,a);j?f():C&&(f(),u())};return document.addEventListener("pointermove",S),()=>document.removeEventListener("pointermove",S)}},[l,h,a,u,f]),s.jsx(Hd,{...e,ref:i})}),[bg,xg]=Cs(co,{isInside:!1}),vg=Th("TooltipContent"),Hd=p.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:a,...c}=e,l=Co(_r,n),u=js(n),{onClose:h}=l;return p.useEffect(()=>(document.addEventListener(Di,h),()=>document.removeEventListener(Di,h)),[h]),p.useEffect(()=>{if(l.trigger){const d=f=>{const m=f.target;m!=null&&m.contains(l.trigger)&&h()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,h]),s.jsx(So,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:h,children:s.jsxs(ca,{"data-state":l.stateAttribute,...u,...c,ref:t,style:{...c.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(vg,{children:r}),s.jsx(bg,{scope:n,isInside:!0,children:s.jsx(ug,{id:l.contentId,role:"tooltip",children:o||r})})]})})});Vd.displayName=_r;var Gd="TooltipArrow",Sg=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=js(n);return xg(Gd,n).isInside?null:s.jsx(la,{...o,...r,ref:t})});Sg.displayName=Gd;function wg(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 kg(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 Cg(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 jg(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const c=t[i],l=t[a],u=c.x,h=c.y,d=l.x,f=l.y;h>r!=f>r&&n<(d-u)*(r-h)/(f-h)+u&&(o=!o)}return o}function Eg(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),Tg(t)}function Tg(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],a=t[t.length-2];if((i.x-a.x)*(o.y-a.y)>=(i.y-a.y)*(o.x-a.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],a=n[n.length-2];if((i.x-a.x)*(o.y-a.y)>=(i.y-a.y)*(o.x-a.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 Ag=qd,Rg=Ud,Og=Wd,_g=Kd,Pg=Vd;function Qd({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:i=200,container:a}){return s.jsxs(Rg,{delayDuration:i,children:[s.jsx(Og,{asChild:!0,children:t}),s.jsx(_g,{container:a,children:s.jsx(Pg,{side:n,align:r,sideOffset:o,style:{background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.sm,padding:`${be[1]} ${be[2]}`,fontSize:Ze.sm,boxShadow:pe("shadowMd"),zIndex:io.tooltip,userSelect:"none"},children:e})})]})}const Ig=Ag;var qs="focusScope.autoFocusOnMount",Us="focusScope.autoFocusOnUnmount",Rc={bubbles:!1,cancelable:!0},Dg="FocusScope",Es=p.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...a}=e,[c,l]=p.useState(null),u=yn(o),h=yn(i),d=p.useRef(null),f=Oe(t,v=>l(v)),m=p.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;p.useEffect(()=>{if(r){let v=function(C){if(m.paused||!c)return;const x=C.target;c.contains(x)?d.current=x:sn(d.current,{select:!0})},b=function(C){if(m.paused||!c)return;const x=C.relatedTarget;x!==null&&(c.contains(x)||sn(d.current,{select:!0}))},w=function(C){if(document.activeElement===document.body)for(const E of C)E.removedNodes.length>0&&sn(c)};document.addEventListener("focusin",v),document.addEventListener("focusout",b);const j=new MutationObserver(w);return c&&j.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",v),document.removeEventListener("focusout",b),j.disconnect()}}},[r,c,m.paused]),p.useEffect(()=>{if(c){_c.add(m);const v=document.activeElement;if(!c.contains(v)){const w=new CustomEvent(qs,Rc);c.addEventListener(qs,u),c.dispatchEvent(w),w.defaultPrevented||($g(Fg(Jd(c)),{select:!0}),document.activeElement===v&&sn(c))}return()=>{c.removeEventListener(qs,u),setTimeout(()=>{const w=new CustomEvent(Us,Rc);c.addEventListener(Us,h),c.dispatchEvent(w),w.defaultPrevented||sn(v??document.body,{select:!0}),c.removeEventListener(Us,h),_c.remove(m)},0)}}},[c,u,h,m]);const S=p.useCallback(v=>{if(!n&&!r||m.paused)return;const b=v.key==="Tab"&&!v.altKey&&!v.ctrlKey&&!v.metaKey,w=document.activeElement;if(b&&w){const j=v.currentTarget,[C,x]=Mg(j);C&&x?!v.shiftKey&&w===x?(v.preventDefault(),n&&sn(C,{select:!0})):v.shiftKey&&w===C&&(v.preventDefault(),n&&sn(x,{select:!0})):w===j&&v.preventDefault()}},[n,r,m.paused]);return s.jsx(Te.div,{tabIndex:-1,...a,ref:f,onKeyDown:S})});Es.displayName=Dg;function $g(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(sn(r,{select:t}),document.activeElement!==n)return}function Mg(e){const t=Jd(e),n=Oc(t,e),r=Oc(t.reverse(),e);return[n,r]}function Jd(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 Oc(e,t){for(const n of e)if(!Lg(n,{upTo:t}))return n}function Lg(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 Ng(e){return e instanceof HTMLInputElement&&"select"in e}function sn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Ng(e)&&t&&e.select()}}var _c=Bg();function Bg(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Pc(e,t),e.unshift(t)},remove(t){var n;e=Pc(e,t),(n=e[0])==null||n.resume()}}}function Pc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function Fg(e){return e.filter(t=>t.tagName!=="A")}var Ws=0;function fa(){p.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Ic()),document.body.insertAdjacentElement("beforeend",e[1]??Ic()),Ws++,()=>{Ws===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ws--}},[])}function Ic(){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 zt=function(){return zt=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},zt.apply(this,arguments)};function Yd(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 zg(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 Zo="right-scroll-bar-position",es="width-before-scroll-bar",qg="with-scroll-bars-hidden",Ug="--removed-body-scroll-bar-size";function Ks(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Wg(e,t){var n=p.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 Kg=typeof window<"u"?p.useLayoutEffect:p.useEffect,Dc=new WeakMap;function Vg(e,t){var n=Wg(null,function(r){return e.forEach(function(o){return Ks(o,r)})});return Kg(function(){var r=Dc.get(n);if(r){var o=new Set(r),i=new Set(e),a=n.current;o.forEach(function(c){i.has(c)||Ks(c,null)}),i.forEach(function(c){o.has(c)||Ks(c,a)})}Dc.set(n,e)},[e]),n}function Hg(e){return e}function Gg(e,t){t===void 0&&(t=Hg);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 a=t(i,r);return n.push(a),function(){n=n.filter(function(c){return c!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(c){return i(c)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var c=n;n=[],c.forEach(i),a=n}var l=function(){var h=a;a=[],h.forEach(i)},u=function(){return Promise.resolve().then(l)};u(),n={push:function(h){a.push(h),u()},filter:function(h){return a=a.filter(h),n}}}};return o}function Qg(e){e===void 0&&(e={});var t=Gg(null);return t.options=zt({async:!0,ssr:!1},e),t}var Xd=function(e){var t=e.sideCar,n=Yd(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 p.createElement(r,zt({},n))};Xd.isSideCarExport=!0;function Jg(e,t){return e.useMedium(t),Xd}var Zd=Qg(),Vs=function(){},Ts=p.forwardRef(function(e,t){var n=p.useRef(null),r=p.useState({onScrollCapture:Vs,onWheelCapture:Vs,onTouchMoveCapture:Vs}),o=r[0],i=r[1],a=e.forwardProps,c=e.children,l=e.className,u=e.removeScrollBar,h=e.enabled,d=e.shards,f=e.sideCar,m=e.noRelative,S=e.noIsolation,v=e.inert,b=e.allowPinchZoom,w=e.as,j=w===void 0?"div":w,C=e.gapMode,x=Yd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),E=f,P=Vg([n,t]),A=zt(zt({},x),o);return p.createElement(p.Fragment,null,h&&p.createElement(E,{sideCar:Zd,removeScrollBar:u,shards:d,noRelative:m,noIsolation:S,inert:v,setCallbacks:i,allowPinchZoom:!!b,lockRef:n,gapMode:C}),a?p.cloneElement(p.Children.only(c),zt(zt({},A),{ref:P})):p.createElement(j,zt({},A,{className:l,ref:P}),c))});Ts.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Ts.classNames={fullWidth:es,zeroRight:Zo};var Yg=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Xg(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Yg();return t&&e.setAttribute("nonce",t),e}function Zg(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function ey(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var ty=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Xg())&&(Zg(t,n),ey(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},ny=function(){var e=ty();return function(t,n){p.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},eu=function(){var e=ny(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},ry={left:0,top:0,right:0,gap:0},Hs=function(e){return parseInt(e||"",10)||0},oy=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[Hs(n),Hs(r),Hs(o)]},sy=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return ry;var t=oy(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])}},iy=eu(),fr="data-scroll-locked",ay=function(e,t,n,r){var o=e.left,i=e.top,a=e.right,c=e.gap;return n===void 0&&(n="margin"),`
11
- .`.concat(qg,` {
10
+ */var tc;function If(){if(tc)return Fr;tc=1;var e=Zl(),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 a(c,l,u){var h,d={},f=null,m=null;u!==void 0&&(f=""+u),l.key!==void 0&&(f=""+l.key),l.ref!==void 0&&(m=l.ref);for(h in l)r.call(l,h)&&!i.hasOwnProperty(h)&&(d[h]=l[h]);if(c&&c.defaultProps)for(h in l=c.defaultProps,l)d[h]===void 0&&(d[h]=l[h]);return{$$typeof:t,type:c,key:f,ref:m,props:d,_owner:o.current}}return Fr.Fragment=n,Fr.jsx=a,Fr.jsxs=a,Fr}var nc;function Df(){return nc||(nc=1,Ls.exports=If()),Ls.exports}var s=Df(),Mo={},rc;function $f(){if(rc)return Mo;rc=1;var e=ed();return Mo.createRoot=e.createRoot,Mo.hydrateRoot=e.hydrateRoot,Mo}var Mf=$f(),p=Zl();const qe=td(p),nd=Pf({__proto__:null,default:qe},[p]);var vo=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Dn,cn,mr,Ul,Lf=(Ul=class extends vo{constructor(){super();le(this,Dn);le(this,cn);le(this,mr);Z(this,mr,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){R(this,cn)||this.setEventListener(R(this,mr))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,cn))==null||t.call(this),Z(this,cn,void 0))}setEventListener(t){var n;Z(this,mr,t),(n=R(this,cn))==null||n.call(this),Z(this,cn,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){R(this,Dn)!==t&&(Z(this,Dn,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof R(this,Dn)=="boolean"?R(this,Dn):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Dn=new WeakMap,cn=new WeakMap,mr=new WeakMap,Ul),Hi=new Lf,Nf={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ln,Vi,Wl,Bf=(Wl=class{constructor(){le(this,ln,Nf);le(this,Vi,!1)}setTimeoutProvider(e){Z(this,ln,e)}setTimeout(e,t){return R(this,ln).setTimeout(e,t)}clearTimeout(e){R(this,ln).clearTimeout(e)}setInterval(e,t){return R(this,ln).setInterval(e,t)}clearInterval(e){R(this,ln).clearInterval(e)}},ln=new WeakMap,Vi=new WeakMap,Wl),Pn=new Bf;function Ff(e){setTimeout(e,0)}var zf=typeof window>"u"||"Deno"in globalThis;function at(){}function qf(e,t){return typeof e=="function"?e(t):e}function mi(e){return typeof e=="number"&&e>=0&&e!==1/0}function rd(e,t){return Math.max(e+(t||0)-Date.now(),0)}function gn(e,t){return typeof e=="function"?e(t):e}function ht(e,t){return typeof e=="function"?e(t):e}function oc(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==Gi(a,t.options))return!1}else if(!Ar(t.queryKey,a))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||i&&!i(t))}function sc(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(oo(t.options.mutationKey)!==oo(i))return!1}else if(!Ar(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gi(e,t){return((t==null?void 0:t.queryKeyHashFn)||oo)(e)}function oo(e){return JSON.stringify(e,(t,n)=>yi(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Ar(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t)){for(let r=0;r<t.length;r++)if(!Ar(e[r],t[r]))return!1;return!0}const n=Object.keys(t);for(const r of n)if(!Ar(e[r],t[r]))return!1;return!0}return!1}var Uf=Object.prototype.hasOwnProperty;function od(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=ic(e)&&ic(t);if(!r&&!(yi(e)&&yi(t)))return t;const i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),c=a.length,l=r?new Array(c):{};let u=0;for(let h=0;h<c;h++){const d=r?h:a[h],f=e[d],m=t[d];if(f===m){l[d]=f,(r?h<i:Uf.call(e,d))&&u++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){l[d]=m;continue}const S=od(f,m,n+1);l[d]=S,S===f&&u++}return i===c&&u===i?e:l}function gi(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function ic(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function yi(e){if(!ac(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!ac(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ac(e){return Object.prototype.toString.call(e)==="[object Object]"}function Wf(e){return new Promise(t=>{Pn.setTimeout(t,e)})}function bi(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?od(e,t):t}function Kf(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Vf(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Qi=Symbol();function sd(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===Qi?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function id(e,t){return typeof e=="function"?e(...t):!!e}function Hf(e,t,n){let r=!1,o;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(o??(o=t()),r||(r=!0,o.aborted?n():o.addEventListener("abort",n,{once:!0})),o)}),e}var so=(()=>{let e=()=>zf;return{isServer(){return e()},setIsServer(t){e=t}}})();function xi(){let e,t;const n=new Promise((o,i)=>{e=o,t=i});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}var Gf=Ff;function Qf(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=Gf;const i=c=>{t?e.push(c):o(()=>{n(c)})},a=()=>{const c=e;e=[],c.length&&o(()=>{r(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||a()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{o=c}}}var Ue=Qf(),gr,dn,yr,Kl,Jf=(Kl=class extends vo{constructor(){super();le(this,gr,!0);le(this,dn);le(this,yr);Z(this,yr,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){R(this,dn)||this.setEventListener(R(this,yr))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,dn))==null||t.call(this),Z(this,dn,void 0))}setEventListener(t){var n;Z(this,yr,t),(n=R(this,dn))==null||n.call(this),Z(this,dn,t(this.setOnline.bind(this)))}setOnline(t){R(this,gr)!==t&&(Z(this,gr,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return R(this,gr)}},gr=new WeakMap,dn=new WeakMap,yr=new WeakMap,Kl),os=new Jf;function Yf(e){return Math.min(1e3*2**e,3e4)}function ad(e){return(e??"online")==="online"?os.isOnline():!0}var vi=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function cd(e){let t=!1,n=0,r;const o=xi(),i=()=>o.status!=="pending",a=v=>{var b;if(!i()){const w=new vi(v);f(w),(b=e.onCancel)==null||b.call(e,w)}},c=()=>{t=!0},l=()=>{t=!1},u=()=>Hi.isFocused()&&(e.networkMode==="always"||os.isOnline())&&e.canRun(),h=()=>ad(e.networkMode)&&e.canRun(),d=v=>{i()||(r==null||r(),o.resolve(v))},f=v=>{i()||(r==null||r(),o.reject(v))},m=()=>new Promise(v=>{var b;r=w=>{(i()||u())&&v(w)},(b=e.onPause)==null||b.call(e)}).then(()=>{var v;r=void 0,i()||(v=e.onContinue)==null||v.call(e)}),S=()=>{if(i())return;let v;const b=n===0?e.initialPromise:void 0;try{v=b??e.fn()}catch(w){v=Promise.reject(w)}Promise.resolve(v).then(d).catch(w=>{var P;if(i())return;const j=e.retry??(so.isServer()?0:3),C=e.retryDelay??Yf,x=typeof C=="function"?C(n,w):C,E=j===!0||typeof j=="number"&&n<j||typeof j=="function"&&j(n,w);if(t||!E){f(w);return}n++,(P=e.onFail)==null||P.call(e,n,w),Wf(x).then(()=>u()?void 0:m()).then(()=>{t?f(w):S()})})};return{promise:o,status:()=>o.status,cancel:a,continue:()=>(r==null||r(),o),cancelRetry:c,continueRetry:l,canStart:h,start:()=>(h()?S():m().then(S),o)}}var $n,Vl,ld=(Vl=class{constructor(){le(this,$n)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),mi(this.gcTime)&&Z(this,$n,Pn.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(so.isServer()?1/0:300*1e3))}clearGcTimeout(){R(this,$n)!==void 0&&(Pn.clearTimeout(R(this,$n)),Z(this,$n,void 0))}},$n=new WeakMap,Vl);function Xf(e){return{onFetch:(t,n)=>{var h,d,f,m,S;const r=t.options,o=(f=(d=(h=t.fetchOptions)==null?void 0:h.meta)==null?void 0:d.fetchMore)==null?void 0:f.direction,i=((m=t.state.data)==null?void 0:m.pages)||[],a=((S=t.state.data)==null?void 0:S.pageParams)||[];let c={pages:[],pageParams:[]},l=0;const u=async()=>{let v=!1;const b=C=>{Hf(C,()=>t.signal,()=>v=!0)},w=sd(t.options,t.fetchOptions),j=async(C,x,E)=>{if(v)return Promise.reject(t.signal.reason);if(x==null&&C.pages.length)return Promise.resolve(C);const A=(()=>{const O={client:t.client,queryKey:t.queryKey,pageParam:x,direction:E?"backward":"forward",meta:t.options.meta};return b(O),O})(),g=await w(A),{maxPages:I}=t.options,T=E?Vf:Kf;return{pages:T(C.pages,g,I),pageParams:T(C.pageParams,x,I)}};if(o&&i.length){const C=o==="backward",x=C?Zf:cc,E={pages:i,pageParams:a},P=x(r,E);c=await j(E,P,C)}else{const C=e??i.length;do{const x=l===0?a[0]??r.initialPageParam:cc(r,c);if(l>0&&x==null)break;c=await j(c,x),l++}while(l<C)}return c};t.options.persister?t.fetchFn=()=>{var v,b;return(b=(v=t.options).persister)==null?void 0:b.call(v,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function cc(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Zf(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var br,Mn,xr,xt,Ln,Le,mo,Nn,ft,dd,Gt,Hl,eh=(Hl=class extends ld{constructor(t){super();le(this,ft);le(this,br);le(this,Mn);le(this,xr);le(this,xt);le(this,Ln);le(this,Le);le(this,mo);le(this,Nn);Z(this,Nn,!1),Z(this,mo,t.defaultOptions),this.setOptions(t.options),this.observers=[],Z(this,Ln,t.client),Z(this,xt,R(this,Ln).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Z(this,Mn,dc(this.options)),this.state=t.state??R(this,Mn),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return R(this,br)}get promise(){var t;return(t=R(this,Le))==null?void 0:t.promise}setOptions(t){if(this.options={...R(this,mo),...t},t!=null&&t._type&&Z(this,br,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=dc(this.options);n.data!==void 0&&(this.setState(lc(n.data,n.dataUpdatedAt)),Z(this,Mn,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&R(this,xt).remove(this)}setData(t,n){const r=bi(this.state.data,t,this.options);return fe(this,ft,Gt).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){fe(this,ft,Gt).call(this,{type:"setState",state:t})}cancel(t){var r,o;const n=(r=R(this,Le))==null?void 0:r.promise;return(o=R(this,Le))==null||o.cancel(t),n?n.then(at).catch(at):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return R(this,Mn)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ht(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Qi||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>gn(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!rd(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,Le))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=R(this,Le))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),R(this,xt).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(R(this,Le)&&(R(this,Nn)||fe(this,ft,dd).call(this)?R(this,Le).cancel({revert:!0}):R(this,Le).cancelRetry()),this.scheduleGc()),R(this,xt).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||fe(this,ft,Gt).call(this,{type:"invalidate"})}async fetch(t,n){var u,h,d,f,m,S,v,b,w,j,C;if(this.state.fetchStatus!=="idle"&&((u=R(this,Le))==null?void 0:u.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(R(this,Le))return R(this,Le).continueRetry(),R(this,Le).promise}if(t&&this.setOptions(t),!this.options.queryFn){const x=this.observers.find(E=>E.options.queryFn);x&&this.setOptions(x.options)}const r=new AbortController,o=x=>{Object.defineProperty(x,"signal",{enumerable:!0,get:()=>(Z(this,Nn,!0),r.signal)})},i=()=>{const x=sd(this.options,n),P=(()=>{const A={client:R(this,Ln),queryKey:this.queryKey,meta:this.meta};return o(A),A})();return Z(this,Nn,!1),this.options.persister?this.options.persister(x,P,this):x(P)},c=(()=>{const x={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:R(this,Ln),state:this.state,fetchFn:i};return o(x),x})(),l=R(this,br)==="infinite"?Xf(this.options.pages):this.options.behavior;l==null||l.onFetch(c,this),Z(this,xr,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=c.fetchOptions)==null?void 0:h.meta))&&fe(this,ft,Gt).call(this,{type:"fetch",meta:(d=c.fetchOptions)==null?void 0:d.meta}),Z(this,Le,cd({initialPromise:n==null?void 0:n.initialPromise,fn:c.fetchFn,onCancel:x=>{x instanceof vi&&x.revert&&this.setState({...R(this,xr),fetchStatus:"idle"}),r.abort()},onFail:(x,E)=>{fe(this,ft,Gt).call(this,{type:"failed",failureCount:x,error:E})},onPause:()=>{fe(this,ft,Gt).call(this,{type:"pause"})},onContinue:()=>{fe(this,ft,Gt).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{const x=await R(this,Le).start();if(x===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(x),(m=(f=R(this,xt).config).onSuccess)==null||m.call(f,x,this),(v=(S=R(this,xt).config).onSettled)==null||v.call(S,x,this.state.error,this),x}catch(x){if(x instanceof vi){if(x.silent)return R(this,Le).promise;if(x.revert){if(this.state.data===void 0)throw x;return this.state.data}}throw fe(this,ft,Gt).call(this,{type:"error",error:x}),(w=(b=R(this,xt).config).onError)==null||w.call(b,x,this),(C=(j=R(this,xt).config).onSettled)==null||C.call(j,this.state.data,x,this),x}finally{this.scheduleGc()}}},br=new WeakMap,Mn=new WeakMap,xr=new WeakMap,xt=new WeakMap,Ln=new WeakMap,Le=new WeakMap,mo=new WeakMap,Nn=new WeakMap,ft=new WeakSet,dd=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Gt=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...ud(r.data,this.options),fetchMeta:t.meta??null};case"success":const o={...r,...lc(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Z(this,xr,t.manual?o:void 0),o;case"error":const i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Ue.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),R(this,xt).notify({query:this,type:"updated",action:t})})},Hl);function ud(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ad(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function lc(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function dc(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var it,he,go,Xe,Bn,vr,Qt,un,yo,Sr,wr,Fn,zn,pn,kr,Se,Hr,Si,wi,ki,Ci,ji,Ei,Ti,pd,Gl,th=(Gl=class extends vo{constructor(t,n){super();le(this,Se);le(this,it);le(this,he);le(this,go);le(this,Xe);le(this,Bn);le(this,vr);le(this,Qt);le(this,un);le(this,yo);le(this,Sr);le(this,wr);le(this,Fn);le(this,zn);le(this,pn);le(this,kr,new Set);this.options=n,Z(this,it,t),Z(this,un,null),Z(this,Qt,xi()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(R(this,he).addObserver(this),uc(R(this,he),this.options)?fe(this,Se,Hr).call(this):this.updateResult(),fe(this,Se,Ci).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ai(R(this,he),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ai(R(this,he),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,fe(this,Se,ji).call(this),fe(this,Se,Ei).call(this),R(this,he).removeObserver(this)}setOptions(t){const n=this.options,r=R(this,he);if(this.options=R(this,it).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ht(this.options.enabled,R(this,he))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");fe(this,Se,Ti).call(this),R(this,he).setOptions(this.options),n._defaulted&&!gi(this.options,n)&&R(this,it).getQueryCache().notify({type:"observerOptionsUpdated",query:R(this,he),observer:this});const o=this.hasListeners();o&&pc(R(this,he),r,this.options,n)&&fe(this,Se,Hr).call(this),this.updateResult(),o&&(R(this,he)!==r||ht(this.options.enabled,R(this,he))!==ht(n.enabled,R(this,he))||gn(this.options.staleTime,R(this,he))!==gn(n.staleTime,R(this,he)))&&fe(this,Se,Si).call(this);const i=fe(this,Se,wi).call(this);o&&(R(this,he)!==r||ht(this.options.enabled,R(this,he))!==ht(n.enabled,R(this,he))||i!==R(this,pn))&&fe(this,Se,ki).call(this,i)}getOptimisticResult(t){const n=R(this,it).getQueryCache().build(R(this,it),t),r=this.createResult(n,t);return rh(this,r)&&(Z(this,Xe,r),Z(this,vr,this.options),Z(this,Bn,R(this,he).state)),r}getCurrentResult(){return R(this,Xe)}trackResult(t,n){return new Proxy(t,{get:(r,o)=>(this.trackProp(o),n==null||n(o),o==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&R(this,Qt).status==="pending"&&R(this,Qt).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,o))})}trackProp(t){R(this,kr).add(t)}getCurrentQuery(){return R(this,he)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=R(this,it).defaultQueryOptions(t),r=R(this,it).getQueryCache().build(R(this,it),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return fe(this,Se,Hr).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),R(this,Xe)))}createResult(t,n){var I;const r=R(this,he),o=this.options,i=R(this,Xe),a=R(this,Bn),c=R(this,vr),u=t!==r?t.state:R(this,go),{state:h}=t;let d={...h},f=!1,m;if(n._optimisticResults){const T=this.hasListeners(),O=!T&&uc(t,n),_=T&&pc(t,r,n,o);(O||_)&&(d={...d,...ud(h.data,t.options)}),n._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:S,errorUpdatedAt:v,status:b}=d;m=d.data;let w=!1;if(n.placeholderData!==void 0&&m===void 0&&b==="pending"){let T;i!=null&&i.isPlaceholderData&&n.placeholderData===(c==null?void 0:c.placeholderData)?(T=i.data,w=!0):T=typeof n.placeholderData=="function"?n.placeholderData((I=R(this,wr))==null?void 0:I.state.data,R(this,wr)):n.placeholderData,T!==void 0&&(b="success",m=bi(i==null?void 0:i.data,T,n),f=!0)}if(n.select&&m!==void 0&&!w)if(i&&m===(a==null?void 0:a.data)&&n.select===R(this,yo))m=R(this,Sr);else try{Z(this,yo,n.select),m=n.select(m),m=bi(i==null?void 0:i.data,m,n),Z(this,Sr,m),Z(this,un,null)}catch(T){Z(this,un,T)}R(this,un)&&(S=R(this,un),m=R(this,Sr),v=Date.now(),b="error");const j=d.fetchStatus==="fetching",C=b==="pending",x=b==="error",E=C&&j,P=m!==void 0,g={status:b,fetchStatus:d.fetchStatus,isPending:C,isSuccess:b==="success",isError:x,isInitialLoading:E,isLoading:E,data:m,dataUpdatedAt:d.dataUpdatedAt,error:S,errorUpdatedAt:v,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:j,isRefetching:j&&!C,isLoadingError:x&&!P,isPaused:d.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:x&&P,isStale:Ji(t,n),refetch:this.refetch,promise:R(this,Qt),isEnabled:ht(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const T=g.data!==void 0,O=g.status==="error"&&!T,_=G=>{O?G.reject(g.error):T&&G.resolve(g.data)},M=()=>{const G=Z(this,Qt,g.promise=xi());_(G)},q=R(this,Qt);switch(q.status){case"pending":t.queryHash===r.queryHash&&_(q);break;case"fulfilled":(O||g.data!==q.value)&&M();break;case"rejected":(!O||g.error!==q.reason)&&M();break}}return g}updateResult(){const t=R(this,Xe),n=this.createResult(R(this,he),this.options);if(Z(this,Bn,R(this,he).state),Z(this,vr,this.options),R(this,Bn).data!==void 0&&Z(this,wr,R(this,he)),gi(n,t))return;Z(this,Xe,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:o}=this.options,i=typeof o=="function"?o():o;if(i==="all"||!i&&!R(this,kr).size)return!0;const a=new Set(i??R(this,kr));return this.options.throwOnError&&a.add("error"),Object.keys(R(this,Xe)).some(c=>{const l=c;return R(this,Xe)[l]!==t[l]&&a.has(l)})};fe(this,Se,pd).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&fe(this,Se,Ci).call(this)}},it=new WeakMap,he=new WeakMap,go=new WeakMap,Xe=new WeakMap,Bn=new WeakMap,vr=new WeakMap,Qt=new WeakMap,un=new WeakMap,yo=new WeakMap,Sr=new WeakMap,wr=new WeakMap,Fn=new WeakMap,zn=new WeakMap,pn=new WeakMap,kr=new WeakMap,Se=new WeakSet,Hr=function(t){fe(this,Se,Ti).call(this);let n=R(this,he).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(at)),n},Si=function(){fe(this,Se,ji).call(this);const t=gn(this.options.staleTime,R(this,he));if(so.isServer()||R(this,Xe).isStale||!mi(t))return;const r=rd(R(this,Xe).dataUpdatedAt,t)+1;Z(this,Fn,Pn.setTimeout(()=>{R(this,Xe).isStale||this.updateResult()},r))},wi=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(R(this,he)):this.options.refetchInterval)??!1},ki=function(t){fe(this,Se,Ei).call(this),Z(this,pn,t),!(so.isServer()||ht(this.options.enabled,R(this,he))===!1||!mi(R(this,pn))||R(this,pn)===0)&&Z(this,zn,Pn.setInterval(()=>{(this.options.refetchIntervalInBackground||Hi.isFocused())&&fe(this,Se,Hr).call(this)},R(this,pn)))},Ci=function(){fe(this,Se,Si).call(this),fe(this,Se,ki).call(this,fe(this,Se,wi).call(this))},ji=function(){R(this,Fn)!==void 0&&(Pn.clearTimeout(R(this,Fn)),Z(this,Fn,void 0))},Ei=function(){R(this,zn)!==void 0&&(Pn.clearInterval(R(this,zn)),Z(this,zn,void 0))},Ti=function(){const t=R(this,it).getQueryCache().build(R(this,it),this.options);if(t===R(this,he))return;const n=R(this,he);Z(this,he,t),Z(this,go,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},pd=function(t){Ue.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(R(this,Xe))}),R(this,it).getQueryCache().notify({query:R(this,he),type:"observerResultsUpdated"})})},Gl);function nh(e,t){return ht(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&ht(t.retryOnMount,e)===!1)}function uc(e,t){return nh(e,t)||e.state.data!==void 0&&Ai(e,t,t.refetchOnMount)}function Ai(e,t,n){if(ht(t.enabled,e)!==!1&&gn(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ji(e,t)}return!1}function pc(e,t,n,r){return(e!==t||ht(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ji(e,n)}function Ji(e,t){return ht(t.enabled,e)!==!1&&e.isStaleByTime(gn(t.staleTime,e))}function rh(e,t){return!gi(e.getCurrentResult(),t)}var bo,Lt,He,qn,Nt,on,Ql,oh=(Ql=class extends ld{constructor(t){super();le(this,Nt);le(this,bo);le(this,Lt);le(this,He);le(this,qn);Z(this,bo,t.client),this.mutationId=t.mutationId,Z(this,He,t.mutationCache),Z(this,Lt,[]),this.state=t.state||sh(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){R(this,Lt).includes(t)||(R(this,Lt).push(t),this.clearGcTimeout(),R(this,He).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Z(this,Lt,R(this,Lt).filter(n=>n!==t)),this.scheduleGc(),R(this,He).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){R(this,Lt).length||(this.state.status==="pending"?this.scheduleGc():R(this,He).remove(this))}continue(){var t;return((t=R(this,qn))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P,A;const n=()=>{fe(this,Nt,on).call(this,{type:"continue"})},r={client:R(this,bo),meta:this.options.meta,mutationKey:this.options.mutationKey};Z(this,qn,cd({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(g,I)=>{fe(this,Nt,on).call(this,{type:"failed",failureCount:g,error:I})},onPause:()=>{fe(this,Nt,on).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>R(this,He).canRun(this)}));const o=this.state.status==="pending",i=!R(this,qn).canStart();try{if(o)n();else{fe(this,Nt,on).call(this,{type:"pending",variables:t,isPaused:i}),R(this,He).config.onMutate&&await R(this,He).config.onMutate(t,this,r);const I=await((c=(a=this.options).onMutate)==null?void 0:c.call(a,t,r));I!==this.state.context&&fe(this,Nt,on).call(this,{type:"pending",context:I,variables:t,isPaused:i})}const g=await R(this,qn).start();return await((u=(l=R(this,He).config).onSuccess)==null?void 0:u.call(l,g,t,this.state.context,this,r)),await((d=(h=this.options).onSuccess)==null?void 0:d.call(h,g,t,this.state.context,r)),await((m=(f=R(this,He).config).onSettled)==null?void 0:m.call(f,g,null,this.state.variables,this.state.context,this,r)),await((v=(S=this.options).onSettled)==null?void 0:v.call(S,g,null,t,this.state.context,r)),fe(this,Nt,on).call(this,{type:"success",data:g}),g}catch(g){try{await((w=(b=R(this,He).config).onError)==null?void 0:w.call(b,g,t,this.state.context,this,r))}catch(I){Promise.reject(I)}try{await((C=(j=this.options).onError)==null?void 0:C.call(j,g,t,this.state.context,r))}catch(I){Promise.reject(I)}try{await((E=(x=R(this,He).config).onSettled)==null?void 0:E.call(x,void 0,g,this.state.variables,this.state.context,this,r))}catch(I){Promise.reject(I)}try{await((A=(P=this.options).onSettled)==null?void 0:A.call(P,void 0,g,t,this.state.context,r))}catch(I){Promise.reject(I)}throw fe(this,Nt,on).call(this,{type:"error",error:g}),g}finally{R(this,He).runNext(this)}}},bo=new WeakMap,Lt=new WeakMap,He=new WeakMap,qn=new WeakMap,Nt=new WeakSet,on=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Ue.batch(()=>{R(this,Lt).forEach(r=>{r.onMutationUpdate(t)}),R(this,He).notify({mutation:this,type:"updated",action:t})})},Ql);function sh(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Jt,Ot,xo,Jl,ih=(Jl=class extends vo{constructor(t={}){super();le(this,Jt);le(this,Ot);le(this,xo);this.config=t,Z(this,Jt,new Set),Z(this,Ot,new Map),Z(this,xo,0)}build(t,n,r){const o=new oh({client:t,mutationCache:this,mutationId:++$o(this,xo)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){R(this,Jt).add(t);const n=Lo(t);if(typeof n=="string"){const r=R(this,Ot).get(n);r?r.push(t):R(this,Ot).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(R(this,Jt).delete(t)){const n=Lo(t);if(typeof n=="string"){const r=R(this,Ot).get(n);if(r)if(r.length>1){const o=r.indexOf(t);o!==-1&&r.splice(o,1)}else r[0]===t&&R(this,Ot).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Lo(t);if(typeof n=="string"){const r=R(this,Ot).get(n),o=r==null?void 0:r.find(i=>i.state.status==="pending");return!o||o===t}else return!0}runNext(t){var r;const n=Lo(t);if(typeof n=="string"){const o=(r=R(this,Ot).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(o==null?void 0:o.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ue.batch(()=>{R(this,Jt).forEach(t=>{this.notify({type:"removed",mutation:t})}),R(this,Jt).clear(),R(this,Ot).clear()})}getAll(){return Array.from(R(this,Jt))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>sc(n,r))}findAll(t={}){return this.getAll().filter(n=>sc(t,n))}notify(t){Ue.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Ue.batch(()=>Promise.all(t.map(n=>n.continue().catch(at))))}},Jt=new WeakMap,Ot=new WeakMap,xo=new WeakMap,Jl);function Lo(e){var t;return(t=e.options.scope)==null?void 0:t.id}var Bt,Yl,ah=(Yl=class extends vo{constructor(t={}){super();le(this,Bt);this.config=t,Z(this,Bt,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gi(o,n);let a=this.get(i);return a||(a=new eh({client:t,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(a)),a}add(t){R(this,Bt).has(t.queryHash)||(R(this,Bt).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=R(this,Bt).get(t.queryHash);n&&(t.destroy(),n===t&&R(this,Bt).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Ue.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return R(this,Bt).get(t)}getAll(){return[...R(this,Bt).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>oc(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>oc(t,r)):n}notify(t){Ue.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Ue.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Ue.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Bt=new WeakMap,Yl),Ae,fn,hn,Cr,jr,mn,Er,Tr,Xl,ch=(Xl=class{constructor(e={}){le(this,Ae);le(this,fn);le(this,hn);le(this,Cr);le(this,jr);le(this,mn);le(this,Er);le(this,Tr);Z(this,Ae,e.queryCache||new ah),Z(this,fn,e.mutationCache||new ih),Z(this,hn,e.defaultOptions||{}),Z(this,Cr,new Map),Z(this,jr,new Map),Z(this,mn,0)}mount(){$o(this,mn)._++,R(this,mn)===1&&(Z(this,Er,Hi.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ae).onFocus())})),Z(this,Tr,os.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ae).onOnline())})))}unmount(){var e,t;$o(this,mn)._--,R(this,mn)===0&&((e=R(this,Er))==null||e.call(this),Z(this,Er,void 0),(t=R(this,Tr))==null||t.call(this),Z(this,Tr,void 0))}isFetching(e){return R(this,Ae).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return R(this,fn).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ae).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=R(this,Ae).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(gn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return R(this,Ae).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),o=R(this,Ae).get(r.queryHash),i=o==null?void 0:o.state.data,a=qf(t,i);if(a!==void 0)return R(this,Ae).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Ue.batch(()=>R(this,Ae).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=R(this,Ae).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=R(this,Ae);Ue.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=R(this,Ae);return Ue.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Ue.batch(()=>R(this,Ae).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(at).catch(at)}invalidateQueries(e,t={}){return Ue.batch(()=>(R(this,Ae).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Ue.batch(()=>R(this,Ae).findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(at)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(at)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=R(this,Ae).build(this,t);return n.isStaleByTime(gn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(at).catch(at)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(at).catch(at)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return os.isOnline()?R(this,fn).resumePausedMutations():Promise.resolve()}getQueryCache(){return R(this,Ae)}getMutationCache(){return R(this,fn)}getDefaultOptions(){return R(this,hn)}setDefaultOptions(e){Z(this,hn,e)}setQueryDefaults(e,t){R(this,Cr).set(oo(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...R(this,Cr).values()],n={};return t.forEach(r=>{Ar(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){R(this,jr).set(oo(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...R(this,jr).values()],n={};return t.forEach(r=>{Ar(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...R(this,hn).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gi(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Qi&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...R(this,hn).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){R(this,Ae).clear(),R(this,fn).clear()}},Ae=new WeakMap,fn=new WeakMap,hn=new WeakMap,Cr=new WeakMap,jr=new WeakMap,mn=new WeakMap,Er=new WeakMap,Tr=new WeakMap,Xl),fd=p.createContext(void 0),Yi=e=>{const t=p.useContext(fd);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},lh=({client:e,children:t})=>(p.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),s.jsx(fd.Provider,{value:e,children:t})),hd=p.createContext(!1),dh=()=>p.useContext(hd);hd.Provider;function uh(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var ph=p.createContext(uh()),fh=()=>p.useContext(ph),hh=(e,t,n)=>{const r=n!=null&&n.state.error&&typeof e.throwOnError=="function"?id(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},mh=e=>{p.useEffect(()=>{e.clearReset()},[e])},gh=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||id(n,[e.error,r])),yh=e=>{if(e.suspense){const n=o=>o==="static"?o:Math.max(o??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...o)=>n(r(...o)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},bh=(e,t)=>e.isLoading&&e.isFetching&&!t,xh=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,fc=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function vh(e,t,n){var m,S,v,b;const r=dh(),o=fh(),i=Yi(),a=i.defaultQueryOptions(e);(S=(m=i.getDefaultOptions().queries)==null?void 0:m._experimental_beforeQuery)==null||S.call(m,a);const c=i.getQueryCache().get(a.queryHash),l=e.subscribed!==!1;a._optimisticResults=r?"isRestoring":l?"optimistic":void 0,yh(a),hh(a,o,c),mh(o);const u=!i.getQueryCache().get(a.queryHash),[h]=p.useState(()=>new t(i,a)),d=h.getOptimisticResult(a),f=!r&&l;if(p.useSyncExternalStore(p.useCallback(w=>{const j=f?h.subscribe(Ue.batchCalls(w)):at;return h.updateResult(),j},[h,f]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),p.useEffect(()=>{h.setOptions(a)},[a,h]),xh(a,d))throw fc(a,h,o);if(gh({result:d,errorResetBoundary:o,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw d.error;if((b=(v=i.getDefaultOptions().queries)==null?void 0:v._experimental_afterQuery)==null||b.call(v,a,d),a.experimental_prefetchInRender&&!so.isServer()&&bh(d,r)){const w=u?fc(a,h,o):c==null?void 0:c.promise;w==null||w.catch(at).finally(()=>{h.updateResult()})}return a.notifyOnChangeProps?d:h.trackResult(d)}function Ri(e,t){return vh(e,th)}const ye={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"},be={1:"4px",2:"8px",3:"12px",4:"16px"},wn={sm:"4px",md:"6px",lg:"8px"},Ze={xs:"11px",sm:"12px",md:"14px"},Xi={medium:"500",semibold:"600"},io={overlay:1e3,modal:1100,popover:1200,tooltip:1300},Ns={surfaceBase:ye.gray1000,surfaceRaised:ye.gray975,surfaceElevated:ye.gray950,surfaceOverlay:"rgba(0,0,0,0.7)",surfaceHover:ye.gray900,surfaceActive:"#1f2d3d",surfaceSunken:ye.gray1000,borderSubtle:"#21262d",borderDefault:"#30363d",borderStrong:"#484f58",borderFocus:ye.blue500,textPrimary:"#e6edf3",textSecondary:"#8b949e",textMuted:"#484f58",textDisabled:"#32383f",textInverse:ye.gray1000,accent:ye.blue500,accentHover:ye.blue400,accentMuted:"rgba(56,139,253,0.15)",accentContrast:"#ffffff",success:ye.green500,warning:ye.yellow500,danger:ye.red500,info:ye.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)"},No={surfaceBase:ye.gray0,surfaceRaised:ye.gray50,surfaceElevated:ye.gray0,surfaceOverlay:"rgba(0,0,0,0.4)",surfaceHover:ye.gray100,surfaceActive:"#dbeafe",surfaceSunken:ye.gray50,borderSubtle:ye.gray100,borderDefault:ye.gray200,borderStrong:ye.gray300,borderFocus:ye.blue600,textPrimary:"#1f2328",textSecondary:ye.gray600,textMuted:ye.gray400,textDisabled:ye.gray300,textInverse:ye.gray0,accent:ye.blue600,accentHover:ye.blue700,accentMuted:"rgba(9,105,218,0.12)",accentContrast:"#ffffff",success:ye.green600,warning:ye.yellow600,danger:ye.red600,info:ye.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)"},Sh={obsidian:Ns,paper:No,white:No,dark:Ns,light:No,midnight:Ns,arctic:No};function md(e){return`--dql-${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function hc(e){const t={};for(const[n,r]of Object.entries(e))t[md(n)]=r;return t}function pe(e){return`var(${md(e)})`}const wh=p.createContext(null);function kh({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[i,a]=p.useState(t),c=e??i,l=Sh[c],u=p.useCallback(f=>{e===void 0&&a(f),n==null||n(f)},[e,n]);p.useEffect(()=>{if(!r)return;const f=hc(l),m=document.documentElement;for(const[S,v]of Object.entries(f))m.style.setProperty(S,v);return m.setAttribute("data-theme",c),()=>{for(const S of Object.keys(f))m.style.removeProperty(S);m.removeAttribute("data-theme")}},[r,c,l]);const h=p.useMemo(()=>({theme:c,tokens:l,setTheme:u}),[c,l,u]),d=r?void 0:hc(l);return s.jsx(wh.Provider,{value:h,children:s.jsx("div",{"data-theme":c,style:d,children:o})})}function de(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 mc(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function bs(...e){return t=>{let n=!1;const r=e.map(o=>{const i=mc(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():mc(e[o],null)}}}}function Oe(...e){return p.useCallback(bs(...e),e)}function Ch(e,t){const n=p.createContext(t),r=i=>{const{children:a,...c}=i,l=p.useMemo(()=>c,Object.values(c));return s.jsx(n.Provider,{value:l,children:a})};r.displayName=e+"Provider";function o(i){const a=p.useContext(n);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[r,o]}function kn(e,t=[]){let n=[];function r(i,a){const c=p.createContext(a),l=n.length;n=[...n,a];const u=d=>{var w;const{scope:f,children:m,...S}=d,v=((w=f==null?void 0:f[e])==null?void 0:w[l])||c,b=p.useMemo(()=>S,Object.values(S));return s.jsx(v.Provider,{value:b,children:m})};u.displayName=i+"Provider";function h(d,f){var v;const m=((v=f==null?void 0:f[e])==null?void 0:v[l])||c,S=p.useContext(m);if(S)return S;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[u,h]}const o=()=>{const i=n.map(a=>p.createContext(a));return function(c){const l=(c==null?void 0:c[e])||i;return p.useMemo(()=>({[`__scope${e}`]:{...c,[e]:l}}),[c,l])}};return o.scopeName=e,[r,jh(o,...t)]}function jh(...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 a=r.reduce((c,{useScope:l,scopeName:u})=>{const d=l(i)[`__scope${u}`];return{...c,...d}},{});return p.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return n.scopeName=t.scopeName,n}var Zi=ed();const Eh=td(Zi);function Rr(e){const t=Th(e),n=p.forwardRef((r,o)=>{const{children:i,...a}=r,c=p.Children.toArray(i),l=c.find(Rh);if(l){const u=l.props.children,h=c.map(d=>d===l?p.Children.count(u)>1?p.Children.only(null):p.isValidElement(u)?u.props.children:null:d);return s.jsx(t,{...a,ref:o,children:p.isValidElement(u)?p.cloneElement(u,void 0,h):null})}return s.jsx(t,{...a,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Th(e){const t=p.forwardRef((n,r)=>{const{children:o,...i}=n;if(p.isValidElement(o)){const a=_h(o),c=Oh(i,o.props);return o.type!==p.Fragment&&(c.ref=r?bs(r,a):a),p.cloneElement(o,c)}return p.Children.count(o)>1?p.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var gd=Symbol("radix.slottable");function Ah(e){const t=({children:n})=>s.jsx(s.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=gd,t}function Rh(e){return p.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===gd}function Oh(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]=(...c)=>{const l=i(...c);return o(...c),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function _h(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 Ph=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Te=Ph.reduce((e,t)=>{const n=Rr(`Primitive.${t}`),r=p.forwardRef((o,i)=>{const{asChild:a,...c}=o,l=a?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(l,{...c,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function yd(e,t){e&&Zi.flushSync(()=>e.dispatchEvent(t))}function yn(e){const t=p.useRef(e);return p.useEffect(()=>{t.current=e}),p.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function Ih(e,t=globalThis==null?void 0:globalThis.document){const n=yn(e);p.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 Dh="DismissableLayer",Oi="dismissableLayer.update",$h="dismissableLayer.pointerDownOutside",Mh="dismissableLayer.focusOutside",gc,bd=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),So=p.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:a,onDismiss:c,...l}=e,u=p.useContext(bd),[h,d]=p.useState(null),f=(h==null?void 0:h.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,m]=p.useState({}),S=Oe(t,A=>d(A)),v=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),w=v.indexOf(b),j=h?v.indexOf(h):-1,C=u.layersWithOutsidePointerEventsDisabled.size>0,x=j>=w,E=Bh(A=>{const g=A.target,I=[...u.branches].some(T=>T.contains(g));!x||I||(o==null||o(A),a==null||a(A),A.defaultPrevented||c==null||c())},f),P=Fh(A=>{const g=A.target;[...u.branches].some(T=>T.contains(g))||(i==null||i(A),a==null||a(A),A.defaultPrevented||c==null||c())},f);return Ih(A=>{j===u.layers.size-1&&(r==null||r(A),!A.defaultPrevented&&c&&(A.preventDefault(),c()))},f),p.useEffect(()=>{if(h)return n&&(u.layersWithOutsidePointerEventsDisabled.size===0&&(gc=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(h)),u.layers.add(h),yc(),()=>{n&&u.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=gc)}},[h,f,n,u]),p.useEffect(()=>()=>{h&&(u.layers.delete(h),u.layersWithOutsidePointerEventsDisabled.delete(h),yc())},[h,u]),p.useEffect(()=>{const A=()=>m({});return document.addEventListener(Oi,A),()=>document.removeEventListener(Oi,A)},[]),s.jsx(Te.div,{...l,ref:S,style:{pointerEvents:C?x?"auto":"none":void 0,...e.style},onFocusCapture:de(e.onFocusCapture,P.onFocusCapture),onBlurCapture:de(e.onBlurCapture,P.onBlurCapture),onPointerDownCapture:de(e.onPointerDownCapture,E.onPointerDownCapture)})});So.displayName=Dh;var Lh="DismissableLayerBranch",Nh=p.forwardRef((e,t)=>{const n=p.useContext(bd),r=p.useRef(null),o=Oe(t,r);return p.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),s.jsx(Te.div,{...e,ref:o})});Nh.displayName=Lh;function Bh(e,t=globalThis==null?void 0:globalThis.document){const n=yn(e),r=p.useRef(!1),o=p.useRef(()=>{});return p.useEffect(()=>{const i=c=>{if(c.target&&!r.current){let l=function(){xd($h,n,u,{discrete:!0})};const u={originalEvent:c};c.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},a=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function Fh(e,t=globalThis==null?void 0:globalThis.document){const n=yn(e),r=p.useRef(!1);return p.useEffect(()=>{const o=i=>{i.target&&!r.current&&xd(Mh,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 yc(){const e=new CustomEvent(Oi);document.dispatchEvent(e)}function xd(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?yd(o,i):o.dispatchEvent(i)}var bn=globalThis!=null&&globalThis.document?p.useLayoutEffect:()=>{},zh=nd[" useId ".trim().toString()]||(()=>{}),qh=0;function to(e){const[t,n]=p.useState(zh());return bn(()=>{n(r=>r??String(qh++))},[e]),t?`radix-${t}`:""}const Uh=["top","right","bottom","left"],xn=Math.min,mt=Math.max,ss=Math.round,Bo=Math.floor,Wt=e=>({x:e,y:e}),Wh={left:"right",right:"left",bottom:"top",top:"bottom"};function _i(e,t,n){return mt(e,xn(t,n))}function Yt(e,t){return typeof e=="function"?e(t):e}function Xt(e){return e.split("-")[0]}function Dr(e){return e.split("-")[1]}function ea(e){return e==="x"?"y":"x"}function ta(e){return e==="y"?"height":"width"}function Ut(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function na(e){return ea(Ut(e))}function Kh(e,t,n){n===void 0&&(n=!1);const r=Dr(e),o=na(e),i=ta(o);let a=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=is(a)),[a,is(a)]}function Vh(e){const t=is(e);return[Pi(e),t,Pi(t)]}function Pi(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const bc=["left","right"],xc=["right","left"],Hh=["top","bottom"],Gh=["bottom","top"];function Qh(e,t,n){switch(e){case"top":case"bottom":return n?t?xc:bc:t?bc:xc;case"left":case"right":return t?Hh:Gh;default:return[]}}function Jh(e,t,n,r){const o=Dr(e);let i=Qh(Xt(e),n==="start",r);return o&&(i=i.map(a=>a+"-"+o),t&&(i=i.concat(i.map(Pi)))),i}function is(e){const t=Xt(e);return Wh[t]+e.slice(t.length)}function Yh(e){return{top:0,right:0,bottom:0,left:0,...e}}function vd(e){return typeof e!="number"?Yh(e):{top:e,right:e,bottom:e,left:e}}function as(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 vc(e,t,n){let{reference:r,floating:o}=e;const i=Ut(t),a=na(t),c=ta(a),l=Xt(t),u=i==="y",h=r.x+r.width/2-o.width/2,d=r.y+r.height/2-o.height/2,f=r[c]/2-o[c]/2;let m;switch(l){case"top":m={x:h,y:r.y-o.height};break;case"bottom":m={x:h,y:r.y+r.height};break;case"right":m={x:r.x+r.width,y:d};break;case"left":m={x:r.x-o.width,y:d};break;default:m={x:r.x,y:r.y}}switch(Dr(t)){case"start":m[a]-=f*(n&&u?-1:1);break;case"end":m[a]+=f*(n&&u?-1:1);break}return m}async function Xh(e,t){var n;t===void 0&&(t={});const{x:r,y:o,platform:i,rects:a,elements:c,strategy:l}=e,{boundary:u="clippingAncestors",rootBoundary:h="viewport",elementContext:d="floating",altBoundary:f=!1,padding:m=0}=Yt(t,e),S=vd(m),b=c[f?d==="floating"?"reference":"floating":d],w=as(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(c.floating)),boundary:u,rootBoundary:h,strategy:l})),j=d==="floating"?{x:r,y:o,width:a.floating.width,height:a.floating.height}:a.reference,C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c.floating)),x=await(i.isElement==null?void 0:i.isElement(C))?await(i.getScale==null?void 0:i.getScale(C))||{x:1,y:1}:{x:1,y:1},E=as(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:c,rect:j,offsetParent:C,strategy:l}):j);return{top:(w.top-E.top+S.top)/x.y,bottom:(E.bottom-w.bottom+S.bottom)/x.y,left:(w.left-E.left+S.left)/x.x,right:(E.right-w.right+S.right)/x.x}}const Zh=50,em=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:a}=n,c=a.detectOverflow?a:{...a,detectOverflow:Xh},l=await(a.isRTL==null?void 0:a.isRTL(t));let u=await a.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:d}=vc(u,r,l),f=r,m=0;const S={};for(let v=0;v<i.length;v++){const b=i[v];if(!b)continue;const{name:w,fn:j}=b,{x:C,y:x,data:E,reset:P}=await j({x:h,y:d,initialPlacement:r,placement:f,strategy:o,middlewareData:S,rects:u,platform:c,elements:{reference:e,floating:t}});h=C??h,d=x??d,S[w]={...S[w],...E},P&&m<Zh&&(m++,typeof P=="object"&&(P.placement&&(f=P.placement),P.rects&&(u=P.rects===!0?await a.getElementRects({reference:e,floating:t,strategy:o}):P.rects),{x:h,y:d}=vc(u,f,l)),v=-1)}return{x:h,y:d,placement:f,strategy:o,middlewareData:S}},tm=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:a,elements:c,middlewareData:l}=t,{element:u,padding:h=0}=Yt(e,t)||{};if(u==null)return{};const d=vd(h),f={x:n,y:r},m=na(o),S=ta(m),v=await a.getDimensions(u),b=m==="y",w=b?"top":"left",j=b?"bottom":"right",C=b?"clientHeight":"clientWidth",x=i.reference[S]+i.reference[m]-f[m]-i.floating[S],E=f[m]-i.reference[m],P=await(a.getOffsetParent==null?void 0:a.getOffsetParent(u));let A=P?P[C]:0;(!A||!await(a.isElement==null?void 0:a.isElement(P)))&&(A=c.floating[C]||i.floating[S]);const g=x/2-E/2,I=A/2-v[S]/2-1,T=xn(d[w],I),O=xn(d[j],I),_=T,M=A-v[S]-O,q=A/2-v[S]/2+g,G=_i(_,q,M),J=!l.arrow&&Dr(o)!=null&&q!==G&&i.reference[S]/2-(q<_?T:O)-v[S]/2<0,H=J?q<_?q-_:q-M:0;return{[m]:f[m]+H,data:{[m]:G,centerOffset:q-G-H,...J&&{alignmentOffset:H}},reset:J}}}),nm=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:o,middlewareData:i,rects:a,initialPlacement:c,platform:l,elements:u}=t,{mainAxis:h=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:m="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:v=!0,...b}=Yt(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const w=Xt(o),j=Ut(c),C=Xt(c)===c,x=await(l.isRTL==null?void 0:l.isRTL(u.floating)),E=f||(C||!v?[is(c)]:Vh(c)),P=S!=="none";!f&&P&&E.push(...Jh(c,v,S,x));const A=[c,...E],g=await l.detectOverflow(t,b),I=[];let T=((r=i.flip)==null?void 0:r.overflows)||[];if(h&&I.push(g[w]),d){const q=Kh(o,a,x);I.push(g[q[0]],g[q[1]])}if(T=[...T,{placement:o,overflows:I}],!I.every(q=>q<=0)){var O,_;const q=(((O=i.flip)==null?void 0:O.index)||0)+1,G=A[q];if(G&&(!(d==="alignment"?j!==Ut(G):!1)||T.every(L=>Ut(L.placement)===j?L.overflows[0]>0:!0)))return{data:{index:q,overflows:T},reset:{placement:G}};let J=(_=T.filter(H=>H.overflows[0]<=0).sort((H,L)=>H.overflows[1]-L.overflows[1])[0])==null?void 0:_.placement;if(!J)switch(m){case"bestFit":{var M;const H=(M=T.filter(L=>{if(P){const $=Ut(L.placement);return $===j||$==="y"}return!0}).map(L=>[L.placement,L.overflows.filter($=>$>0).reduce(($,X)=>$+X,0)]).sort((L,$)=>L[1]-$[1])[0])==null?void 0:M[0];H&&(J=H);break}case"initialPlacement":J=c;break}if(o!==J)return{reset:{placement:J}}}return{}}}};function Sc(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function wc(e){return Uh.some(t=>e[t]>=0)}const rm=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:o="referenceHidden",...i}=Yt(e,t);switch(o){case"referenceHidden":{const a=await r.detectOverflow(t,{...i,elementContext:"reference"}),c=Sc(a,n.reference);return{data:{referenceHiddenOffsets:c,referenceHidden:wc(c)}}}case"escaped":{const a=await r.detectOverflow(t,{...i,altBoundary:!0}),c=Sc(a,n.floating);return{data:{escapedOffsets:c,escaped:wc(c)}}}default:return{}}}}},Sd=new Set(["left","top"]);async function om(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),a=Xt(n),c=Dr(n),l=Ut(n)==="y",u=Sd.has(a)?-1:1,h=i&&l?-1:1,d=Yt(t,e);let{mainAxis:f,crossAxis:m,alignmentAxis:S}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return c&&typeof S=="number"&&(m=c==="end"?S*-1:S),l?{x:m*h,y:f*u}:{x:f*u,y:m*h}}const sm=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:o,y:i,placement:a,middlewareData:c}=t,l=await om(t,e);return a===((n=c.offset)==null?void 0:n.placement)&&(r=c.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:i+l.y,data:{...l,placement:a}}}}},im=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:a=!0,crossAxis:c=!1,limiter:l={fn:w=>{let{x:j,y:C}=w;return{x:j,y:C}}},...u}=Yt(e,t),h={x:n,y:r},d=await i.detectOverflow(t,u),f=Ut(Xt(o)),m=ea(f);let S=h[m],v=h[f];if(a){const w=m==="y"?"top":"left",j=m==="y"?"bottom":"right",C=S+d[w],x=S-d[j];S=_i(C,S,x)}if(c){const w=f==="y"?"top":"left",j=f==="y"?"bottom":"right",C=v+d[w],x=v-d[j];v=_i(C,v,x)}const b=l.fn({...t,[m]:S,[f]:v});return{...b,data:{x:b.x-n,y:b.y-r,enabled:{[m]:a,[f]:c}}}}}},am=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:a}=t,{offset:c=0,mainAxis:l=!0,crossAxis:u=!0}=Yt(e,t),h={x:n,y:r},d=Ut(o),f=ea(d);let m=h[f],S=h[d];const v=Yt(c,t),b=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:0,crossAxis:0,...v};if(l){const C=f==="y"?"height":"width",x=i.reference[f]-i.floating[C]+b.mainAxis,E=i.reference[f]+i.reference[C]-b.mainAxis;m<x?m=x:m>E&&(m=E)}if(u){var w,j;const C=f==="y"?"width":"height",x=Sd.has(Xt(o)),E=i.reference[d]-i.floating[C]+(x&&((w=a.offset)==null?void 0:w[d])||0)+(x?0:b.crossAxis),P=i.reference[d]+i.reference[C]+(x?0:((j=a.offset)==null?void 0:j[d])||0)-(x?b.crossAxis:0);S<E?S=E:S>P&&(S=P)}return{[f]:m,[d]:S}}}},cm=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:o,rects:i,platform:a,elements:c}=t,{apply:l=()=>{},...u}=Yt(e,t),h=await a.detectOverflow(t,u),d=Xt(o),f=Dr(o),m=Ut(o)==="y",{width:S,height:v}=i.floating;let b,w;d==="top"||d==="bottom"?(b=d,w=f===(await(a.isRTL==null?void 0:a.isRTL(c.floating))?"start":"end")?"left":"right"):(w=d,b=f==="end"?"top":"bottom");const j=v-h.top-h.bottom,C=S-h.left-h.right,x=xn(v-h[b],j),E=xn(S-h[w],C),P=!t.middlewareData.shift;let A=x,g=E;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(g=C),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(A=j),P&&!f){const T=mt(h.left,0),O=mt(h.right,0),_=mt(h.top,0),M=mt(h.bottom,0);m?g=S-2*(T!==0||O!==0?T+O:mt(h.left,h.right)):A=v-2*(_!==0||M!==0?_+M:mt(h.top,h.bottom))}await l({...t,availableWidth:g,availableHeight:A});const I=await a.getDimensions(c.floating);return S!==I.width||v!==I.height?{reset:{rects:!0}}:{}}}};function xs(){return typeof window<"u"}function $r(e){return wd(e)?(e.nodeName||"").toLowerCase():"#document"}function gt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Kt(e){var t;return(t=(wd(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function wd(e){return xs()?e instanceof Node||e instanceof gt(e).Node:!1}function Pt(e){return xs()?e instanceof Element||e instanceof gt(e).Element:!1}function Zt(e){return xs()?e instanceof HTMLElement||e instanceof gt(e).HTMLElement:!1}function kc(e){return!xs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof gt(e).ShadowRoot}function wo(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=It(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&o!=="inline"&&o!=="contents"}function lm(e){return/^(table|td|th)$/.test($r(e))}function vs(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const dm=/transform|translate|scale|rotate|perspective|filter/,um=/paint|layout|strict|content/,Rn=e=>!!e&&e!=="none";let Bs;function ra(e){const t=Pt(e)?It(e):e;return Rn(t.transform)||Rn(t.translate)||Rn(t.scale)||Rn(t.rotate)||Rn(t.perspective)||!oa()&&(Rn(t.backdropFilter)||Rn(t.filter))||dm.test(t.willChange||"")||um.test(t.contain||"")}function pm(e){let t=vn(e);for(;Zt(t)&&!Or(t);){if(ra(t))return t;if(vs(t))return null;t=vn(t)}return null}function oa(){return Bs==null&&(Bs=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Bs}function Or(e){return/^(html|body|#document)$/.test($r(e))}function It(e){return gt(e).getComputedStyle(e)}function Ss(e){return Pt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function vn(e){if($r(e)==="html")return e;const t=e.assignedSlot||e.parentNode||kc(e)&&e.host||Kt(e);return kc(t)?t.host:t}function kd(e){const t=vn(e);return Or(t)?e.ownerDocument?e.ownerDocument.body:e.body:Zt(t)&&wo(t)?t:kd(t)}function ao(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=kd(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),a=gt(o);if(i){const c=Ii(a);return t.concat(a,a.visualViewport||[],wo(o)?o:[],c&&n?ao(c):[])}else return t.concat(o,ao(o,[],n))}function Ii(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Cd(e){const t=It(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Zt(e),i=o?e.offsetWidth:n,a=o?e.offsetHeight:r,c=ss(n)!==i||ss(r)!==a;return c&&(n=i,r=a),{width:n,height:r,$:c}}function sa(e){return Pt(e)?e:e.contextElement}function pr(e){const t=sa(e);if(!Zt(t))return Wt(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=Cd(t);let a=(i?ss(n.width):n.width)/r,c=(i?ss(n.height):n.height)/o;return(!a||!Number.isFinite(a))&&(a=1),(!c||!Number.isFinite(c))&&(c=1),{x:a,y:c}}const fm=Wt(0);function jd(e){const t=gt(e);return!oa()||!t.visualViewport?fm:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function hm(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==gt(e)?!1:t}function Wn(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=sa(e);let a=Wt(1);t&&(r?Pt(r)&&(a=pr(r)):a=pr(e));const c=hm(i,n,r)?jd(i):Wt(0);let l=(o.left+c.x)/a.x,u=(o.top+c.y)/a.y,h=o.width/a.x,d=o.height/a.y;if(i){const f=gt(i),m=r&&Pt(r)?gt(r):r;let S=f,v=Ii(S);for(;v&&r&&m!==S;){const b=pr(v),w=v.getBoundingClientRect(),j=It(v),C=w.left+(v.clientLeft+parseFloat(j.paddingLeft))*b.x,x=w.top+(v.clientTop+parseFloat(j.paddingTop))*b.y;l*=b.x,u*=b.y,h*=b.x,d*=b.y,l+=C,u+=x,S=gt(v),v=Ii(S)}}return as({width:h,height:d,x:l,y:u})}function ws(e,t){const n=Ss(e).scrollLeft;return t?t.left+n:Wn(Kt(e)).left+n}function Ed(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-ws(e,n),o=n.top+t.scrollTop;return{x:r,y:o}}function mm(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i=o==="fixed",a=Kt(r),c=t?vs(t.floating):!1;if(r===a||c&&i)return n;let l={scrollLeft:0,scrollTop:0},u=Wt(1);const h=Wt(0),d=Zt(r);if((d||!d&&!i)&&(($r(r)!=="body"||wo(a))&&(l=Ss(r)),d)){const m=Wn(r);u=pr(r),h.x=m.x+r.clientLeft,h.y=m.y+r.clientTop}const f=a&&!d&&!i?Ed(a,l):Wt(0);return{width:n.width*u.x,height:n.height*u.y,x:n.x*u.x-l.scrollLeft*u.x+h.x+f.x,y:n.y*u.y-l.scrollTop*u.y+h.y+f.y}}function gm(e){return Array.from(e.getClientRects())}function ym(e){const t=Kt(e),n=Ss(e),r=e.ownerDocument.body,o=mt(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=mt(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+ws(e);const c=-n.scrollTop;return It(r).direction==="rtl"&&(a+=mt(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:a,y:c}}const Cc=25;function bm(e,t){const n=gt(e),r=Kt(e),o=n.visualViewport;let i=r.clientWidth,a=r.clientHeight,c=0,l=0;if(o){i=o.width,a=o.height;const h=oa();(!h||h&&t==="fixed")&&(c=o.offsetLeft,l=o.offsetTop)}const u=ws(r);if(u<=0){const h=r.ownerDocument,d=h.body,f=getComputedStyle(d),m=h.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,S=Math.abs(r.clientWidth-d.clientWidth-m);S<=Cc&&(i-=S)}else u<=Cc&&(i+=u);return{width:i,height:a,x:c,y:l}}function xm(e,t){const n=Wn(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Zt(e)?pr(e):Wt(1),a=e.clientWidth*i.x,c=e.clientHeight*i.y,l=o*i.x,u=r*i.y;return{width:a,height:c,x:l,y:u}}function jc(e,t,n){let r;if(t==="viewport")r=bm(e,n);else if(t==="document")r=ym(Kt(e));else if(Pt(t))r=xm(t,n);else{const o=jd(e);r={x:t.x-o.x,y:t.y-o.y,width:t.width,height:t.height}}return as(r)}function Td(e,t){const n=vn(e);return n===t||!Pt(n)||Or(n)?!1:It(n).position==="fixed"||Td(n,t)}function vm(e,t){const n=t.get(e);if(n)return n;let r=ao(e,[],!1).filter(c=>Pt(c)&&$r(c)!=="body"),o=null;const i=It(e).position==="fixed";let a=i?vn(e):e;for(;Pt(a)&&!Or(a);){const c=It(a),l=ra(a);!l&&c.position==="fixed"&&(o=null),(i?!l&&!o:!l&&c.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||wo(a)&&!l&&Td(e,a))?r=r.filter(h=>h!==a):o=c,a=vn(a)}return t.set(e,r),r}function Sm(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const a=[...n==="clippingAncestors"?vs(t)?[]:vm(t,this._c):[].concat(n),r],c=jc(t,a[0],o);let l=c.top,u=c.right,h=c.bottom,d=c.left;for(let f=1;f<a.length;f++){const m=jc(t,a[f],o);l=mt(m.top,l),u=xn(m.right,u),h=xn(m.bottom,h),d=mt(m.left,d)}return{width:u-d,height:h-l,x:d,y:l}}function wm(e){const{width:t,height:n}=Cd(e);return{width:t,height:n}}function km(e,t,n){const r=Zt(t),o=Kt(t),i=n==="fixed",a=Wn(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=Wt(0);function u(){l.x=ws(o)}if(r||!r&&!i)if(($r(t)!=="body"||wo(o))&&(c=Ss(t)),r){const m=Wn(t,!0,i,t);l.x=m.x+t.clientLeft,l.y=m.y+t.clientTop}else o&&u();i&&!r&&o&&u();const h=o&&!r&&!i?Ed(o,c):Wt(0),d=a.left+c.scrollLeft-l.x-h.x,f=a.top+c.scrollTop-l.y-h.y;return{x:d,y:f,width:a.width,height:a.height}}function Fs(e){return It(e).position==="static"}function Ec(e,t){if(!Zt(e)||It(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Kt(e)===n&&(n=n.ownerDocument.body),n}function Ad(e,t){const n=gt(e);if(vs(e))return n;if(!Zt(e)){let o=vn(e);for(;o&&!Or(o);){if(Pt(o)&&!Fs(o))return o;o=vn(o)}return n}let r=Ec(e,t);for(;r&&lm(r)&&Fs(r);)r=Ec(r,t);return r&&Or(r)&&Fs(r)&&!ra(r)?n:r||pm(e)||n}const Cm=async function(e){const t=this.getOffsetParent||Ad,n=this.getDimensions,r=await n(e.floating);return{reference:km(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function jm(e){return It(e).direction==="rtl"}const Em={convertOffsetParentRelativeRectToViewportRelativeRect:mm,getDocumentElement:Kt,getClippingRect:Sm,getOffsetParent:Ad,getElementRects:Cm,getClientRects:gm,getDimensions:wm,getScale:pr,isElement:Pt,isRTL:jm};function Rd(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Tm(e,t){let n=null,r;const o=Kt(e);function i(){var c;clearTimeout(r),(c=n)==null||c.disconnect(),n=null}function a(c,l){c===void 0&&(c=!1),l===void 0&&(l=1),i();const u=e.getBoundingClientRect(),{left:h,top:d,width:f,height:m}=u;if(c||t(),!f||!m)return;const S=Bo(d),v=Bo(o.clientWidth-(h+f)),b=Bo(o.clientHeight-(d+m)),w=Bo(h),C={rootMargin:-S+"px "+-v+"px "+-b+"px "+-w+"px",threshold:mt(0,xn(1,l))||1};let x=!0;function E(P){const A=P[0].intersectionRatio;if(A!==l){if(!x)return a();A?a(!1,A):r=setTimeout(()=>{a(!1,1e-7)},1e3)}A===1&&!Rd(u,e.getBoundingClientRect())&&a(),x=!1}try{n=new IntersectionObserver(E,{...C,root:o.ownerDocument})}catch{n=new IntersectionObserver(E,C)}n.observe(e)}return a(!0),i}function Am(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:a=typeof ResizeObserver=="function",layoutShift:c=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,u=sa(e),h=o||i?[...u?ao(u):[],...t?ao(t):[]]:[];h.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),i&&w.addEventListener("resize",n)});const d=u&&c?Tm(u,n):null;let f=-1,m=null;a&&(m=new ResizeObserver(w=>{let[j]=w;j&&j.target===u&&m&&t&&(m.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var C;(C=m)==null||C.observe(t)})),n()}),u&&!l&&m.observe(u),t&&m.observe(t));let S,v=l?Wn(e):null;l&&b();function b(){const w=Wn(e);v&&!Rd(v,w)&&n(),v=w,S=requestAnimationFrame(b)}return n(),()=>{var w;h.forEach(j=>{o&&j.removeEventListener("scroll",n),i&&j.removeEventListener("resize",n)}),d==null||d(),(w=m)==null||w.disconnect(),m=null,l&&cancelAnimationFrame(S)}}const Rm=sm,Om=im,_m=nm,Pm=cm,Im=rm,Tc=tm,Dm=am,$m=(e,t,n)=>{const r=new Map,o={platform:Em,...n},i={...o.platform,_c:r};return em(e,t,{...o,platform:i})};var Mm=typeof document<"u",Lm=function(){},Xo=Mm?p.useLayoutEffect:Lm;function cs(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(!cs(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)&&!cs(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Od(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function Ac(e,t){const n=Od(e);return Math.round(t*n)/n}function zs(e){const t=p.useRef(e);return Xo(()=>{t.current=e}),t}function Nm(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:a}={},transform:c=!0,whileElementsMounted:l,open:u}=e,[h,d]=p.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[f,m]=p.useState(r);cs(f,r)||m(r);const[S,v]=p.useState(null),[b,w]=p.useState(null),j=p.useCallback(L=>{L!==P.current&&(P.current=L,v(L))},[]),C=p.useCallback(L=>{L!==A.current&&(A.current=L,w(L))},[]),x=i||S,E=a||b,P=p.useRef(null),A=p.useRef(null),g=p.useRef(h),I=l!=null,T=zs(l),O=zs(o),_=zs(u),M=p.useCallback(()=>{if(!P.current||!A.current)return;const L={placement:t,strategy:n,middleware:f};O.current&&(L.platform=O.current),$m(P.current,A.current,L).then($=>{const X={...$,isPositioned:_.current!==!1};q.current&&!cs(g.current,X)&&(g.current=X,Zi.flushSync(()=>{d(X)}))})},[f,t,n,O,_]);Xo(()=>{u===!1&&g.current.isPositioned&&(g.current.isPositioned=!1,d(L=>({...L,isPositioned:!1})))},[u]);const q=p.useRef(!1);Xo(()=>(q.current=!0,()=>{q.current=!1}),[]),Xo(()=>{if(x&&(P.current=x),E&&(A.current=E),x&&E){if(T.current)return T.current(x,E,M);M()}},[x,E,M,T,I]);const G=p.useMemo(()=>({reference:P,floating:A,setReference:j,setFloating:C}),[j,C]),J=p.useMemo(()=>({reference:x,floating:E}),[x,E]),H=p.useMemo(()=>{const L={position:n,left:0,top:0};if(!J.floating)return L;const $=Ac(J.floating,h.x),X=Ac(J.floating,h.y);return c?{...L,transform:"translate("+$+"px, "+X+"px)",...Od(J.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:$,top:X}},[n,c,J.floating,h.x,h.y]);return p.useMemo(()=>({...h,update:M,refs:G,elements:J,floatingStyles:H}),[h,M,G,J,H])}const Bm=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?Tc({element:r.current,padding:o}).fn(n):{}:r?Tc({element:r,padding:o}).fn(n):{}}}},Fm=(e,t)=>{const n=Rm(e);return{name:n.name,fn:n.fn,options:[e,t]}},zm=(e,t)=>{const n=Om(e);return{name:n.name,fn:n.fn,options:[e,t]}},qm=(e,t)=>({fn:Dm(e).fn,options:[e,t]}),Um=(e,t)=>{const n=_m(e);return{name:n.name,fn:n.fn,options:[e,t]}},Wm=(e,t)=>{const n=Pm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Km=(e,t)=>{const n=Im(e);return{name:n.name,fn:n.fn,options:[e,t]}},Vm=(e,t)=>{const n=Bm(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Hm="Arrow",_d=p.forwardRef((e,t)=>{const{children:n,width:r=10,height:o=5,...i}=e;return s.jsx(Te.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"})})});_d.displayName=Hm;var Gm=_d;function Qm(e){const[t,n]=p.useState(void 0);return bn(()=>{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 a,c;if("borderBoxSize"in i){const l=i.borderBoxSize,u=Array.isArray(l)?l[0]:l;a=u.inlineSize,c=u.blockSize}else a=e.offsetWidth,c=e.offsetHeight;n({width:a,height:c})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}var ia="Popper",[Pd,Mr]=kn(ia),[Jm,Id]=Pd(ia),Dd=e=>{const{__scopePopper:t,children:n}=e,[r,o]=p.useState(null);return s.jsx(Jm,{scope:t,anchor:r,onAnchorChange:o,children:n})};Dd.displayName=ia;var $d="PopperAnchor",Md=p.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Id($d,n),a=p.useRef(null),c=Oe(t,a),l=p.useRef(null);return p.useEffect(()=>{const u=l.current;l.current=(r==null?void 0:r.current)||a.current,u!==l.current&&i.onAnchorChange(l.current)}),r?null:s.jsx(Te.div,{...o,ref:c})});Md.displayName=$d;var aa="PopperContent",[Ym,Xm]=Pd(aa),Ld=p.forwardRef((e,t)=>{var ce,ke,xe,De,We,Be;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:i="center",alignOffset:a=0,arrowPadding:c=0,avoidCollisions:l=!0,collisionBoundary:u=[],collisionPadding:h=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:m="optimized",onPlaced:S,...v}=e,b=Id(aa,n),[w,j]=p.useState(null),C=Oe(t,Ee=>j(Ee)),[x,E]=p.useState(null),P=Qm(x),A=(P==null?void 0:P.width)??0,g=(P==null?void 0:P.height)??0,I=r+(i!=="center"?"-"+i:""),T=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},O=Array.isArray(u)?u:[u],_=O.length>0,M={padding:T,boundary:O.filter(eg),altBoundary:_},{refs:q,floatingStyles:G,placement:J,isPositioned:H,middlewareData:L}=Nm({strategy:"fixed",placement:I,whileElementsMounted:(...Ee)=>Am(...Ee,{animationFrame:m==="always"}),elements:{reference:b.anchor},middleware:[Fm({mainAxis:o+g,alignmentAxis:a}),l&&zm({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?qm():void 0,...M}),l&&Um({...M}),Wm({...M,apply:({elements:Ee,rects:ge,availableWidth:Je,availableHeight:tt})=>{const{width:Fe,height:Ke}=ge.reference,bt=Ee.floating.style;bt.setProperty("--radix-popper-available-width",`${Je}px`),bt.setProperty("--radix-popper-available-height",`${tt}px`),bt.setProperty("--radix-popper-anchor-width",`${Fe}px`),bt.setProperty("--radix-popper-anchor-height",`${Ke}px`)}}),x&&Vm({element:x,padding:c}),tg({arrowWidth:A,arrowHeight:g}),f&&Km({strategy:"referenceHidden",...M})]}),[$,X]=Fd(J),W=yn(S);bn(()=>{H&&(W==null||W())},[H,W]);const te=(ce=L.arrow)==null?void 0:ce.x,F=(ke=L.arrow)==null?void 0:ke.y,K=((xe=L.arrow)==null?void 0:xe.centerOffset)!==0,[oe,ee]=p.useState();return bn(()=>{w&&ee(window.getComputedStyle(w).zIndex)},[w]),s.jsx("div",{ref:q.setFloating,"data-radix-popper-content-wrapper":"",style:{...G,transform:H?G.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:oe,"--radix-popper-transform-origin":[(De=L.transformOrigin)==null?void 0:De.x,(We=L.transformOrigin)==null?void 0:We.y].join(" "),...((Be=L.hide)==null?void 0:Be.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:s.jsx(Ym,{scope:n,placedSide:$,onArrowChange:E,arrowX:te,arrowY:F,shouldHideArrow:K,children:s.jsx(Te.div,{"data-side":$,"data-align":X,...v,ref:C,style:{...v.style,animation:H?void 0:"none"}})})})});Ld.displayName=aa;var Nd="PopperArrow",Zm={top:"bottom",right:"left",bottom:"top",left:"right"},Bd=p.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,i=Xm(Nd,r),a=Zm[i.placedSide];return s.jsx("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[a]: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(Gm,{...o,ref:n,style:{...o.style,display:"block"}})})});Bd.displayName=Nd;function eg(e){return e!==null}var tg=e=>({name:"transformOrigin",options:e,fn(t){var b,w,j;const{placement:n,rects:r,middlewareData:o}=t,a=((b=o.arrow)==null?void 0:b.centerOffset)!==0,c=a?0:e.arrowWidth,l=a?0:e.arrowHeight,[u,h]=Fd(n),d={start:"0%",center:"50%",end:"100%"}[h],f=(((w=o.arrow)==null?void 0:w.x)??0)+c/2,m=(((j=o.arrow)==null?void 0:j.y)??0)+l/2;let S="",v="";return u==="bottom"?(S=a?d:`${f}px`,v=`${-l}px`):u==="top"?(S=a?d:`${f}px`,v=`${r.floating.height+l}px`):u==="right"?(S=`${-l}px`,v=a?d:`${m}px`):u==="left"&&(S=`${r.floating.width+l}px`,v=a?d:`${m}px`),{data:{x:S,y:v}}}});function Fd(e){const[t,n="center"]=e.split("-");return[t,n]}var ng=Dd,ks=Md,ca=Ld,la=Bd,rg="Portal",ko=p.forwardRef((e,t)=>{var c;const{container:n,...r}=e,[o,i]=p.useState(!1);bn(()=>i(!0),[]);const a=n||o&&((c=globalThis==null?void 0:globalThis.document)==null?void 0:c.body);return a?Eh.createPortal(s.jsx(Te.div,{...r,ref:t}),a):null});ko.displayName=rg;function og(e,t){return p.useReducer((n,r)=>t[n][r]??n,e)}var kt=e=>{const{present:t,children:n}=e,r=sg(t),o=typeof n=="function"?n({present:r.isPresent}):p.Children.only(n),i=Oe(r.ref,ig(o));return typeof n=="function"||r.isPresent?p.cloneElement(o,{ref:i}):null};kt.displayName="Presence";function sg(e){const[t,n]=p.useState(),r=p.useRef(null),o=p.useRef(e),i=p.useRef("none"),a=e?"mounted":"unmounted",[c,l]=og(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const u=Fo(r.current);i.current=c==="mounted"?u:"none"},[c]),bn(()=>{const u=r.current,h=o.current;if(h!==e){const f=i.current,m=Fo(u);e?l("MOUNT"):m==="none"||(u==null?void 0:u.display)==="none"?l("UNMOUNT"):l(h&&f!==m?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),bn(()=>{if(t){let u;const h=t.ownerDocument.defaultView??window,d=m=>{const v=Fo(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&v&&(l("ANIMATION_END"),!o.current)){const b=t.style.animationFillMode;t.style.animationFillMode="forwards",u=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=b)})}},f=m=>{m.target===t&&(i.current=Fo(r.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{h.clearTimeout(u),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:p.useCallback(u=>{r.current=u?getComputedStyle(u):null,n(u)},[])}}function Fo(e){return(e==null?void 0:e.animationName)||"none"}function ig(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 ag=nd[" useInsertionEffect ".trim().toString()]||bn;function da({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,i,a]=cg({defaultProp:t,onChange:n}),c=e!==void 0,l=c?e:o;{const h=p.useRef(e!==void 0);p.useEffect(()=>{const d=h.current;d!==c&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${c?"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.`),h.current=c},[c,r])}const u=p.useCallback(h=>{var d;if(c){const f=lg(h)?h(e):h;f!==e&&((d=a.current)==null||d.call(a,f))}else i(h)},[c,e,i,a]);return[l,u]}function cg({defaultProp:e,onChange:t}){const[n,r]=p.useState(e),o=p.useRef(n),i=p.useRef(t);return ag(()=>{i.current=t},[t]),p.useEffect(()=>{var a;o.current!==n&&((a=i.current)==null||a.call(i,n),o.current=n)},[n,o]),[n,r,i]}function lg(e){return typeof e=="function"}var dg=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"}),ug="VisuallyHidden",zd=p.forwardRef((e,t)=>s.jsx(Te.span,{...e,ref:t,style:{...dg,...e.style}}));zd.displayName=ug;var pg=zd,[Cs]=kn("Tooltip",[Mr]),js=Mr(),qd="TooltipProvider",fg=700,Di="tooltip.open",[hg,ua]=Cs(qd),Ud=e=>{const{__scopeTooltip:t,delayDuration:n=fg,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,a=p.useRef(!0),c=p.useRef(!1),l=p.useRef(0);return p.useEffect(()=>{const u=l.current;return()=>window.clearTimeout(u)},[]),s.jsx(hg,{scope:t,isOpenDelayedRef:a,delayDuration:n,onOpen:p.useCallback(()=>{window.clearTimeout(l.current),a.current=!1},[]),onClose:p.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>a.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:p.useCallback(u=>{c.current=u},[]),disableHoverableContent:o,children:i})};Ud.displayName=qd;var co="Tooltip",[mg,Co]=Cs(co),Wd=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:a,delayDuration:c}=e,l=ua(co,e.__scopeTooltip),u=js(t),[h,d]=p.useState(null),f=to(),m=p.useRef(0),S=a??l.disableHoverableContent,v=c??l.delayDuration,b=p.useRef(!1),[w,j]=da({prop:r,defaultProp:o??!1,onChange:A=>{A?(l.onOpen(),document.dispatchEvent(new CustomEvent(Di))):l.onClose(),i==null||i(A)},caller:co}),C=p.useMemo(()=>w?b.current?"delayed-open":"instant-open":"closed",[w]),x=p.useCallback(()=>{window.clearTimeout(m.current),m.current=0,b.current=!1,j(!0)},[j]),E=p.useCallback(()=>{window.clearTimeout(m.current),m.current=0,j(!1)},[j]),P=p.useCallback(()=>{window.clearTimeout(m.current),m.current=window.setTimeout(()=>{b.current=!0,j(!0),m.current=0},v)},[v,j]);return p.useEffect(()=>()=>{m.current&&(window.clearTimeout(m.current),m.current=0)},[]),s.jsx(ng,{...u,children:s.jsx(mg,{scope:t,contentId:f,open:w,stateAttribute:C,trigger:h,onTriggerChange:d,onTriggerEnter:p.useCallback(()=>{l.isOpenDelayedRef.current?P():x()},[l.isOpenDelayedRef,P,x]),onTriggerLeave:p.useCallback(()=>{S?E():(window.clearTimeout(m.current),m.current=0)},[E,S]),onOpen:x,onClose:E,disableHoverableContent:S,children:n})})};Wd.displayName=co;var $i="TooltipTrigger",Kd=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Co($i,n),i=ua($i,n),a=js(n),c=p.useRef(null),l=Oe(t,c,o.onTriggerChange),u=p.useRef(!1),h=p.useRef(!1),d=p.useCallback(()=>u.current=!1,[]);return p.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),s.jsx(ks,{asChild:!0,...a,children:s.jsx(Te.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:l,onPointerMove:de(e.onPointerMove,f=>{f.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:de(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:de(e.onPointerDown,()=>{o.open&&o.onClose(),u.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:de(e.onFocus,()=>{u.current||o.onOpen()}),onBlur:de(e.onBlur,o.onClose),onClick:de(e.onClick,o.onClose)})})});Kd.displayName=$i;var pa="TooltipPortal",[gg,yg]=Cs(pa,{forceMount:void 0}),Vd=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,i=Co(pa,t);return s.jsx(gg,{scope:t,forceMount:n,children:s.jsx(kt,{present:n||i.open,children:s.jsx(ko,{asChild:!0,container:o,children:r})})})};Vd.displayName=pa;var _r="TooltipContent",Hd=p.forwardRef((e,t)=>{const n=yg(_r,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,a=Co(_r,e.__scopeTooltip);return s.jsx(kt,{present:r||a.open,children:a.disableHoverableContent?s.jsx(Gd,{side:o,...i,ref:t}):s.jsx(bg,{side:o,...i,ref:t})})}),bg=p.forwardRef((e,t)=>{const n=Co(_r,e.__scopeTooltip),r=ua(_r,e.__scopeTooltip),o=p.useRef(null),i=Oe(t,o),[a,c]=p.useState(null),{trigger:l,onClose:u}=n,h=o.current,{onPointerInTransitChange:d}=r,f=p.useCallback(()=>{c(null),d(!1)},[d]),m=p.useCallback((S,v)=>{const b=S.currentTarget,w={x:S.clientX,y:S.clientY},j=kg(w,b.getBoundingClientRect()),C=Cg(w,j),x=jg(v.getBoundingClientRect()),E=Tg([...C,...x]);c(E),d(!0)},[d]);return p.useEffect(()=>()=>f(),[f]),p.useEffect(()=>{if(l&&h){const S=b=>m(b,h),v=b=>m(b,l);return l.addEventListener("pointerleave",S),h.addEventListener("pointerleave",v),()=>{l.removeEventListener("pointerleave",S),h.removeEventListener("pointerleave",v)}}},[l,h,m,f]),p.useEffect(()=>{if(a){const S=v=>{const b=v.target,w={x:v.clientX,y:v.clientY},j=(l==null?void 0:l.contains(b))||(h==null?void 0:h.contains(b)),C=!Eg(w,a);j?f():C&&(f(),u())};return document.addEventListener("pointermove",S),()=>document.removeEventListener("pointermove",S)}},[l,h,a,u,f]),s.jsx(Gd,{...e,ref:i})}),[xg,vg]=Cs(co,{isInside:!1}),Sg=Ah("TooltipContent"),Gd=p.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:a,...c}=e,l=Co(_r,n),u=js(n),{onClose:h}=l;return p.useEffect(()=>(document.addEventListener(Di,h),()=>document.removeEventListener(Di,h)),[h]),p.useEffect(()=>{if(l.trigger){const d=f=>{const m=f.target;m!=null&&m.contains(l.trigger)&&h()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,h]),s.jsx(So,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:a,onFocusOutside:d=>d.preventDefault(),onDismiss:h,children:s.jsxs(ca,{"data-state":l.stateAttribute,...u,...c,ref:t,style:{...c.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(Sg,{children:r}),s.jsx(xg,{scope:n,isInside:!0,children:s.jsx(pg,{id:l.contentId,role:"tooltip",children:o||r})})]})})});Hd.displayName=_r;var Qd="TooltipArrow",wg=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=js(n);return vg(Qd,n).isInside?null:s.jsx(la,{...o,...r,ref:t})});wg.displayName=Qd;function kg(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 Cg(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 jg(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 Eg(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const c=t[i],l=t[a],u=c.x,h=c.y,d=l.x,f=l.y;h>r!=f>r&&n<(d-u)*(r-h)/(f-h)+u&&(o=!o)}return o}function Tg(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),Ag(t)}function Ag(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],a=t[t.length-2];if((i.x-a.x)*(o.y-a.y)>=(i.y-a.y)*(o.x-a.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],a=n[n.length-2];if((i.x-a.x)*(o.y-a.y)>=(i.y-a.y)*(o.x-a.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 Rg=Ud,Og=Wd,_g=Kd,Pg=Vd,Ig=Hd;function Jd({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:i=200,container:a}){return s.jsxs(Og,{delayDuration:i,children:[s.jsx(_g,{asChild:!0,children:t}),s.jsx(Pg,{container:a,children:s.jsx(Ig,{side:n,align:r,sideOffset:o,style:{background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.sm,padding:`${be[1]} ${be[2]}`,fontSize:Ze.sm,boxShadow:pe("shadowMd"),zIndex:io.tooltip,userSelect:"none"},children:e})})]})}const Dg=Rg;var qs="focusScope.autoFocusOnMount",Us="focusScope.autoFocusOnUnmount",Rc={bubbles:!1,cancelable:!0},$g="FocusScope",Es=p.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...a}=e,[c,l]=p.useState(null),u=yn(o),h=yn(i),d=p.useRef(null),f=Oe(t,v=>l(v)),m=p.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;p.useEffect(()=>{if(r){let v=function(C){if(m.paused||!c)return;const x=C.target;c.contains(x)?d.current=x:sn(d.current,{select:!0})},b=function(C){if(m.paused||!c)return;const x=C.relatedTarget;x!==null&&(c.contains(x)||sn(d.current,{select:!0}))},w=function(C){if(document.activeElement===document.body)for(const E of C)E.removedNodes.length>0&&sn(c)};document.addEventListener("focusin",v),document.addEventListener("focusout",b);const j=new MutationObserver(w);return c&&j.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",v),document.removeEventListener("focusout",b),j.disconnect()}}},[r,c,m.paused]),p.useEffect(()=>{if(c){_c.add(m);const v=document.activeElement;if(!c.contains(v)){const w=new CustomEvent(qs,Rc);c.addEventListener(qs,u),c.dispatchEvent(w),w.defaultPrevented||(Mg(zg(Yd(c)),{select:!0}),document.activeElement===v&&sn(c))}return()=>{c.removeEventListener(qs,u),setTimeout(()=>{const w=new CustomEvent(Us,Rc);c.addEventListener(Us,h),c.dispatchEvent(w),w.defaultPrevented||sn(v??document.body,{select:!0}),c.removeEventListener(Us,h),_c.remove(m)},0)}}},[c,u,h,m]);const S=p.useCallback(v=>{if(!n&&!r||m.paused)return;const b=v.key==="Tab"&&!v.altKey&&!v.ctrlKey&&!v.metaKey,w=document.activeElement;if(b&&w){const j=v.currentTarget,[C,x]=Lg(j);C&&x?!v.shiftKey&&w===x?(v.preventDefault(),n&&sn(C,{select:!0})):v.shiftKey&&w===C&&(v.preventDefault(),n&&sn(x,{select:!0})):w===j&&v.preventDefault()}},[n,r,m.paused]);return s.jsx(Te.div,{tabIndex:-1,...a,ref:f,onKeyDown:S})});Es.displayName=$g;function Mg(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(sn(r,{select:t}),document.activeElement!==n)return}function Lg(e){const t=Yd(e),n=Oc(t,e),r=Oc(t.reverse(),e);return[n,r]}function Yd(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 Oc(e,t){for(const n of e)if(!Ng(n,{upTo:t}))return n}function Ng(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 Bg(e){return e instanceof HTMLInputElement&&"select"in e}function sn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Bg(e)&&t&&e.select()}}var _c=Fg();function Fg(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Pc(e,t),e.unshift(t)},remove(t){var n;e=Pc(e,t),(n=e[0])==null||n.resume()}}}function Pc(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function zg(e){return e.filter(t=>t.tagName!=="A")}var Ws=0;function fa(){p.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Ic()),document.body.insertAdjacentElement("beforeend",e[1]??Ic()),Ws++,()=>{Ws===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Ws--}},[])}function Ic(){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 zt=function(){return zt=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},zt.apply(this,arguments)};function Xd(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 qg(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 Zo="right-scroll-bar-position",es="width-before-scroll-bar",Ug="with-scroll-bars-hidden",Wg="--removed-body-scroll-bar-size";function Ks(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Kg(e,t){var n=p.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 Vg=typeof window<"u"?p.useLayoutEffect:p.useEffect,Dc=new WeakMap;function Hg(e,t){var n=Kg(null,function(r){return e.forEach(function(o){return Ks(o,r)})});return Vg(function(){var r=Dc.get(n);if(r){var o=new Set(r),i=new Set(e),a=n.current;o.forEach(function(c){i.has(c)||Ks(c,null)}),i.forEach(function(c){o.has(c)||Ks(c,a)})}Dc.set(n,e)},[e]),n}function Gg(e){return e}function Qg(e,t){t===void 0&&(t=Gg);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 a=t(i,r);return n.push(a),function(){n=n.filter(function(c){return c!==a})}},assignSyncMedium:function(i){for(r=!0;n.length;){var a=n;n=[],a.forEach(i)}n={push:function(c){return i(c)},filter:function(){return n}}},assignMedium:function(i){r=!0;var a=[];if(n.length){var c=n;n=[],c.forEach(i),a=n}var l=function(){var h=a;a=[],h.forEach(i)},u=function(){return Promise.resolve().then(l)};u(),n={push:function(h){a.push(h),u()},filter:function(h){return a=a.filter(h),n}}}};return o}function Jg(e){e===void 0&&(e={});var t=Qg(null);return t.options=zt({async:!0,ssr:!1},e),t}var Zd=function(e){var t=e.sideCar,n=Xd(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 p.createElement(r,zt({},n))};Zd.isSideCarExport=!0;function Yg(e,t){return e.useMedium(t),Zd}var eu=Jg(),Vs=function(){},Ts=p.forwardRef(function(e,t){var n=p.useRef(null),r=p.useState({onScrollCapture:Vs,onWheelCapture:Vs,onTouchMoveCapture:Vs}),o=r[0],i=r[1],a=e.forwardProps,c=e.children,l=e.className,u=e.removeScrollBar,h=e.enabled,d=e.shards,f=e.sideCar,m=e.noRelative,S=e.noIsolation,v=e.inert,b=e.allowPinchZoom,w=e.as,j=w===void 0?"div":w,C=e.gapMode,x=Xd(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),E=f,P=Hg([n,t]),A=zt(zt({},x),o);return p.createElement(p.Fragment,null,h&&p.createElement(E,{sideCar:eu,removeScrollBar:u,shards:d,noRelative:m,noIsolation:S,inert:v,setCallbacks:i,allowPinchZoom:!!b,lockRef:n,gapMode:C}),a?p.cloneElement(p.Children.only(c),zt(zt({},A),{ref:P})):p.createElement(j,zt({},A,{className:l,ref:P}),c))});Ts.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Ts.classNames={fullWidth:es,zeroRight:Zo};var Xg=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Zg(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Xg();return t&&e.setAttribute("nonce",t),e}function ey(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function ty(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var ny=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Zg())&&(ey(t,n),ty(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},ry=function(){var e=ny();return function(t,n){p.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},tu=function(){var e=ry(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},oy={left:0,top:0,right:0,gap:0},Hs=function(e){return parseInt(e||"",10)||0},sy=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[Hs(n),Hs(r),Hs(o)]},iy=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return oy;var t=sy(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])}},ay=tu(),fr="data-scroll-locked",cy=function(e,t,n,r){var o=e.left,i=e.top,a=e.right,c=e.gap;return n===void 0&&(n="margin"),`
11
+ .`.concat(Ug,` {
12
12
  overflow: hidden `).concat(r,`;
13
13
  padding-right: `).concat(c,"px ").concat(r,`;
14
14
  }
@@ -42,405 +42,405 @@ var Rf=Object.defineProperty;var ec=e=>{throw TypeError(e)};var Of=(e,t,n)=>t in
42
42
  }
43
43
 
44
44
  body[`).concat(fr,`] {
45
- `).concat(Ug,": ").concat(c,`px;
45
+ `).concat(Wg,": ").concat(c,`px;
46
46
  }
47
- `)},$c=function(){var e=parseInt(document.body.getAttribute(fr)||"0",10);return isFinite(e)?e:0},cy=function(){p.useEffect(function(){return document.body.setAttribute(fr,($c()+1).toString()),function(){var e=$c()-1;e<=0?document.body.removeAttribute(fr):document.body.setAttribute(fr,e.toString())}},[])},ly=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;cy();var i=p.useMemo(function(){return sy(o)},[o]);return p.createElement(iy,{styles:ay(i,!t,o,n?"":"!important")})},Mi=!1;if(typeof window<"u")try{var zo=Object.defineProperty({},"passive",{get:function(){return Mi=!0,!0}});window.addEventListener("test",zo,zo),window.removeEventListener("test",zo,zo)}catch{Mi=!1}var er=Mi?{passive:!1}:!1,dy=function(e){return e.tagName==="TEXTAREA"},tu=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!dy(e)&&n[t]==="visible")},uy=function(e){return tu(e,"overflowY")},py=function(e){return tu(e,"overflowX")},Mc=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=nu(e,r);if(o){var i=ru(e,r),a=i[1],c=i[2];if(a>c)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},fy=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},hy=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},nu=function(e,t){return e==="v"?uy(t):py(t)},ru=function(e,t){return e==="v"?fy(t):hy(t)},my=function(e,t){return e==="h"&&t==="rtl"?-1:1},gy=function(e,t,n,r,o){var i=my(e,window.getComputedStyle(t).direction),a=i*r,c=n.target,l=t.contains(c),u=!1,h=a>0,d=0,f=0;do{if(!c)break;var m=ru(e,c),S=m[0],v=m[1],b=m[2],w=v-b-i*S;(S||w)&&nu(e,c)&&(d+=w,f+=S);var j=c.parentNode;c=j&&j.nodeType===Node.DOCUMENT_FRAGMENT_NODE?j.host:j}while(!l&&c!==document.body||l&&(t.contains(c)||t===c));return(h&&Math.abs(d)<1||!h&&Math.abs(f)<1)&&(u=!0),u},qo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Lc=function(e){return[e.deltaX,e.deltaY]},Nc=function(e){return e&&"current"in e?e.current:e},yy=function(e,t){return e[0]===t[0]&&e[1]===t[1]},by=function(e){return`
47
+ `)},$c=function(){var e=parseInt(document.body.getAttribute(fr)||"0",10);return isFinite(e)?e:0},ly=function(){p.useEffect(function(){return document.body.setAttribute(fr,($c()+1).toString()),function(){var e=$c()-1;e<=0?document.body.removeAttribute(fr):document.body.setAttribute(fr,e.toString())}},[])},dy=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;ly();var i=p.useMemo(function(){return iy(o)},[o]);return p.createElement(ay,{styles:cy(i,!t,o,n?"":"!important")})},Mi=!1;if(typeof window<"u")try{var zo=Object.defineProperty({},"passive",{get:function(){return Mi=!0,!0}});window.addEventListener("test",zo,zo),window.removeEventListener("test",zo,zo)}catch{Mi=!1}var er=Mi?{passive:!1}:!1,uy=function(e){return e.tagName==="TEXTAREA"},nu=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!uy(e)&&n[t]==="visible")},py=function(e){return nu(e,"overflowY")},fy=function(e){return nu(e,"overflowX")},Mc=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=ru(e,r);if(o){var i=ou(e,r),a=i[1],c=i[2];if(a>c)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},hy=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},my=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},ru=function(e,t){return e==="v"?py(t):fy(t)},ou=function(e,t){return e==="v"?hy(t):my(t)},gy=function(e,t){return e==="h"&&t==="rtl"?-1:1},yy=function(e,t,n,r,o){var i=gy(e,window.getComputedStyle(t).direction),a=i*r,c=n.target,l=t.contains(c),u=!1,h=a>0,d=0,f=0;do{if(!c)break;var m=ou(e,c),S=m[0],v=m[1],b=m[2],w=v-b-i*S;(S||w)&&ru(e,c)&&(d+=w,f+=S);var j=c.parentNode;c=j&&j.nodeType===Node.DOCUMENT_FRAGMENT_NODE?j.host:j}while(!l&&c!==document.body||l&&(t.contains(c)||t===c));return(h&&Math.abs(d)<1||!h&&Math.abs(f)<1)&&(u=!0),u},qo=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Lc=function(e){return[e.deltaX,e.deltaY]},Nc=function(e){return e&&"current"in e?e.current:e},by=function(e,t){return e[0]===t[0]&&e[1]===t[1]},xy=function(e){return`
48
48
  .block-interactivity-`.concat(e,` {pointer-events: none;}
49
49
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
50
- `)},xy=0,tr=[];function vy(e){var t=p.useRef([]),n=p.useRef([0,0]),r=p.useRef(),o=p.useState(xy++)[0],i=p.useState(eu)[0],a=p.useRef(e);p.useEffect(function(){a.current=e},[e]),p.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var v=zg([e.lockRef.current],(e.shards||[]).map(Nc),!0).filter(Boolean);return v.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),v.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=p.useCallback(function(v,b){if("touches"in v&&v.touches.length===2||v.type==="wheel"&&v.ctrlKey)return!a.current.allowPinchZoom;var w=qo(v),j=n.current,C="deltaX"in v?v.deltaX:j[0]-w[0],x="deltaY"in v?v.deltaY:j[1]-w[1],E,P=v.target,A=Math.abs(C)>Math.abs(x)?"h":"v";if("touches"in v&&A==="h"&&P.type==="range")return!1;var g=window.getSelection(),I=g&&g.anchorNode,T=I?I===P||I.contains(P):!1;if(T)return!1;var O=Mc(A,P);if(!O)return!0;if(O?E=A:(E=A==="v"?"h":"v",O=Mc(A,P)),!O)return!1;if(!r.current&&"changedTouches"in v&&(C||x)&&(r.current=E),!E)return!0;var _=r.current||E;return gy(_,b,v,_==="h"?C:x)},[]),l=p.useCallback(function(v){var b=v;if(!(!tr.length||tr[tr.length-1]!==i)){var w="deltaY"in b?Lc(b):qo(b),j=t.current.filter(function(E){return E.name===b.type&&(E.target===b.target||b.target===E.shadowParent)&&yy(E.delta,w)})[0];if(j&&j.should){b.cancelable&&b.preventDefault();return}if(!j){var C=(a.current.shards||[]).map(Nc).filter(Boolean).filter(function(E){return E.contains(b.target)}),x=C.length>0?c(b,C[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),u=p.useCallback(function(v,b,w,j){var C={name:v,delta:b,target:w,should:j,shadowParent:Sy(w)};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(x){return x!==C})},1)},[]),h=p.useCallback(function(v){n.current=qo(v),r.current=void 0},[]),d=p.useCallback(function(v){u(v.type,Lc(v),v.target,c(v,e.lockRef.current))},[]),f=p.useCallback(function(v){u(v.type,qo(v),v.target,c(v,e.lockRef.current))},[]);p.useEffect(function(){return tr.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,er),document.addEventListener("touchmove",l,er),document.addEventListener("touchstart",h,er),function(){tr=tr.filter(function(v){return v!==i}),document.removeEventListener("wheel",l,er),document.removeEventListener("touchmove",l,er),document.removeEventListener("touchstart",h,er)}},[]);var m=e.removeScrollBar,S=e.inert;return p.createElement(p.Fragment,null,S?p.createElement(i,{styles:by(o)}):null,m?p.createElement(ly,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Sy(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const wy=Jg(Zd,vy);var As=p.forwardRef(function(e,t){return p.createElement(Ts,zt({},e,{ref:t,sideCar:wy}))});As.classNames=Ts.classNames;var ky=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},nr=new WeakMap,Uo=new WeakMap,Wo={},Gs=0,ou=function(e){return e&&(e.host||ou(e.parentNode))},Cy=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=ou(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})},jy=function(e,t,n,r){var o=Cy(t,Array.isArray(e)?e:[e]);Wo[n]||(Wo[n]=new WeakMap);var i=Wo[n],a=[],c=new Set,l=new Set(o),u=function(d){!d||c.has(d)||(c.add(d),u(d.parentNode))};o.forEach(u);var h=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(c.has(f))h(f);else try{var m=f.getAttribute(r),S=m!==null&&m!=="false",v=(nr.get(f)||0)+1,b=(i.get(f)||0)+1;nr.set(f,v),i.set(f,b),a.push(f),v===1&&S&&Uo.set(f,!0),b===1&&f.setAttribute(n,"true"),S||f.setAttribute(r,"true")}catch(w){console.error("aria-hidden: cannot operate on ",f,w)}})};return h(t),c.clear(),Gs++,function(){a.forEach(function(d){var f=nr.get(d)-1,m=i.get(d)-1;nr.set(d,f),i.set(d,m),f||(Uo.has(d)||d.removeAttribute(r),Uo.delete(d)),m||d.removeAttribute(n)}),Gs--,Gs||(nr=new WeakMap,nr=new WeakMap,Uo=new WeakMap,Wo={})}},ha=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=ky(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),jy(r,o,n,"aria-hidden")):function(){return null}},Rs="Dialog",[su]=kn(Rs),[Ey,$t]=su(Rs),iu=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:a=!0}=e,c=p.useRef(null),l=p.useRef(null),[u,h]=da({prop:r,defaultProp:o??!1,onChange:i,caller:Rs});return s.jsx(Ey,{scope:t,triggerRef:c,contentRef:l,contentId:to(),titleId:to(),descriptionId:to(),open:u,onOpenChange:h,onOpenToggle:p.useCallback(()=>h(d=>!d),[h]),modal:a,children:n})};iu.displayName=Rs;var au="DialogTrigger",Ty=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(au,n),i=Oe(t,o.triggerRef);return s.jsx(Te.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":ya(o.open),...r,ref:i,onClick:de(e.onClick,o.onOpenToggle)})});Ty.displayName=au;var ma="DialogPortal",[Ay,cu]=su(ma,{forceMount:void 0}),lu=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=$t(ma,t);return s.jsx(Ay,{scope:t,forceMount:n,children:p.Children.map(r,a=>s.jsx(kt,{present:n||i.open,children:s.jsx(ko,{asChild:!0,container:o,children:a})}))})};lu.displayName=ma;var ls="DialogOverlay",du=p.forwardRef((e,t)=>{const n=cu(ls,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=$t(ls,e.__scopeDialog);return i.modal?s.jsx(kt,{present:r||i.open,children:s.jsx(Oy,{...o,ref:t})}):null});du.displayName=ls;var Ry=Rr("DialogOverlay.RemoveScroll"),Oy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(ls,n);return s.jsx(As,{as:Ry,allowPinchZoom:!0,shards:[o.contentRef],children:s.jsx(Te.div,{"data-state":ya(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Kn="DialogContent",uu=p.forwardRef((e,t)=>{const n=cu(Kn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=$t(Kn,e.__scopeDialog);return s.jsx(kt,{present:r||i.open,children:i.modal?s.jsx(_y,{...o,ref:t}):s.jsx(Py,{...o,ref:t})})});uu.displayName=Kn;var _y=p.forwardRef((e,t)=>{const n=$t(Kn,e.__scopeDialog),r=p.useRef(null),o=Oe(t,n.contentRef,r);return p.useEffect(()=>{const i=r.current;if(i)return ha(i)},[]),s.jsx(pu,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,c=a.button===0&&a.ctrlKey===!0;(a.button===2||c)&&i.preventDefault()}),onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault())})}),Py=p.forwardRef((e,t)=>{const n=$t(Kn,e.__scopeDialog),r=p.useRef(!1),o=p.useRef(!1);return s.jsx(pu,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,c;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(r.current||(c=n.triggerRef.current)==null||c.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=i.target;((u=n.triggerRef.current)==null?void 0:u.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),pu=p.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...a}=e,c=$t(Kn,n),l=p.useRef(null),u=Oe(t,l);return fa(),s.jsxs(s.Fragment,{children:[s.jsx(Es,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(So,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":ya(c.open),...a,ref:u,onDismiss:()=>c.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx($y,{titleId:c.titleId}),s.jsx(Ly,{contentRef:l,descriptionId:c.descriptionId})]})]})}),ga="DialogTitle",fu=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(ga,n);return s.jsx(Te.h2,{id:o.titleId,...r,ref:t})});fu.displayName=ga;var hu="DialogDescription",Iy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(hu,n);return s.jsx(Te.p,{id:o.descriptionId,...r,ref:t})});Iy.displayName=hu;var mu="DialogClose",Dy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(mu,n);return s.jsx(Te.button,{type:"button",...r,ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))})});Dy.displayName=mu;function ya(e){return e?"open":"closed"}var gu="DialogTitleWarning",[Oj,yu]=kh(gu,{contentName:Kn,titleName:ga,docsSlug:"dialog"}),$y=({titleId:e})=>{const t=yu(gu),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
50
+ `)},vy=0,tr=[];function Sy(e){var t=p.useRef([]),n=p.useRef([0,0]),r=p.useRef(),o=p.useState(vy++)[0],i=p.useState(tu)[0],a=p.useRef(e);p.useEffect(function(){a.current=e},[e]),p.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var v=qg([e.lockRef.current],(e.shards||[]).map(Nc),!0).filter(Boolean);return v.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),v.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var c=p.useCallback(function(v,b){if("touches"in v&&v.touches.length===2||v.type==="wheel"&&v.ctrlKey)return!a.current.allowPinchZoom;var w=qo(v),j=n.current,C="deltaX"in v?v.deltaX:j[0]-w[0],x="deltaY"in v?v.deltaY:j[1]-w[1],E,P=v.target,A=Math.abs(C)>Math.abs(x)?"h":"v";if("touches"in v&&A==="h"&&P.type==="range")return!1;var g=window.getSelection(),I=g&&g.anchorNode,T=I?I===P||I.contains(P):!1;if(T)return!1;var O=Mc(A,P);if(!O)return!0;if(O?E=A:(E=A==="v"?"h":"v",O=Mc(A,P)),!O)return!1;if(!r.current&&"changedTouches"in v&&(C||x)&&(r.current=E),!E)return!0;var _=r.current||E;return yy(_,b,v,_==="h"?C:x)},[]),l=p.useCallback(function(v){var b=v;if(!(!tr.length||tr[tr.length-1]!==i)){var w="deltaY"in b?Lc(b):qo(b),j=t.current.filter(function(E){return E.name===b.type&&(E.target===b.target||b.target===E.shadowParent)&&by(E.delta,w)})[0];if(j&&j.should){b.cancelable&&b.preventDefault();return}if(!j){var C=(a.current.shards||[]).map(Nc).filter(Boolean).filter(function(E){return E.contains(b.target)}),x=C.length>0?c(b,C[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),u=p.useCallback(function(v,b,w,j){var C={name:v,delta:b,target:w,should:j,shadowParent:wy(w)};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(x){return x!==C})},1)},[]),h=p.useCallback(function(v){n.current=qo(v),r.current=void 0},[]),d=p.useCallback(function(v){u(v.type,Lc(v),v.target,c(v,e.lockRef.current))},[]),f=p.useCallback(function(v){u(v.type,qo(v),v.target,c(v,e.lockRef.current))},[]);p.useEffect(function(){return tr.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,er),document.addEventListener("touchmove",l,er),document.addEventListener("touchstart",h,er),function(){tr=tr.filter(function(v){return v!==i}),document.removeEventListener("wheel",l,er),document.removeEventListener("touchmove",l,er),document.removeEventListener("touchstart",h,er)}},[]);var m=e.removeScrollBar,S=e.inert;return p.createElement(p.Fragment,null,S?p.createElement(i,{styles:xy(o)}):null,m?p.createElement(dy,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function wy(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ky=Yg(eu,Sy);var As=p.forwardRef(function(e,t){return p.createElement(Ts,zt({},e,{ref:t,sideCar:ky}))});As.classNames=Ts.classNames;var Cy=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},nr=new WeakMap,Uo=new WeakMap,Wo={},Gs=0,su=function(e){return e&&(e.host||su(e.parentNode))},jy=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=su(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})},Ey=function(e,t,n,r){var o=jy(t,Array.isArray(e)?e:[e]);Wo[n]||(Wo[n]=new WeakMap);var i=Wo[n],a=[],c=new Set,l=new Set(o),u=function(d){!d||c.has(d)||(c.add(d),u(d.parentNode))};o.forEach(u);var h=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(c.has(f))h(f);else try{var m=f.getAttribute(r),S=m!==null&&m!=="false",v=(nr.get(f)||0)+1,b=(i.get(f)||0)+1;nr.set(f,v),i.set(f,b),a.push(f),v===1&&S&&Uo.set(f,!0),b===1&&f.setAttribute(n,"true"),S||f.setAttribute(r,"true")}catch(w){console.error("aria-hidden: cannot operate on ",f,w)}})};return h(t),c.clear(),Gs++,function(){a.forEach(function(d){var f=nr.get(d)-1,m=i.get(d)-1;nr.set(d,f),i.set(d,m),f||(Uo.has(d)||d.removeAttribute(r),Uo.delete(d)),m||d.removeAttribute(n)}),Gs--,Gs||(nr=new WeakMap,nr=new WeakMap,Uo=new WeakMap,Wo={})}},ha=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=Cy(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Ey(r,o,n,"aria-hidden")):function(){return null}},Rs="Dialog",[iu]=kn(Rs),[Ty,$t]=iu(Rs),au=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:a=!0}=e,c=p.useRef(null),l=p.useRef(null),[u,h]=da({prop:r,defaultProp:o??!1,onChange:i,caller:Rs});return s.jsx(Ty,{scope:t,triggerRef:c,contentRef:l,contentId:to(),titleId:to(),descriptionId:to(),open:u,onOpenChange:h,onOpenToggle:p.useCallback(()=>h(d=>!d),[h]),modal:a,children:n})};au.displayName=Rs;var cu="DialogTrigger",Ay=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(cu,n),i=Oe(t,o.triggerRef);return s.jsx(Te.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":ya(o.open),...r,ref:i,onClick:de(e.onClick,o.onOpenToggle)})});Ay.displayName=cu;var ma="DialogPortal",[Ry,lu]=iu(ma,{forceMount:void 0}),du=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=$t(ma,t);return s.jsx(Ry,{scope:t,forceMount:n,children:p.Children.map(r,a=>s.jsx(kt,{present:n||i.open,children:s.jsx(ko,{asChild:!0,container:o,children:a})}))})};du.displayName=ma;var ls="DialogOverlay",uu=p.forwardRef((e,t)=>{const n=lu(ls,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=$t(ls,e.__scopeDialog);return i.modal?s.jsx(kt,{present:r||i.open,children:s.jsx(_y,{...o,ref:t})}):null});uu.displayName=ls;var Oy=Rr("DialogOverlay.RemoveScroll"),_y=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(ls,n);return s.jsx(As,{as:Oy,allowPinchZoom:!0,shards:[o.contentRef],children:s.jsx(Te.div,{"data-state":ya(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Kn="DialogContent",pu=p.forwardRef((e,t)=>{const n=lu(Kn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=$t(Kn,e.__scopeDialog);return s.jsx(kt,{present:r||i.open,children:i.modal?s.jsx(Py,{...o,ref:t}):s.jsx(Iy,{...o,ref:t})})});pu.displayName=Kn;var Py=p.forwardRef((e,t)=>{const n=$t(Kn,e.__scopeDialog),r=p.useRef(null),o=Oe(t,n.contentRef,r);return p.useEffect(()=>{const i=r.current;if(i)return ha(i)},[]),s.jsx(fu,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,c=a.button===0&&a.ctrlKey===!0;(a.button===2||c)&&i.preventDefault()}),onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault())})}),Iy=p.forwardRef((e,t)=>{const n=$t(Kn,e.__scopeDialog),r=p.useRef(!1),o=p.useRef(!1);return s.jsx(fu,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,c;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(r.current||(c=n.triggerRef.current)==null||c.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=i.target;((u=n.triggerRef.current)==null?void 0:u.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),fu=p.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...a}=e,c=$t(Kn,n),l=p.useRef(null),u=Oe(t,l);return fa(),s.jsxs(s.Fragment,{children:[s.jsx(Es,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(So,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":ya(c.open),...a,ref:u,onDismiss:()=>c.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx(My,{titleId:c.titleId}),s.jsx(Ny,{contentRef:l,descriptionId:c.descriptionId})]})]})}),ga="DialogTitle",hu=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(ga,n);return s.jsx(Te.h2,{id:o.titleId,...r,ref:t})});hu.displayName=ga;var mu="DialogDescription",Dy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(mu,n);return s.jsx(Te.p,{id:o.descriptionId,...r,ref:t})});Dy.displayName=mu;var gu="DialogClose",$y=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=$t(gu,n);return s.jsx(Te.button,{type:"button",...r,ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))})});$y.displayName=gu;function ya(e){return e?"open":"closed"}var yu="DialogTitleWarning",[_j,bu]=Ch(yu,{contentName:Kn,titleName:ga,docsSlug:"dialog"}),My=({titleId:e})=>{const t=bu(yu),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
51
51
 
52
52
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
53
53
 
54
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return p.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},My="DialogDescriptionWarning",Ly=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${yu(My).contentName}}.`;return p.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},Ny=iu,By=lu,Fy=du,zy=uu,qy=fu;function bu(e){const t=e+"CollectionProvider",[n,r]=kn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=v=>{const{scope:b,children:w}=v,j=qe.useRef(null),C=qe.useRef(new Map).current;return s.jsx(o,{scope:b,itemMap:C,collectionRef:j,children:w})};a.displayName=t;const c=e+"CollectionSlot",l=Rr(c),u=qe.forwardRef((v,b)=>{const{scope:w,children:j}=v,C=i(c,w),x=Oe(b,C.collectionRef);return s.jsx(l,{ref:x,children:j})});u.displayName=c;const h=e+"CollectionItemSlot",d="data-radix-collection-item",f=Rr(h),m=qe.forwardRef((v,b)=>{const{scope:w,children:j,...C}=v,x=qe.useRef(null),E=Oe(b,x),P=i(h,w);return qe.useEffect(()=>(P.itemMap.set(x,{ref:x,...C}),()=>void P.itemMap.delete(x))),s.jsx(f,{[d]:"",ref:E,children:j})});m.displayName=h;function S(v){const b=i(e+"CollectionConsumer",v);return qe.useCallback(()=>{const j=b.collectionRef.current;if(!j)return[];const C=Array.from(j.querySelectorAll(`[${d}]`));return Array.from(b.itemMap.values()).sort((P,A)=>C.indexOf(P.ref.current)-C.indexOf(A.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:a,Slot:u,ItemSlot:m},S,r]}var Uy=p.createContext(void 0);function Wy(e){const t=p.useContext(Uy);return e||t||"ltr"}var Qs="rovingFocusGroup.onEntryFocus",Ky={bubbles:!1,cancelable:!0},jo="RovingFocusGroup",[Li,xu,Vy]=bu(jo),[Hy,vu]=kn(jo,[Vy]),[Gy,Qy]=Hy(jo),Su=p.forwardRef((e,t)=>s.jsx(Li.Provider,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Li.Slot,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Jy,{...e,ref:t})})}));Su.displayName=jo;var Jy=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:a,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:h=!1,...d}=e,f=p.useRef(null),m=Oe(t,f),S=Wy(i),[v,b]=da({prop:a,defaultProp:c??null,onChange:l,caller:jo}),[w,j]=p.useState(!1),C=yn(u),x=xu(n),E=p.useRef(!1),[P,A]=p.useState(0);return p.useEffect(()=>{const g=f.current;if(g)return g.addEventListener(Qs,C),()=>g.removeEventListener(Qs,C)},[C]),s.jsx(Gy,{scope:n,orientation:r,dir:S,loop:o,currentTabStopId:v,onItemFocus:p.useCallback(g=>b(g),[b]),onItemShiftTab:p.useCallback(()=>j(!0),[]),onFocusableItemAdd:p.useCallback(()=>A(g=>g+1),[]),onFocusableItemRemove:p.useCallback(()=>A(g=>g-1),[]),children:s.jsx(Te.div,{tabIndex:w||P===0?-1:0,"data-orientation":r,...d,ref:m,style:{outline:"none",...e.style},onMouseDown:de(e.onMouseDown,()=>{E.current=!0}),onFocus:de(e.onFocus,g=>{const I=!E.current;if(g.target===g.currentTarget&&I&&!w){const T=new CustomEvent(Qs,Ky);if(g.currentTarget.dispatchEvent(T),!T.defaultPrevented){const O=x().filter(J=>J.focusable),_=O.find(J=>J.active),M=O.find(J=>J.id===v),G=[_,M,...O].filter(Boolean).map(J=>J.ref.current);Cu(G,h)}}E.current=!1}),onBlur:de(e.onBlur,()=>j(!1))})})}),wu="RovingFocusGroupItem",ku=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,children:a,...c}=e,l=to(),u=i||l,h=Qy(wu,n),d=h.currentTabStopId===u,f=xu(n),{onFocusableItemAdd:m,onFocusableItemRemove:S,currentTabStopId:v}=h;return p.useEffect(()=>{if(r)return m(),()=>S()},[r,m,S]),s.jsx(Li.ItemSlot,{scope:n,id:u,focusable:r,active:o,children:s.jsx(Te.span,{tabIndex:d?0:-1,"data-orientation":h.orientation,...c,ref:t,onMouseDown:de(e.onMouseDown,b=>{r?h.onItemFocus(u):b.preventDefault()}),onFocus:de(e.onFocus,()=>h.onItemFocus(u)),onKeyDown:de(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){h.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const w=Zy(b,h.orientation,h.dir);if(w!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let C=f().filter(x=>x.focusable).map(x=>x.ref.current);if(w==="last")C.reverse();else if(w==="prev"||w==="next"){w==="prev"&&C.reverse();const x=C.indexOf(b.currentTarget);C=h.loop?eb(C,x+1):C.slice(x+1)}setTimeout(()=>Cu(C))}}),children:typeof a=="function"?a({isCurrentTabStop:d,hasTabStop:v!=null}):a})})});ku.displayName=wu;var Yy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Xy(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Zy(e,t,n){const r=Xy(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Yy[r]}function Cu(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function eb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var tb=Su,nb=ku,Ni=["Enter"," "],rb=["ArrowDown","PageUp","Home"],ju=["ArrowUp","PageDown","End"],ob=[...rb,...ju],sb={ltr:[...Ni,"ArrowRight"],rtl:[...Ni,"ArrowLeft"]},ib={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Os="Menu",[lo,ab,cb]=bu(Os),[Gn,Eu]=kn(Os,[cb,Mr,vu]),ba=Mr(),Tu=vu(),[_j,Qn]=Gn(Os),[Pj,Eo]=Gn(Os),lb="MenuAnchor",xa=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ba(n);return s.jsx(ks,{...o,...r,ref:t})});xa.displayName=lb;var va="MenuPortal",[db,Au]=Gn(va,{forceMount:void 0}),Ru=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Qn(va,t);return s.jsx(db,{scope:t,forceMount:n,children:s.jsx(kt,{present:n||i.open,children:s.jsx(ko,{asChild:!0,container:o,children:r})})})};Ru.displayName=va;var wt="MenuContent",[ub,Sa]=Gn(wt),Ou=p.forwardRef((e,t)=>{const n=Au(wt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Qn(wt,e.__scopeMenu),a=Eo(wt,e.__scopeMenu);return s.jsx(lo.Provider,{scope:e.__scopeMenu,children:s.jsx(kt,{present:r||i.open,children:s.jsx(lo.Slot,{scope:e.__scopeMenu,children:a.modal?s.jsx(pb,{...o,ref:t}):s.jsx(fb,{...o,ref:t})})})})}),pb=p.forwardRef((e,t)=>{const n=Qn(wt,e.__scopeMenu),r=p.useRef(null),o=Oe(t,r);return p.useEffect(()=>{const i=r.current;if(i)return ha(i)},[]),s.jsx(wa,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),fb=p.forwardRef((e,t)=>{const n=Qn(wt,e.__scopeMenu);return s.jsx(wa,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),hb=Rr("MenuContent.ScrollLock"),wa=p.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:c,onEntryFocus:l,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:d,onInteractOutside:f,onDismiss:m,disableOutsideScroll:S,...v}=e,b=Qn(wt,n),w=Eo(wt,n),j=ba(n),C=Tu(n),x=ab(n),[E,P]=p.useState(null),A=p.useRef(null),g=Oe(t,A,b.onContentChange),I=p.useRef(0),T=p.useRef(""),O=p.useRef(0),_=p.useRef(null),M=p.useRef("right"),q=p.useRef(0),G=S?As:p.Fragment,J=S?{as:hb,allowPinchZoom:!0}:void 0,H=$=>{var ce,ke;const X=T.current+$,W=x().filter(xe=>!xe.disabled),te=document.activeElement,F=(ce=W.find(xe=>xe.ref.current===te))==null?void 0:ce.textValue,K=W.map(xe=>xe.textValue),oe=Eb(K,X,F),ee=(ke=W.find(xe=>xe.textValue===oe))==null?void 0:ke.ref.current;(function xe(De){T.current=De,window.clearTimeout(I.current),De!==""&&(I.current=window.setTimeout(()=>xe(""),1e3))})(X),ee&&setTimeout(()=>ee.focus())};p.useEffect(()=>()=>window.clearTimeout(I.current),[]),fa();const L=p.useCallback($=>{var W,te;return M.current===((W=_.current)==null?void 0:W.side)&&Ab($,(te=_.current)==null?void 0:te.area)},[]);return s.jsx(ub,{scope:n,searchRef:T,onItemEnter:p.useCallback($=>{L($)&&$.preventDefault()},[L]),onItemLeave:p.useCallback($=>{var X;L($)||((X=A.current)==null||X.focus(),P(null))},[L]),onTriggerLeave:p.useCallback($=>{L($)&&$.preventDefault()},[L]),pointerGraceTimerRef:O,onPointerGraceIntentChange:p.useCallback($=>{_.current=$},[]),children:s.jsx(G,{...J,children:s.jsx(Es,{asChild:!0,trapped:o,onMountAutoFocus:de(i,$=>{var X;$.preventDefault(),(X=A.current)==null||X.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:s.jsx(So,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:d,onInteractOutside:f,onDismiss:m,children:s.jsx(tb,{asChild:!0,...C,dir:w.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:P,onEntryFocus:de(l,$=>{w.isUsingKeyboardRef.current||$.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(ca,{role:"menu","aria-orientation":"vertical","data-state":Vu(b.open),"data-radix-menu-content":"",dir:w.dir,...j,...v,ref:g,style:{outline:"none",...v.style},onKeyDown:de(v.onKeyDown,$=>{const W=$.target.closest("[data-radix-menu-content]")===$.currentTarget,te=$.ctrlKey||$.altKey||$.metaKey,F=$.key.length===1;W&&($.key==="Tab"&&$.preventDefault(),!te&&F&&H($.key));const K=A.current;if($.target!==K||!ob.includes($.key))return;$.preventDefault();const ee=x().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);ju.includes($.key)&&ee.reverse(),Cb(ee)}),onBlur:de(e.onBlur,$=>{$.currentTarget.contains($.target)||(window.clearTimeout(I.current),T.current="")}),onPointerMove:de(e.onPointerMove,uo($=>{const X=$.target,W=q.current!==$.clientX;if($.currentTarget.contains(X)&&W){const te=$.clientX>q.current?"right":"left";M.current=te,q.current=$.clientX}}))})})})})})})});Ou.displayName=wt;var mb="MenuGroup",ka=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{role:"group",...r,ref:t})});ka.displayName=mb;var gb="MenuLabel",_u=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{...r,ref:t})});_u.displayName=gb;var ds="MenuItem",Bc="menu.itemSelect",_s=p.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=p.useRef(null),a=Eo(ds,e.__scopeMenu),c=Sa(ds,e.__scopeMenu),l=Oe(t,i),u=p.useRef(!1),h=()=>{const d=i.current;if(!n&&d){const f=new CustomEvent(Bc,{bubbles:!0,cancelable:!0});d.addEventListener(Bc,m=>r==null?void 0:r(m),{once:!0}),gd(d,f),f.defaultPrevented?u.current=!1:a.onClose()}};return s.jsx(Pu,{...o,ref:l,disabled:n,onClick:de(e.onClick,h),onPointerDown:d=>{var f;(f=e.onPointerDown)==null||f.call(e,d),u.current=!0},onPointerUp:de(e.onPointerUp,d=>{var f;u.current||(f=d.currentTarget)==null||f.click()}),onKeyDown:de(e.onKeyDown,d=>{const f=c.searchRef.current!=="";n||f&&d.key===" "||Ni.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});_s.displayName=ds;var Pu=p.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,a=Sa(ds,n),c=Tu(n),l=p.useRef(null),u=Oe(t,l),[h,d]=p.useState(!1),[f,m]=p.useState("");return p.useEffect(()=>{const S=l.current;S&&m((S.textContent??"").trim())},[i.children]),s.jsx(lo.ItemSlot,{scope:n,disabled:r,textValue:o??f,children:s.jsx(nb,{asChild:!0,...c,focusable:!r,children:s.jsx(Te.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:u,onPointerMove:de(e.onPointerMove,uo(S=>{r?a.onItemLeave(S):(a.onItemEnter(S),S.defaultPrevented||S.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:de(e.onPointerLeave,uo(S=>a.onItemLeave(S))),onFocus:de(e.onFocus,()=>d(!0)),onBlur:de(e.onBlur,()=>d(!1))})})})}),yb="MenuCheckboxItem",Iu=p.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return s.jsx(Nu,{scope:e.__scopeMenu,checked:n,children:s.jsx(_s,{role:"menuitemcheckbox","aria-checked":us(n)?"mixed":n,...o,ref:t,"data-state":ja(n),onSelect:de(o.onSelect,()=>r==null?void 0:r(us(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Iu.displayName=yb;var Du="MenuRadioGroup",[bb,xb]=Gn(Du,{value:void 0,onValueChange:()=>{}}),$u=p.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,i=yn(r);return s.jsx(bb,{scope:e.__scopeMenu,value:n,onValueChange:i,children:s.jsx(ka,{...o,ref:t})})});$u.displayName=Du;var Mu="MenuRadioItem",Lu=p.forwardRef((e,t)=>{const{value:n,...r}=e,o=xb(Mu,e.__scopeMenu),i=n===o.value;return s.jsx(Nu,{scope:e.__scopeMenu,checked:i,children:s.jsx(_s,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":ja(i),onSelect:de(r.onSelect,()=>{var a;return(a=o.onValueChange)==null?void 0:a.call(o,n)},{checkForDefaultPrevented:!1})})})});Lu.displayName=Mu;var Ca="MenuItemIndicator",[Nu,vb]=Gn(Ca,{checked:!1}),Bu=p.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=vb(Ca,n);return s.jsx(kt,{present:r||us(i.checked)||i.checked===!0,children:s.jsx(Te.span,{...o,ref:t,"data-state":ja(i.checked)})})});Bu.displayName=Ca;var Sb="MenuSeparator",Fu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Fu.displayName=Sb;var wb="MenuArrow",zu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ba(n);return s.jsx(la,{...o,...r,ref:t})});zu.displayName=wb;var kb="MenuSub",[Ij,qu]=Gn(kb),Gr="MenuSubTrigger",Uu=p.forwardRef((e,t)=>{const n=Qn(Gr,e.__scopeMenu),r=Eo(Gr,e.__scopeMenu),o=qu(Gr,e.__scopeMenu),i=Sa(Gr,e.__scopeMenu),a=p.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:l}=i,u={__scopeMenu:e.__scopeMenu},h=p.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return p.useEffect(()=>h,[h]),p.useEffect(()=>{const d=c.current;return()=>{window.clearTimeout(d),l(null)}},[c,l]),s.jsx(xa,{asChild:!0,...u,children:s.jsx(Pu,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":Vu(n.open),...e,ref:bs(t,o.onTriggerChange),onClick:d=>{var f;(f=e.onClick)==null||f.call(e,d),!(e.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:de(e.onPointerMove,uo(d=>{i.onItemEnter(d),!d.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(i.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:de(e.onPointerLeave,uo(d=>{var m,S;h();const f=(m=n.content)==null?void 0:m.getBoundingClientRect();if(f){const v=(S=n.content)==null?void 0:S.dataset.side,b=v==="right",w=b?-5:5,j=f[b?"left":"right"],C=f[b?"right":"left"];i.onPointerGraceIntentChange({area:[{x:d.clientX+w,y:d.clientY},{x:j,y:f.top},{x:C,y:f.top},{x:C,y:f.bottom},{x:j,y:f.bottom}],side:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(d),d.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:de(e.onKeyDown,d=>{var m;const f=i.searchRef.current!=="";e.disabled||f&&d.key===" "||sb[r.dir].includes(d.key)&&(n.onOpenChange(!0),(m=n.content)==null||m.focus(),d.preventDefault())})})})});Uu.displayName=Gr;var Wu="MenuSubContent",Ku=p.forwardRef((e,t)=>{const n=Au(wt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Qn(wt,e.__scopeMenu),a=Eo(wt,e.__scopeMenu),c=qu(Wu,e.__scopeMenu),l=p.useRef(null),u=Oe(t,l);return s.jsx(lo.Provider,{scope:e.__scopeMenu,children:s.jsx(kt,{present:r||i.open,children:s.jsx(lo.Slot,{scope:e.__scopeMenu,children:s.jsx(wa,{id:c.contentId,"aria-labelledby":c.triggerId,...o,ref:u,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var d;a.isUsingKeyboardRef.current&&((d=l.current)==null||d.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:de(e.onFocusOutside,h=>{h.target!==c.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:de(e.onEscapeKeyDown,h=>{a.onClose(),h.preventDefault()}),onKeyDown:de(e.onKeyDown,h=>{var m;const d=h.currentTarget.contains(h.target),f=ib[a.dir].includes(h.key);d&&f&&(i.onOpenChange(!1),(m=c.trigger)==null||m.focus(),h.preventDefault())})})})})})});Ku.displayName=Wu;function Vu(e){return e?"open":"closed"}function us(e){return e==="indeterminate"}function ja(e){return us(e)?"indeterminate":e?"checked":"unchecked"}function Cb(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function jb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Eb(e,t,n){const o=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=jb(e,Math.max(i,0));o.length===1&&(a=a.filter(u=>u!==n));const l=a.find(u=>u.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function Tb(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const c=t[i],l=t[a],u=c.x,h=c.y,d=l.x,f=l.y;h>r!=f>r&&n<(d-u)*(r-h)/(f-h)+u&&(o=!o)}return o}function Ab(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Tb(n,t)}function uo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Rb=xa,Ob=Ru,_b=Ou,Pb=ka,Ib=_u,Db=_s,$b=Iu,Mb=$u,Lb=Lu,Nb=Bu,Bb=Fu,Fb=zu,zb=Uu,qb=Ku,Hu="DropdownMenu",[Ub]=kn(Hu,[Eu]),dt=Eu(),[Dj,Gu]=Ub(Hu),Qu="DropdownMenuTrigger",Wb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=Gu(Qu,n),a=dt(n);return s.jsx(Rb,{asChild:!0,...a,children:s.jsx(Te.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:bs(t,i.triggerRef),onPointerDown:de(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(i.onOpenToggle(),i.open||c.preventDefault())}),onKeyDown:de(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&i.onOpenToggle(),c.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});Wb.displayName=Qu;var Kb="DropdownMenuPortal",Ju=e=>{const{__scopeDropdownMenu:t,...n}=e,r=dt(t);return s.jsx(Ob,{...r,...n})};Ju.displayName=Kb;var Yu="DropdownMenuContent",Xu=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Gu(Yu,n),i=dt(n),a=p.useRef(!1);return s.jsx(_b,{id:o.contentId,"aria-labelledby":o.triggerId,...i,...r,ref:t,onCloseAutoFocus:de(e.onCloseAutoFocus,c=>{var l;a.current||(l=o.triggerRef.current)==null||l.focus(),a.current=!1,c.preventDefault()}),onInteractOutside:de(e.onInteractOutside,c=>{const l=c.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,h=l.button===2||u;(!o.modal||h)&&(a.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)"}})});Xu.displayName=Yu;var Vb="DropdownMenuGroup",Hb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Pb,{...o,...r,ref:t})});Hb.displayName=Vb;var Gb="DropdownMenuLabel",Zu=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Ib,{...o,...r,ref:t})});Zu.displayName=Gb;var Qb="DropdownMenuItem",ep=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Db,{...o,...r,ref:t})});ep.displayName=Qb;var Jb="DropdownMenuCheckboxItem",Yb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx($b,{...o,...r,ref:t})});Yb.displayName=Jb;var Xb="DropdownMenuRadioGroup",Zb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Mb,{...o,...r,ref:t})});Zb.displayName=Xb;var ex="DropdownMenuRadioItem",tx=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Lb,{...o,...r,ref:t})});tx.displayName=ex;var nx="DropdownMenuItemIndicator",rx=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Nb,{...o,...r,ref:t})});rx.displayName=nx;var ox="DropdownMenuSeparator",tp=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Bb,{...o,...r,ref:t})});tp.displayName=ox;var sx="DropdownMenuArrow",ix=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Fb,{...o,...r,ref:t})});ix.displayName=sx;var ax="DropdownMenuSubTrigger",cx=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(zb,{...o,...r,ref:t})});cx.displayName=ax;var lx="DropdownMenuSubContent",dx=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(qb,{...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)"}})});dx.displayName=lx;var ux=Ju,px=Xu,fx=Zu,hx=ep,mx=tp;const gx=p.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>s.jsx(ux,{container:e,children:s.jsx(px,{ref:o,sideOffset:n,style:{minWidth:180,background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.md,boxShadow:pe("shadowMd"),padding:be[1],zIndex:io.popover,...t},...r})}));gx.displayName="DropdownMenuContent";const yx=p.forwardRef(({style:e,...t},n)=>s.jsx(hx,{ref:n,style:{display:"flex",alignItems:"center",gap:be[2],padding:`${be[1]} ${be[2]}`,fontSize:Ze.sm,borderRadius:wn.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));yx.displayName="DropdownMenuItem";const bx=p.forwardRef(({style:e,...t},n)=>s.jsx(mx,{ref:n,style:{height:1,background:pe("borderSubtle"),margin:`${be[1]} 0`,...e},...t}));bx.displayName="DropdownMenuSeparator";const xx=p.forwardRef(({style:e,...t},n)=>s.jsx(fx,{ref:n,style:{padding:`${be[1]} ${be[2]}`,fontSize:Ze.xs,color:pe("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));xx.displayName="DropdownMenuLabel";var np="Popover",[rp]=kn(np,[Mr]),Ps=Mr(),[$j,Cn]=rp(np),op="PopoverAnchor",vx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Cn(op,n),i=Ps(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:c}=o;return p.useEffect(()=>(a(),()=>c()),[a,c]),s.jsx(ks,{...i,...r,ref:t})});vx.displayName=op;var sp="PopoverTrigger",Sx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Cn(sp,n),i=Ps(n),a=Oe(t,o.triggerRef),c=s.jsx(Te.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":dp(o.open),...r,ref:a,onClick:de(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?c:s.jsx(ks,{asChild:!0,...i,children:c})});Sx.displayName=sp;var Ea="PopoverPortal",[wx,kx]=rp(Ea,{forceMount:void 0}),ip=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Cn(Ea,t);return s.jsx(wx,{scope:t,forceMount:n,children:s.jsx(kt,{present:n||i.open,children:s.jsx(ko,{asChild:!0,container:o,children:r})})})};ip.displayName=Ea;var Pr="PopoverContent",ap=p.forwardRef((e,t)=>{const n=kx(Pr,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Cn(Pr,e.__scopePopover);return s.jsx(kt,{present:r||i.open,children:i.modal?s.jsx(jx,{...o,ref:t}):s.jsx(Ex,{...o,ref:t})})});ap.displayName=Pr;var Cx=Rr("PopoverContent.RemoveScroll"),jx=p.forwardRef((e,t)=>{const n=Cn(Pr,e.__scopePopover),r=p.useRef(null),o=Oe(t,r),i=p.useRef(!1);return p.useEffect(()=>{const a=r.current;if(a)return ha(a)},[]),s.jsx(As,{as:Cx,allowPinchZoom:!0,children:s.jsx(cp,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,a=>{var c;a.preventDefault(),i.current||(c=n.triggerRef.current)==null||c.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,a=>{const c=a.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0,u=c.button===2||l;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:de(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),Ex=p.forwardRef((e,t)=>{const n=Cn(Pr,e.__scopePopover),r=p.useRef(!1),o=p.useRef(!1);return s.jsx(cp,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,c;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(r.current||(c=n.triggerRef.current)==null||c.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=i.target;((u=n.triggerRef.current)==null?void 0:u.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),cp=p.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:h,...d}=e,f=Cn(Pr,n),m=Ps(n);return fa(),s.jsx(Es,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(So,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:h,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:s.jsx(ca,{"data-state":dp(f.open),role:"dialog",id:f.contentId,...m,...d,ref:t,style:{...d.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)"}})})})}),lp="PopoverClose",Tx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Cn(lp,n);return s.jsx(Te.button,{type:"button",...r,ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))})});Tx.displayName=lp;var Ax="PopoverArrow",Rx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Ps(n);return s.jsx(la,{...o,...r,ref:t})});Rx.displayName=Ax;function dp(e){return e?"open":"closed"}var Ox=ip,_x=ap;const Px=p.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>s.jsx(Ox,{container:e,children:s.jsx(_x,{ref:o,sideOffset:n,style:{background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.md,boxShadow:pe("shadowMd"),padding:be[3],zIndex:io.popover,minWidth:220,...t},...r})}));Px.displayName="PopoverContent";function Ta({icon:e,eyebrow:t,title:n,subtitle:r,status:o,actions:i,toolbar:a,bodyPadding:c=14,children:l}){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})]}),a&&s.jsx("div",{className:"panel-frame-toolbar",children:a}),s.jsx("div",{className:"panel-frame-body",style:{padding:c},children:l})]})}function up({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 no({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 pp({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 Ix({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 ${be[1]}px`,borderRadius:wn.sm,border:`1px solid ${pe("borderSubtle")}`,background:pe("surfaceRaised"),color:pe("textSecondary"),fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ze.xs,fontWeight:Xi.medium,lineHeight:1,whiteSpace:"nowrap",...n},children:e??t})}const Fc=e=>{let t;const n=new Set,r=(u,h)=>{const d=typeof u=="function"?u(t):u;if(!Object.is(d,t)){const f=t;t=h??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(m=>m(t,f))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u))},l=t=e(r,o,c);return c},Dx=(e=>e?Fc(e):Fc),$x=e=>e;function Mx(e,t=$x){const n=qe.useSyncExternalStore(e.subscribe,qe.useCallback(()=>t(e.getState()),[e,t]),qe.useCallback(()=>t(e.getInitialState()),[e,t]));return qe.useDebugValue(n),n}const zc=e=>{const t=Dx(e),n=r=>Mx(t,r);return Object.assign(n,t),n},Lx=(e=>e?zc(e):zc),qc=e=>Symbol.iterator in e,Uc=e=>"entries"in e,Wc=(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},Nx=(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 Bx(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:qc(e)&&qc(t)?Uc(e)&&Uc(t)?Wc(e,t):Nx(e,t):Wc({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Lr(e){const t=qe.useRef(void 0);return n=>{const r=e(n);return Bx(t.current,r)?t.current:t.current=r}}const Fx=/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g;function Aa(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(Fx)){const i=o[1],a=n.get(i);a&&a!==e.id&&r.set(a,{cellId:a,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 zx(e){const t=e.filter(u=>!["markdown","param","chat"].includes(u.type)),n=new Set(t.map(u=>u.id)),r=new Set(e.map(u=>u.id)),o=new Map(t.map(u=>[u.id,0])),i=new Map(t.map(u=>[u.id,[]])),a=[];for(const u of t)for(const h of Aa(u,e)){if(!r.has(h.cellId)){a.push({cellId:u.id,dependency:h.cellId});continue}n.has(h.cellId)&&(i.get(h.cellId).push(u.id),o.set(u.id,(o.get(u.id)??0)+1))}const c=t.filter(u=>o.get(u.id)===0),l=[];for(;c.length>0;){const u=c.shift();l.push(u);for(const h of i.get(u.id)??[]){const d=(o.get(h)??0)-1;if(o.set(h,d),d===0){const f=t.find(m=>m.id===h);f&&c.push(f)}}}return{ordered:l,cycleCellIds:t.filter(u=>!l.some(h=>h.id===u.id)).map(u=>u.id),missing:a}}function qx(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||Aa(i,t).some(a=>a.cellId===o)&&(n.add(i.id),r.push(i.id))}return n}function Ux(){var e;if(typeof window<"u")try{(e=window.localStorage)==null||e.removeItem("dql-app-mode")}catch{}return"studio"}function Wx(){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 Kx(){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 Vx={mainView:Kx(),agentLogRun:void 0,settingsTab:"overview",themeMode:Wx(),appMode:Ux(),sidebarPanel:null,sidebarOpen:!1,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,schemaTables:[],schemaLoading:!1,authoredDomains:[],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,blockStudioLastRun:null,blockStudioValidation:null,blockStudioMetadata:null,blockStudioCatalog:null,blockStudioCatalogLoading:!1,blockStudioImportOpen:!1,blockStudioDbtStatus:null,setupOpen:!1,inspectorOpen:!1,inspectorContext:null,apps:[],appsLoading:!1,activeAppId:null,activeAppDraftId:null,activeDashboardId:null,activeAppExperience:"view",activeAppSection:"dashboards",activePersona:null,globalAi:{open:!1,audience:"stakeholder",context:{}}};function Bi(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=vt();while(t.has(r));return t.add(r),r===n.id?n:{...n,id:r}})}function Hx(e,t){var n,r,o,i,a,c,l,u,h;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,...t.view==="notebook"&&((n=e.activeFile)==null?void 0:n.type)==="block"?{activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,dashboardMode:!1}:{},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 d=t.mode==="dark"||t.mode==="midnight"?"obsidian":t.mode==="light"?"paper":t.mode==="arctic"?"white":t.mode;document.documentElement.setAttribute("data-theme",d);try{(r=window.localStorage)==null||r.setItem("dql-theme",t.mode)}catch{}}return{...e,themeMode:t.mode}}case"SET_APP_MODE":{if(typeof window<"u")try{(o=window.localStorage)==null||o.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 d=["connection","git","apps","readiness","skills","domains","settings"],f=t.panel!==null&&d.includes(t.panel),m=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"||((i=e.activeFile)==null?void 0:i.type)==="block"?"block_studio":"notebook";return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null&&!f,...m==="notebook"&&((a=e.activeFile)==null?void 0:a.type)==="block"?{activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,dashboardMode:!1}:{},lineageFullscreen:!1,lineageFocusNodeId:null,lineageReturnTarget:null,mainView:m}}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,blockStudioLastRun: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:Bi(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,blockStudioLastRun:t.file.type==="block"?e.blockStudioLastRun: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,blockStudioLastRun:t.payload.lastRun??null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,blockStudioImportOpen:!1,lineageFullscreen:!1,lineageFocusNodeId:(c=t.payload.metadata)!=null&&c.name?`block:${t.payload.metadata.name}`:null};case"BLOCK_CERTIFICATION_ACCEPTED":return{...e,blockStudioDraft:t.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioLastRun:null,blockStudioMetadata:e.blockStudioMetadata?{...e.blockStudioMetadata,reviewStatus:"draft"}:null};case"RECONCILE_BLOCK_CERTIFICATION":{const d=t.newPath??t.payload.path,f={name:`${t.payload.metadata.name}.dql`,path:d,type:"block",folder:"blocks",isNew:!1},m=t.outcome==="certified"?new Set([t.draftPath,t.oldPath].filter(j=>j!==d&&j.includes("/_drafts/"))):new Set,S=e.files.filter(j=>!m.has(j.path)),v=S.findIndex(j=>j.path===d),b=v>=0?S.map((j,C)=>C===v?{...j,...f}:j):[...S,f];return e.mainView==="block_studio"&&!e.blockStudioDirty&&(!e.activeBlockPath||[t.oldPath,t.draftPath,d].includes(e.activeBlockPath))?{...e,files:b,activeFile:f,activeBlockPath:d,notebookTitle:t.payload.metadata.name,blockStudioDraft:t.payload.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioLastRun:t.payload.lastRun??null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,lineageFocusNodeId:`block:${t.payload.metadata.name}`}:{...e,files:b}}case"SET_CELLS":return{...e,cells:Bi(t.cells),notebookDirty:!0};case"UPDATE_NOTEBOOK_METADATA":{const d=e.notebookMetadata;let f=!1;for(const m of Object.keys(t.updates))if(d[m]!==t.updates[m]){f=!0;break}return f?{...e,notebookMetadata:{...d,...t.updates},notebookDirty:!0}:e}case"ADD_CELL":{const d=e.cells.some(S=>S.id===t.cell.id)?{...t.cell,id:vt()}:t.cell;if(!t.afterId)return{...e,cells:[...e.cells,d],notebookDirty:!0};const f=e.cells.findIndex(S=>S.id===t.afterId);if(f===-1)return{...e,cells:[...e.cells,d],notebookDirty:!0};const m=[...e.cells];return m.splice(f+1,0,d),{...e,cells:m,notebookDirty:!0}}case"UPDATE_CELL":{const d=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=d?qx(t.id,e.cells):new Set,m=e.cells.map(v=>{if(v.id===t.id){const b={...v,...t.updates};return d&&v.result&&t.updates.stale===void 0?{...b,stale:!0}:b}return f.has(v.id)&&v.result?{...v,stale:!0}:v}),S=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:m,notebookDirty:!0,executionCounter:S}}case"DELETE_CELL":return{...e,cells:e.cells.filter(d=>d.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const d=e.cells.findIndex(m=>m.id===t.id);if(d===-1)return e;const f=[...e.cells];return t.direction==="up"&&d>0?[f[d-1],f[d]]=[f[d],f[d-1]]:t.direction==="down"&&d<f.length-1&&([f[d],f[d+1]]=[f[d+1],f[d]]),{...e,cells:f,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:d,toIndex:f}=t;if(d===f||d<0||f<0||d>=e.cells.length||f>=e.cells.length)return e;const m=[...e.cells],[S]=m.splice(d,1);return m.splice(f,0,S),{...e,cells:m,notebookDirty:!0}}case"SET_SCHEMA":return{...e,schemaTables:t.tables};case"MERGE_SCHEMA_TABLES":{const d=new Map(e.schemaTables.map(f=>[f.path.toLowerCase(),f]));for(const f of t.tables){const m=f.path.toLowerCase(),S=d.get(m);d.set(m,S?{...S,...f,columns:f.columns.length>0?f.columns:S.columns,expanded:S.expanded}:f)}return{...e,schemaTables:Array.from(d.values())}}case"SET_SCHEMA_LOADING":return{...e,schemaLoading:t.loading};case"SET_AUTHORED_DOMAINS":return{...e,authoredDomains:t.domains};case"TOGGLE_SCHEMA_TABLE":return{...e,schemaTables:e.schemaTables.map(d=>d.name===t.tableName?{...d,expanded:!d.expanded}:d)};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,blockStudioLastRun: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(d=>d.path===t.file.path)?e:{...e,files:[...e.files,t.file]};case"FILE_REMOVED":{const d=e.files.filter(f=>f.path!==t.path);return((l=e.activeFile)==null?void 0:l.path)!==t.path?{...e,files:d}:{...e,files:d,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1}}case"SET_TABLE_COLUMNS":return{...e,schemaTables:e.schemaTables.map(d=>d.name===t.tableName?{...d,columns:t.columns}:d)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(d=>d.id===t.id?{...d,paramValue:t.value}:d),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 d=[t.name,...e.semanticLayer.recentlyUsed.filter(f=>f!==t.name)].slice(0,12);return{...e,semanticLayer:{...e.semanticLayer,recentlyUsed:d}}}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 d=t.returnTo!==void 0?t.returnTo:e.mainView==="lineage_detail"?e.lineageReturnTarget:null;return{...e,mainView:"lineage_detail",lineageFullscreen:!1,lineageFocusNodeId:t.nodeId,lineageReturnTarget:d,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,blockStudioLastRun:t.preview?{rowCount:t.preview.result.rowCount??t.preview.result.rows.length,executionTime:t.preview.result.executionTime,columns:t.preview.result.columns,ranAt:new Date().toISOString()}:e.blockStudioLastRun};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 d=e.apps.find(S=>S.id===t.appId)??null,f=t.dashboardId!==void 0?t.dashboardId:((u=d==null?void 0:d.homepage)==null?void 0:u.type)==="dashboard"?d.homepage.id:((h=d==null?void 0:d.dashboards[0])==null?void 0:h.id)??null,m=e.activeAppId===t.appId;return{...e,mainView:"apps",activeAppId:t.appId,activeAppDraftId:null,activeDashboardId:f,activeAppExperience:t.experience??(m?e.activeAppExperience:"view"),activeAppSection:t.section??(m?e.activeAppSection:"dashboards"),lineageReturnTarget:null}}case"OPEN_APP_DRAFT":return{...e,mainView:"apps",activeAppId:t.appId??null,activeAppDraftId:t.draftId,activeDashboardId:t.dashboardId??null,activeAppExperience:"build",activeAppSection:"dashboards",lineageReturnTarget:null};case"CLOSE_APP":return{...e,activeAppId:null,activeAppDraftId:null,activeDashboardId:null,activeAppExperience:"view",activeAppSection:"dashboards"};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 Ge=Lx((e,t)=>({...Vx,dispatch:n=>{const r=Hx(t(),n);e(r)}})),In=Ge,Gx=p.createContext(null);function Qx({children:e}){return qe.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")&&Ge.getState().dispatch({type:"SET_THEME",mode:r})};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]),s.jsx(s.Fragment,{children:e})}function et(){const e=Ge(Lr(r=>{const{dispatch:o,...i}=r;return i})),t=Ge(r=>r.dispatch);return p.useContext(Gx)??{state:e,dispatch:t}}function jn(){return Ge(e=>e.dispatch)}function vt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ra(e,t=""){const n={id:vt(),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 Jx="modulepreload",Yx=function(e){return"/"+e},Kc={},_e=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){let a=function(u){return Promise.all(u.map(h=>Promise.resolve(h).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=a(n.map(u=>{if(u=Yx(u),u in Kc)return;Kc[u]=!0;const h=u.endsWith(".css"),d=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const f=document.createElement("link");if(f.rel=h?"stylesheet":Jx,h||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),h)return new Promise((m,S)=>{f.addEventListener("load",m),f.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return o.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};/**
54
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return p.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Ly="DialogDescriptionWarning",Ny=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${bu(Ly).contentName}}.`;return p.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},By=au,Fy=du,zy=uu,qy=pu,Uy=hu;function xu(e){const t=e+"CollectionProvider",[n,r]=kn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),a=v=>{const{scope:b,children:w}=v,j=qe.useRef(null),C=qe.useRef(new Map).current;return s.jsx(o,{scope:b,itemMap:C,collectionRef:j,children:w})};a.displayName=t;const c=e+"CollectionSlot",l=Rr(c),u=qe.forwardRef((v,b)=>{const{scope:w,children:j}=v,C=i(c,w),x=Oe(b,C.collectionRef);return s.jsx(l,{ref:x,children:j})});u.displayName=c;const h=e+"CollectionItemSlot",d="data-radix-collection-item",f=Rr(h),m=qe.forwardRef((v,b)=>{const{scope:w,children:j,...C}=v,x=qe.useRef(null),E=Oe(b,x),P=i(h,w);return qe.useEffect(()=>(P.itemMap.set(x,{ref:x,...C}),()=>void P.itemMap.delete(x))),s.jsx(f,{[d]:"",ref:E,children:j})});m.displayName=h;function S(v){const b=i(e+"CollectionConsumer",v);return qe.useCallback(()=>{const j=b.collectionRef.current;if(!j)return[];const C=Array.from(j.querySelectorAll(`[${d}]`));return Array.from(b.itemMap.values()).sort((P,A)=>C.indexOf(P.ref.current)-C.indexOf(A.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:a,Slot:u,ItemSlot:m},S,r]}var Wy=p.createContext(void 0);function Ky(e){const t=p.useContext(Wy);return e||t||"ltr"}var Qs="rovingFocusGroup.onEntryFocus",Vy={bubbles:!1,cancelable:!0},jo="RovingFocusGroup",[Li,vu,Hy]=xu(jo),[Gy,Su]=kn(jo,[Hy]),[Qy,Jy]=Gy(jo),wu=p.forwardRef((e,t)=>s.jsx(Li.Provider,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Li.Slot,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Yy,{...e,ref:t})})}));wu.displayName=jo;var Yy=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:a,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:h=!1,...d}=e,f=p.useRef(null),m=Oe(t,f),S=Ky(i),[v,b]=da({prop:a,defaultProp:c??null,onChange:l,caller:jo}),[w,j]=p.useState(!1),C=yn(u),x=vu(n),E=p.useRef(!1),[P,A]=p.useState(0);return p.useEffect(()=>{const g=f.current;if(g)return g.addEventListener(Qs,C),()=>g.removeEventListener(Qs,C)},[C]),s.jsx(Qy,{scope:n,orientation:r,dir:S,loop:o,currentTabStopId:v,onItemFocus:p.useCallback(g=>b(g),[b]),onItemShiftTab:p.useCallback(()=>j(!0),[]),onFocusableItemAdd:p.useCallback(()=>A(g=>g+1),[]),onFocusableItemRemove:p.useCallback(()=>A(g=>g-1),[]),children:s.jsx(Te.div,{tabIndex:w||P===0?-1:0,"data-orientation":r,...d,ref:m,style:{outline:"none",...e.style},onMouseDown:de(e.onMouseDown,()=>{E.current=!0}),onFocus:de(e.onFocus,g=>{const I=!E.current;if(g.target===g.currentTarget&&I&&!w){const T=new CustomEvent(Qs,Vy);if(g.currentTarget.dispatchEvent(T),!T.defaultPrevented){const O=x().filter(J=>J.focusable),_=O.find(J=>J.active),M=O.find(J=>J.id===v),G=[_,M,...O].filter(Boolean).map(J=>J.ref.current);ju(G,h)}}E.current=!1}),onBlur:de(e.onBlur,()=>j(!1))})})}),ku="RovingFocusGroupItem",Cu=p.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,children:a,...c}=e,l=to(),u=i||l,h=Jy(ku,n),d=h.currentTabStopId===u,f=vu(n),{onFocusableItemAdd:m,onFocusableItemRemove:S,currentTabStopId:v}=h;return p.useEffect(()=>{if(r)return m(),()=>S()},[r,m,S]),s.jsx(Li.ItemSlot,{scope:n,id:u,focusable:r,active:o,children:s.jsx(Te.span,{tabIndex:d?0:-1,"data-orientation":h.orientation,...c,ref:t,onMouseDown:de(e.onMouseDown,b=>{r?h.onItemFocus(u):b.preventDefault()}),onFocus:de(e.onFocus,()=>h.onItemFocus(u)),onKeyDown:de(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){h.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const w=eb(b,h.orientation,h.dir);if(w!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let C=f().filter(x=>x.focusable).map(x=>x.ref.current);if(w==="last")C.reverse();else if(w==="prev"||w==="next"){w==="prev"&&C.reverse();const x=C.indexOf(b.currentTarget);C=h.loop?tb(C,x+1):C.slice(x+1)}setTimeout(()=>ju(C))}}),children:typeof a=="function"?a({isCurrentTabStop:d,hasTabStop:v!=null}):a})})});Cu.displayName=ku;var Xy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Zy(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function eb(e,t,n){const r=Zy(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Xy[r]}function ju(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function tb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var nb=wu,rb=Cu,Ni=["Enter"," "],ob=["ArrowDown","PageUp","Home"],Eu=["ArrowUp","PageDown","End"],sb=[...ob,...Eu],ib={ltr:[...Ni,"ArrowRight"],rtl:[...Ni,"ArrowLeft"]},ab={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Os="Menu",[lo,cb,lb]=xu(Os),[Gn,Tu]=kn(Os,[lb,Mr,Su]),ba=Mr(),Au=Su(),[Pj,Qn]=Gn(Os),[Ij,Eo]=Gn(Os),db="MenuAnchor",xa=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ba(n);return s.jsx(ks,{...o,...r,ref:t})});xa.displayName=db;var va="MenuPortal",[ub,Ru]=Gn(va,{forceMount:void 0}),Ou=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Qn(va,t);return s.jsx(ub,{scope:t,forceMount:n,children:s.jsx(kt,{present:n||i.open,children:s.jsx(ko,{asChild:!0,container:o,children:r})})})};Ou.displayName=va;var wt="MenuContent",[pb,Sa]=Gn(wt),_u=p.forwardRef((e,t)=>{const n=Ru(wt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Qn(wt,e.__scopeMenu),a=Eo(wt,e.__scopeMenu);return s.jsx(lo.Provider,{scope:e.__scopeMenu,children:s.jsx(kt,{present:r||i.open,children:s.jsx(lo.Slot,{scope:e.__scopeMenu,children:a.modal?s.jsx(fb,{...o,ref:t}):s.jsx(hb,{...o,ref:t})})})})}),fb=p.forwardRef((e,t)=>{const n=Qn(wt,e.__scopeMenu),r=p.useRef(null),o=Oe(t,r);return p.useEffect(()=>{const i=r.current;if(i)return ha(i)},[]),s.jsx(wa,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),hb=p.forwardRef((e,t)=>{const n=Qn(wt,e.__scopeMenu);return s.jsx(wa,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),mb=Rr("MenuContent.ScrollLock"),wa=p.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:c,onEntryFocus:l,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:d,onInteractOutside:f,onDismiss:m,disableOutsideScroll:S,...v}=e,b=Qn(wt,n),w=Eo(wt,n),j=ba(n),C=Au(n),x=cb(n),[E,P]=p.useState(null),A=p.useRef(null),g=Oe(t,A,b.onContentChange),I=p.useRef(0),T=p.useRef(""),O=p.useRef(0),_=p.useRef(null),M=p.useRef("right"),q=p.useRef(0),G=S?As:p.Fragment,J=S?{as:mb,allowPinchZoom:!0}:void 0,H=$=>{var ce,ke;const X=T.current+$,W=x().filter(xe=>!xe.disabled),te=document.activeElement,F=(ce=W.find(xe=>xe.ref.current===te))==null?void 0:ce.textValue,K=W.map(xe=>xe.textValue),oe=Tb(K,X,F),ee=(ke=W.find(xe=>xe.textValue===oe))==null?void 0:ke.ref.current;(function xe(De){T.current=De,window.clearTimeout(I.current),De!==""&&(I.current=window.setTimeout(()=>xe(""),1e3))})(X),ee&&setTimeout(()=>ee.focus())};p.useEffect(()=>()=>window.clearTimeout(I.current),[]),fa();const L=p.useCallback($=>{var W,te;return M.current===((W=_.current)==null?void 0:W.side)&&Rb($,(te=_.current)==null?void 0:te.area)},[]);return s.jsx(pb,{scope:n,searchRef:T,onItemEnter:p.useCallback($=>{L($)&&$.preventDefault()},[L]),onItemLeave:p.useCallback($=>{var X;L($)||((X=A.current)==null||X.focus(),P(null))},[L]),onTriggerLeave:p.useCallback($=>{L($)&&$.preventDefault()},[L]),pointerGraceTimerRef:O,onPointerGraceIntentChange:p.useCallback($=>{_.current=$},[]),children:s.jsx(G,{...J,children:s.jsx(Es,{asChild:!0,trapped:o,onMountAutoFocus:de(i,$=>{var X;$.preventDefault(),(X=A.current)==null||X.focus({preventScroll:!0})}),onUnmountAutoFocus:a,children:s.jsx(So,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:d,onInteractOutside:f,onDismiss:m,children:s.jsx(nb,{asChild:!0,...C,dir:w.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:P,onEntryFocus:de(l,$=>{w.isUsingKeyboardRef.current||$.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(ca,{role:"menu","aria-orientation":"vertical","data-state":Hu(b.open),"data-radix-menu-content":"",dir:w.dir,...j,...v,ref:g,style:{outline:"none",...v.style},onKeyDown:de(v.onKeyDown,$=>{const W=$.target.closest("[data-radix-menu-content]")===$.currentTarget,te=$.ctrlKey||$.altKey||$.metaKey,F=$.key.length===1;W&&($.key==="Tab"&&$.preventDefault(),!te&&F&&H($.key));const K=A.current;if($.target!==K||!sb.includes($.key))return;$.preventDefault();const ee=x().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);Eu.includes($.key)&&ee.reverse(),jb(ee)}),onBlur:de(e.onBlur,$=>{$.currentTarget.contains($.target)||(window.clearTimeout(I.current),T.current="")}),onPointerMove:de(e.onPointerMove,uo($=>{const X=$.target,W=q.current!==$.clientX;if($.currentTarget.contains(X)&&W){const te=$.clientX>q.current?"right":"left";M.current=te,q.current=$.clientX}}))})})})})})})});_u.displayName=wt;var gb="MenuGroup",ka=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{role:"group",...r,ref:t})});ka.displayName=gb;var yb="MenuLabel",Pu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{...r,ref:t})});Pu.displayName=yb;var ds="MenuItem",Bc="menu.itemSelect",_s=p.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=p.useRef(null),a=Eo(ds,e.__scopeMenu),c=Sa(ds,e.__scopeMenu),l=Oe(t,i),u=p.useRef(!1),h=()=>{const d=i.current;if(!n&&d){const f=new CustomEvent(Bc,{bubbles:!0,cancelable:!0});d.addEventListener(Bc,m=>r==null?void 0:r(m),{once:!0}),yd(d,f),f.defaultPrevented?u.current=!1:a.onClose()}};return s.jsx(Iu,{...o,ref:l,disabled:n,onClick:de(e.onClick,h),onPointerDown:d=>{var f;(f=e.onPointerDown)==null||f.call(e,d),u.current=!0},onPointerUp:de(e.onPointerUp,d=>{var f;u.current||(f=d.currentTarget)==null||f.click()}),onKeyDown:de(e.onKeyDown,d=>{const f=c.searchRef.current!=="";n||f&&d.key===" "||Ni.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});_s.displayName=ds;var Iu=p.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,a=Sa(ds,n),c=Au(n),l=p.useRef(null),u=Oe(t,l),[h,d]=p.useState(!1),[f,m]=p.useState("");return p.useEffect(()=>{const S=l.current;S&&m((S.textContent??"").trim())},[i.children]),s.jsx(lo.ItemSlot,{scope:n,disabled:r,textValue:o??f,children:s.jsx(rb,{asChild:!0,...c,focusable:!r,children:s.jsx(Te.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:u,onPointerMove:de(e.onPointerMove,uo(S=>{r?a.onItemLeave(S):(a.onItemEnter(S),S.defaultPrevented||S.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:de(e.onPointerLeave,uo(S=>a.onItemLeave(S))),onFocus:de(e.onFocus,()=>d(!0)),onBlur:de(e.onBlur,()=>d(!1))})})})}),bb="MenuCheckboxItem",Du=p.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return s.jsx(Bu,{scope:e.__scopeMenu,checked:n,children:s.jsx(_s,{role:"menuitemcheckbox","aria-checked":us(n)?"mixed":n,...o,ref:t,"data-state":ja(n),onSelect:de(o.onSelect,()=>r==null?void 0:r(us(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Du.displayName=bb;var $u="MenuRadioGroup",[xb,vb]=Gn($u,{value:void 0,onValueChange:()=>{}}),Mu=p.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,i=yn(r);return s.jsx(xb,{scope:e.__scopeMenu,value:n,onValueChange:i,children:s.jsx(ka,{...o,ref:t})})});Mu.displayName=$u;var Lu="MenuRadioItem",Nu=p.forwardRef((e,t)=>{const{value:n,...r}=e,o=vb(Lu,e.__scopeMenu),i=n===o.value;return s.jsx(Bu,{scope:e.__scopeMenu,checked:i,children:s.jsx(_s,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":ja(i),onSelect:de(r.onSelect,()=>{var a;return(a=o.onValueChange)==null?void 0:a.call(o,n)},{checkForDefaultPrevented:!1})})})});Nu.displayName=Lu;var Ca="MenuItemIndicator",[Bu,Sb]=Gn(Ca,{checked:!1}),Fu=p.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=Sb(Ca,n);return s.jsx(kt,{present:r||us(i.checked)||i.checked===!0,children:s.jsx(Te.span,{...o,ref:t,"data-state":ja(i.checked)})})});Fu.displayName=Ca;var wb="MenuSeparator",zu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});zu.displayName=wb;var kb="MenuArrow",qu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ba(n);return s.jsx(la,{...o,...r,ref:t})});qu.displayName=kb;var Cb="MenuSub",[Dj,Uu]=Gn(Cb),Gr="MenuSubTrigger",Wu=p.forwardRef((e,t)=>{const n=Qn(Gr,e.__scopeMenu),r=Eo(Gr,e.__scopeMenu),o=Uu(Gr,e.__scopeMenu),i=Sa(Gr,e.__scopeMenu),a=p.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:l}=i,u={__scopeMenu:e.__scopeMenu},h=p.useCallback(()=>{a.current&&window.clearTimeout(a.current),a.current=null},[]);return p.useEffect(()=>h,[h]),p.useEffect(()=>{const d=c.current;return()=>{window.clearTimeout(d),l(null)}},[c,l]),s.jsx(xa,{asChild:!0,...u,children:s.jsx(Iu,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":Hu(n.open),...e,ref:bs(t,o.onTriggerChange),onClick:d=>{var f;(f=e.onClick)==null||f.call(e,d),!(e.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:de(e.onPointerMove,uo(d=>{i.onItemEnter(d),!d.defaultPrevented&&!e.disabled&&!n.open&&!a.current&&(i.onPointerGraceIntentChange(null),a.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:de(e.onPointerLeave,uo(d=>{var m,S;h();const f=(m=n.content)==null?void 0:m.getBoundingClientRect();if(f){const v=(S=n.content)==null?void 0:S.dataset.side,b=v==="right",w=b?-5:5,j=f[b?"left":"right"],C=f[b?"right":"left"];i.onPointerGraceIntentChange({area:[{x:d.clientX+w,y:d.clientY},{x:j,y:f.top},{x:C,y:f.top},{x:C,y:f.bottom},{x:j,y:f.bottom}],side:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(d),d.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:de(e.onKeyDown,d=>{var m;const f=i.searchRef.current!=="";e.disabled||f&&d.key===" "||ib[r.dir].includes(d.key)&&(n.onOpenChange(!0),(m=n.content)==null||m.focus(),d.preventDefault())})})})});Wu.displayName=Gr;var Ku="MenuSubContent",Vu=p.forwardRef((e,t)=>{const n=Ru(wt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Qn(wt,e.__scopeMenu),a=Eo(wt,e.__scopeMenu),c=Uu(Ku,e.__scopeMenu),l=p.useRef(null),u=Oe(t,l);return s.jsx(lo.Provider,{scope:e.__scopeMenu,children:s.jsx(kt,{present:r||i.open,children:s.jsx(lo.Slot,{scope:e.__scopeMenu,children:s.jsx(wa,{id:c.contentId,"aria-labelledby":c.triggerId,...o,ref:u,align:"start",side:a.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var d;a.isUsingKeyboardRef.current&&((d=l.current)==null||d.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:de(e.onFocusOutside,h=>{h.target!==c.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:de(e.onEscapeKeyDown,h=>{a.onClose(),h.preventDefault()}),onKeyDown:de(e.onKeyDown,h=>{var m;const d=h.currentTarget.contains(h.target),f=ab[a.dir].includes(h.key);d&&f&&(i.onOpenChange(!1),(m=c.trigger)==null||m.focus(),h.preventDefault())})})})})})});Vu.displayName=Ku;function Hu(e){return e?"open":"closed"}function us(e){return e==="indeterminate"}function ja(e){return us(e)?"indeterminate":e?"checked":"unchecked"}function jb(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Eb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Tb(e,t,n){const o=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let a=Eb(e,Math.max(i,0));o.length===1&&(a=a.filter(u=>u!==n));const l=a.find(u=>u.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function Ab(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,a=t.length-1;i<t.length;a=i++){const c=t[i],l=t[a],u=c.x,h=c.y,d=l.x,f=l.y;h>r!=f>r&&n<(d-u)*(r-h)/(f-h)+u&&(o=!o)}return o}function Rb(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Ab(n,t)}function uo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Ob=xa,_b=Ou,Pb=_u,Ib=ka,Db=Pu,$b=_s,Mb=Du,Lb=Mu,Nb=Nu,Bb=Fu,Fb=zu,zb=qu,qb=Wu,Ub=Vu,Gu="DropdownMenu",[Wb]=kn(Gu,[Tu]),dt=Tu(),[$j,Qu]=Wb(Gu),Ju="DropdownMenuTrigger",Kb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=Qu(Ju,n),a=dt(n);return s.jsx(Ob,{asChild:!0,...a,children:s.jsx(Te.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:bs(t,i.triggerRef),onPointerDown:de(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(i.onOpenToggle(),i.open||c.preventDefault())}),onKeyDown:de(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&i.onOpenToggle(),c.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});Kb.displayName=Ju;var Vb="DropdownMenuPortal",Yu=e=>{const{__scopeDropdownMenu:t,...n}=e,r=dt(t);return s.jsx(_b,{...r,...n})};Yu.displayName=Vb;var Xu="DropdownMenuContent",Zu=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Qu(Xu,n),i=dt(n),a=p.useRef(!1);return s.jsx(Pb,{id:o.contentId,"aria-labelledby":o.triggerId,...i,...r,ref:t,onCloseAutoFocus:de(e.onCloseAutoFocus,c=>{var l;a.current||(l=o.triggerRef.current)==null||l.focus(),a.current=!1,c.preventDefault()}),onInteractOutside:de(e.onInteractOutside,c=>{const l=c.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,h=l.button===2||u;(!o.modal||h)&&(a.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)"}})});Zu.displayName=Xu;var Hb="DropdownMenuGroup",Gb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Ib,{...o,...r,ref:t})});Gb.displayName=Hb;var Qb="DropdownMenuLabel",ep=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Db,{...o,...r,ref:t})});ep.displayName=Qb;var Jb="DropdownMenuItem",tp=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx($b,{...o,...r,ref:t})});tp.displayName=Jb;var Yb="DropdownMenuCheckboxItem",Xb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Mb,{...o,...r,ref:t})});Xb.displayName=Yb;var Zb="DropdownMenuRadioGroup",ex=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Lb,{...o,...r,ref:t})});ex.displayName=Zb;var tx="DropdownMenuRadioItem",nx=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Nb,{...o,...r,ref:t})});nx.displayName=tx;var rx="DropdownMenuItemIndicator",ox=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Bb,{...o,...r,ref:t})});ox.displayName=rx;var sx="DropdownMenuSeparator",np=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Fb,{...o,...r,ref:t})});np.displayName=sx;var ix="DropdownMenuArrow",ax=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(zb,{...o,...r,ref:t})});ax.displayName=ix;var cx="DropdownMenuSubTrigger",lx=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(qb,{...o,...r,ref:t})});lx.displayName=cx;var dx="DropdownMenuSubContent",ux=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Ub,{...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)"}})});ux.displayName=dx;var px=Yu,fx=Zu,hx=ep,mx=tp,gx=np;const yx=p.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>s.jsx(px,{container:e,children:s.jsx(fx,{ref:o,sideOffset:n,style:{minWidth:180,background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.md,boxShadow:pe("shadowMd"),padding:be[1],zIndex:io.popover,...t},...r})}));yx.displayName="DropdownMenuContent";const bx=p.forwardRef(({style:e,...t},n)=>s.jsx(mx,{ref:n,style:{display:"flex",alignItems:"center",gap:be[2],padding:`${be[1]} ${be[2]}`,fontSize:Ze.sm,borderRadius:wn.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));bx.displayName="DropdownMenuItem";const xx=p.forwardRef(({style:e,...t},n)=>s.jsx(gx,{ref:n,style:{height:1,background:pe("borderSubtle"),margin:`${be[1]} 0`,...e},...t}));xx.displayName="DropdownMenuSeparator";const vx=p.forwardRef(({style:e,...t},n)=>s.jsx(hx,{ref:n,style:{padding:`${be[1]} ${be[2]}`,fontSize:Ze.xs,color:pe("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));vx.displayName="DropdownMenuLabel";var rp="Popover",[op]=kn(rp,[Mr]),Ps=Mr(),[Mj,Cn]=op(rp),sp="PopoverAnchor",Sx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Cn(sp,n),i=Ps(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:c}=o;return p.useEffect(()=>(a(),()=>c()),[a,c]),s.jsx(ks,{...i,...r,ref:t})});Sx.displayName=sp;var ip="PopoverTrigger",wx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Cn(ip,n),i=Ps(n),a=Oe(t,o.triggerRef),c=s.jsx(Te.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":up(o.open),...r,ref:a,onClick:de(e.onClick,o.onOpenToggle)});return o.hasCustomAnchor?c:s.jsx(ks,{asChild:!0,...i,children:c})});wx.displayName=ip;var Ea="PopoverPortal",[kx,Cx]=op(Ea,{forceMount:void 0}),ap=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Cn(Ea,t);return s.jsx(kx,{scope:t,forceMount:n,children:s.jsx(kt,{present:n||i.open,children:s.jsx(ko,{asChild:!0,container:o,children:r})})})};ap.displayName=Ea;var Pr="PopoverContent",cp=p.forwardRef((e,t)=>{const n=Cx(Pr,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Cn(Pr,e.__scopePopover);return s.jsx(kt,{present:r||i.open,children:i.modal?s.jsx(Ex,{...o,ref:t}):s.jsx(Tx,{...o,ref:t})})});cp.displayName=Pr;var jx=Rr("PopoverContent.RemoveScroll"),Ex=p.forwardRef((e,t)=>{const n=Cn(Pr,e.__scopePopover),r=p.useRef(null),o=Oe(t,r),i=p.useRef(!1);return p.useEffect(()=>{const a=r.current;if(a)return ha(a)},[]),s.jsx(As,{as:jx,allowPinchZoom:!0,children:s.jsx(lp,{...e,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,a=>{var c;a.preventDefault(),i.current||(c=n.triggerRef.current)==null||c.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,a=>{const c=a.detail.originalEvent,l=c.button===0&&c.ctrlKey===!0,u=c.button===2||l;i.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:de(e.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1})})})}),Tx=p.forwardRef((e,t)=>{const n=Cn(Pr,e.__scopePopover),r=p.useRef(!1),o=p.useRef(!1);return s.jsx(lp,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var a,c;(a=e.onCloseAutoFocus)==null||a.call(e,i),i.defaultPrevented||(r.current||(c=n.triggerRef.current)==null||c.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const a=i.target;((u=n.triggerRef.current)==null?void 0:u.contains(a))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),lp=p.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:h,...d}=e,f=Cn(Pr,n),m=Ps(n);return fa(),s.jsx(Es,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(So,{asChild:!0,disableOutsidePointerEvents:a,onInteractOutside:h,onEscapeKeyDown:c,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),children:s.jsx(ca,{"data-state":up(f.open),role:"dialog",id:f.contentId,...m,...d,ref:t,style:{...d.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)"}})})})}),dp="PopoverClose",Ax=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Cn(dp,n);return s.jsx(Te.button,{type:"button",...r,ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))})});Ax.displayName=dp;var Rx="PopoverArrow",Ox=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Ps(n);return s.jsx(la,{...o,...r,ref:t})});Ox.displayName=Rx;function up(e){return e?"open":"closed"}var _x=ap,Px=cp;const Ix=p.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>s.jsx(_x,{container:e,children:s.jsx(Px,{ref:o,sideOffset:n,style:{background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.md,boxShadow:pe("shadowMd"),padding:be[3],zIndex:io.popover,minWidth:220,...t},...r})}));Ix.displayName="PopoverContent";function Ta({icon:e,eyebrow:t,title:n,subtitle:r,status:o,actions:i,toolbar:a,bodyPadding:c=14,children:l}){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})]}),a&&s.jsx("div",{className:"panel-frame-toolbar",children:a}),s.jsx("div",{className:"panel-frame-body",style:{padding:c},children:l})]})}function pp({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 no({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 fp({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 Dx({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 ${be[1]}px`,borderRadius:wn.sm,border:`1px solid ${pe("borderSubtle")}`,background:pe("surfaceRaised"),color:pe("textSecondary"),fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ze.xs,fontWeight:Xi.medium,lineHeight:1,whiteSpace:"nowrap",...n},children:e??t})}const Fc=e=>{let t;const n=new Set,r=(u,h)=>{const d=typeof u=="function"?u(t):u;if(!Object.is(d,t)){const f=t;t=h??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(m=>m(t,f))}},o=()=>t,c={setState:r,getState:o,getInitialState:()=>l,subscribe:u=>(n.add(u),()=>n.delete(u))},l=t=e(r,o,c);return c},$x=(e=>e?Fc(e):Fc),Mx=e=>e;function Lx(e,t=Mx){const n=qe.useSyncExternalStore(e.subscribe,qe.useCallback(()=>t(e.getState()),[e,t]),qe.useCallback(()=>t(e.getInitialState()),[e,t]));return qe.useDebugValue(n),n}const zc=e=>{const t=$x(e),n=r=>Lx(t,r);return Object.assign(n,t),n},Nx=(e=>e?zc(e):zc),qc=e=>Symbol.iterator in e,Uc=e=>"entries"in e,Wc=(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},Bx=(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 Fx(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:qc(e)&&qc(t)?Uc(e)&&Uc(t)?Wc(e,t):Bx(e,t):Wc({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Lr(e){const t=qe.useRef(void 0);return n=>{const r=e(n);return Fx(t.current,r)?t.current:t.current=r}}const zx=/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g;function Aa(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(zx)){const i=o[1],a=n.get(i);a&&a!==e.id&&r.set(a,{cellId:a,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 qx(e){const t=e.filter(u=>!["markdown","param","chat"].includes(u.type)),n=new Set(t.map(u=>u.id)),r=new Set(e.map(u=>u.id)),o=new Map(t.map(u=>[u.id,0])),i=new Map(t.map(u=>[u.id,[]])),a=[];for(const u of t)for(const h of Aa(u,e)){if(!r.has(h.cellId)){a.push({cellId:u.id,dependency:h.cellId});continue}n.has(h.cellId)&&(i.get(h.cellId).push(u.id),o.set(u.id,(o.get(u.id)??0)+1))}const c=t.filter(u=>o.get(u.id)===0),l=[];for(;c.length>0;){const u=c.shift();l.push(u);for(const h of i.get(u.id)??[]){const d=(o.get(h)??0)-1;if(o.set(h,d),d===0){const f=t.find(m=>m.id===h);f&&c.push(f)}}}return{ordered:l,cycleCellIds:t.filter(u=>!l.some(h=>h.id===u.id)).map(u=>u.id),missing:a}}function Ux(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||Aa(i,t).some(a=>a.cellId===o)&&(n.add(i.id),r.push(i.id))}return n}function Wx(){var e;if(typeof window<"u")try{(e=window.localStorage)==null||e.removeItem("dql-app-mode")}catch{}return"studio"}function Kx(){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 Vx(){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 Hx={mainView:Vx(),agentLogRun:void 0,settingsTab:"overview",themeMode:Kx(),appMode:Wx(),sidebarPanel:null,sidebarOpen:!1,files:[],filesLoading:!1,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,schemaTables:[],schemaLoading:!1,authoredDomains:[],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,blockStudioLastRun:null,blockStudioValidation:null,blockStudioMetadata:null,blockStudioCatalog:null,blockStudioCatalogLoading:!1,blockStudioImportOpen:!1,blockStudioDbtStatus:null,setupOpen:!1,inspectorOpen:!1,inspectorContext:null,apps:[],appsLoading:!1,activeAppId:null,activeAppDraftId:null,activeDashboardId:null,activeAppExperience:"view",activeAppSection:"dashboards",activePersona:null,globalAi:{open:!1,audience:"stakeholder",context:{}}};function Bi(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=vt();while(t.has(r));return t.add(r),r===n.id?n:{...n,id:r}})}function Gx(e,t){var n,r,o,i,a,c,l,u,h;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,...t.view==="notebook"&&((n=e.activeFile)==null?void 0:n.type)==="block"?{activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,dashboardMode:!1}:{},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 d=t.mode==="dark"||t.mode==="midnight"?"obsidian":t.mode==="light"?"paper":t.mode==="arctic"?"white":t.mode;document.documentElement.setAttribute("data-theme",d);try{(r=window.localStorage)==null||r.setItem("dql-theme",t.mode)}catch{}}return{...e,themeMode:t.mode}}case"SET_APP_MODE":{if(typeof window<"u")try{(o=window.localStorage)==null||o.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 d=["connection","git","apps","readiness","skills","domains","settings"],f=t.panel!==null&&d.includes(t.panel),m=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"||((i=e.activeFile)==null?void 0:i.type)==="block"?"block_studio":"notebook";return{...e,sidebarPanel:t.panel,sidebarOpen:t.panel!==null&&!f,...m==="notebook"&&((a=e.activeFile)==null?void 0:a.type)==="block"?{activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1,dashboardMode:!1}:{},lineageFullscreen:!1,lineageFocusNodeId:null,lineageReturnTarget:null,mainView:m}}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,blockStudioLastRun: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:Bi(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,blockStudioLastRun:t.file.type==="block"?e.blockStudioLastRun: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,blockStudioLastRun:t.payload.lastRun??null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,blockStudioImportOpen:!1,lineageFullscreen:!1,lineageFocusNodeId:(c=t.payload.metadata)!=null&&c.name?`block:${t.payload.metadata.name}`:null};case"BLOCK_CERTIFICATION_ACCEPTED":return{...e,blockStudioDraft:t.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioLastRun:null,blockStudioMetadata:e.blockStudioMetadata?{...e.blockStudioMetadata,reviewStatus:"draft"}:null};case"RECONCILE_BLOCK_CERTIFICATION":{const d=t.newPath??t.payload.path,f={name:`${t.payload.metadata.name}.dql`,path:d,type:"block",folder:"blocks",isNew:!1},m=t.outcome==="certified"?new Set([t.draftPath,t.oldPath].filter(j=>j!==d&&j.includes("/_drafts/"))):new Set,S=e.files.filter(j=>!m.has(j.path)),v=S.findIndex(j=>j.path===d),b=v>=0?S.map((j,C)=>C===v?{...j,...f}:j):[...S,f];return e.mainView==="block_studio"&&!e.blockStudioDirty&&(!e.activeBlockPath||[t.oldPath,t.draftPath,d].includes(e.activeBlockPath))?{...e,files:b,activeFile:f,activeBlockPath:d,notebookTitle:t.payload.metadata.name,blockStudioDraft:t.payload.source,blockStudioDirty:!1,blockStudioPreview:null,blockStudioLastRun:t.payload.lastRun??null,blockStudioValidation:t.payload.validation,blockStudioMetadata:t.payload.metadata,lineageFocusNodeId:`block:${t.payload.metadata.name}`}:{...e,files:b}}case"SET_CELLS":return{...e,cells:Bi(t.cells),notebookDirty:!0};case"UPDATE_NOTEBOOK_METADATA":{const d=e.notebookMetadata;let f=!1;for(const m of Object.keys(t.updates))if(d[m]!==t.updates[m]){f=!0;break}return f?{...e,notebookMetadata:{...d,...t.updates},notebookDirty:!0}:e}case"ADD_CELL":{const d=e.cells.some(S=>S.id===t.cell.id)?{...t.cell,id:vt()}:t.cell;if(!t.afterId)return{...e,cells:[...e.cells,d],notebookDirty:!0};const f=e.cells.findIndex(S=>S.id===t.afterId);if(f===-1)return{...e,cells:[...e.cells,d],notebookDirty:!0};const m=[...e.cells];return m.splice(f+1,0,d),{...e,cells:m,notebookDirty:!0}}case"UPDATE_CELL":{const d=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=d?Ux(t.id,e.cells):new Set,m=e.cells.map(v=>{if(v.id===t.id){const b={...v,...t.updates};return d&&v.result&&t.updates.stale===void 0?{...b,stale:!0}:b}return f.has(v.id)&&v.result?{...v,stale:!0}:v}),S=t.updates.executionCount!==void 0?e.executionCounter+1:e.executionCounter;return{...e,cells:m,notebookDirty:!0,executionCounter:S}}case"DELETE_CELL":return{...e,cells:e.cells.filter(d=>d.id!==t.id),notebookDirty:!0};case"MOVE_CELL":{const d=e.cells.findIndex(m=>m.id===t.id);if(d===-1)return e;const f=[...e.cells];return t.direction==="up"&&d>0?[f[d-1],f[d]]=[f[d],f[d-1]]:t.direction==="down"&&d<f.length-1&&([f[d],f[d+1]]=[f[d+1],f[d]]),{...e,cells:f,notebookDirty:!0}}case"REORDER_CELL":{const{fromIndex:d,toIndex:f}=t;if(d===f||d<0||f<0||d>=e.cells.length||f>=e.cells.length)return e;const m=[...e.cells],[S]=m.splice(d,1);return m.splice(f,0,S),{...e,cells:m,notebookDirty:!0}}case"SET_SCHEMA":return{...e,schemaTables:t.tables};case"MERGE_SCHEMA_TABLES":{const d=new Map(e.schemaTables.map(f=>[f.path.toLowerCase(),f]));for(const f of t.tables){const m=f.path.toLowerCase(),S=d.get(m);d.set(m,S?{...S,...f,columns:f.columns.length>0?f.columns:S.columns,expanded:S.expanded}:f)}return{...e,schemaTables:Array.from(d.values())}}case"SET_SCHEMA_LOADING":return{...e,schemaLoading:t.loading};case"SET_AUTHORED_DOMAINS":return{...e,authoredDomains:t.domains};case"TOGGLE_SCHEMA_TABLE":return{...e,schemaTables:e.schemaTables.map(d=>d.name===t.tableName?{...d,expanded:!d.expanded}:d)};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,blockStudioLastRun: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(d=>d.path===t.file.path)?e:{...e,files:[...e.files,t.file]};case"FILE_REMOVED":{const d=e.files.filter(f=>f.path!==t.path);return((l=e.activeFile)==null?void 0:l.path)!==t.path?{...e,files:d}:{...e,files:d,activeFile:null,cells:[],notebookTitle:"",notebookMetadata:{},notebookDirty:!1}}case"SET_TABLE_COLUMNS":return{...e,schemaTables:e.schemaTables.map(d=>d.name===t.tableName?{...d,columns:t.columns}:d)};case"SET_PARAM_VALUE":return{...e,cells:e.cells.map(d=>d.id===t.id?{...d,paramValue:t.value}:d),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 d=[t.name,...e.semanticLayer.recentlyUsed.filter(f=>f!==t.name)].slice(0,12);return{...e,semanticLayer:{...e.semanticLayer,recentlyUsed:d}}}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 d=t.returnTo!==void 0?t.returnTo:e.mainView==="lineage_detail"?e.lineageReturnTarget:null;return{...e,mainView:"lineage_detail",lineageFullscreen:!1,lineageFocusNodeId:t.nodeId,lineageReturnTarget:d,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,blockStudioLastRun:t.preview?{rowCount:t.preview.result.rowCount??t.preview.result.rows.length,executionTime:t.preview.result.executionTime,columns:t.preview.result.columns,ranAt:new Date().toISOString()}:e.blockStudioLastRun};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 d=e.apps.find(S=>S.id===t.appId)??null,f=t.dashboardId!==void 0?t.dashboardId:((u=d==null?void 0:d.homepage)==null?void 0:u.type)==="dashboard"?d.homepage.id:((h=d==null?void 0:d.dashboards[0])==null?void 0:h.id)??null,m=e.activeAppId===t.appId;return{...e,mainView:"apps",activeAppId:t.appId,activeAppDraftId:null,activeDashboardId:f,activeAppExperience:t.experience??(m?e.activeAppExperience:"view"),activeAppSection:t.section??(m?e.activeAppSection:"dashboards"),lineageReturnTarget:null}}case"OPEN_APP_DRAFT":return{...e,mainView:"apps",activeAppId:t.appId??null,activeAppDraftId:t.draftId,activeDashboardId:t.dashboardId??null,activeAppExperience:"build",activeAppSection:"dashboards",lineageReturnTarget:null};case"CLOSE_APP":return{...e,activeAppId:null,activeAppDraftId:null,activeDashboardId:null,activeAppExperience:"view",activeAppSection:"dashboards"};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 Ge=Nx((e,t)=>({...Hx,dispatch:n=>{const r=Gx(t(),n);e(r)}})),In=Ge,Qx=p.createContext(null);function Jx({children:e}){return qe.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")&&Ge.getState().dispatch({type:"SET_THEME",mode:r})};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]),s.jsx(s.Fragment,{children:e})}function et(){const e=Ge(Lr(r=>{const{dispatch:o,...i}=r;return i})),t=Ge(r=>r.dispatch);return p.useContext(Qx)??{state:e,dispatch:t}}function jn(){return Ge(e=>e.dispatch)}function vt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ra(e,t=""){const n={id:vt(),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 Yx="modulepreload",Xx=function(e){return"/"+e},Kc={},_e=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){let a=function(u){return Promise.all(u.map(h=>Promise.resolve(h).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=a(n.map(u=>{if(u=Xx(u),u in Kc)return;Kc[u]=!0;const h=u.endsWith(".css"),d=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const f=document.createElement("link");if(f.rel=h?"stylesheet":Yx,h||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),h)return new Promise((m,S)=>{f.addEventListener("load",m),f.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return o.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};/**
55
55
  * @license lucide-react v0.563.0 - ISC
56
56
  *
57
57
  * This source code is licensed under the ISC license.
58
58
  * See the LICENSE file in the root directory of this source tree.
59
- */const fp=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/**
59
+ */const hp=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/**
60
60
  * @license lucide-react v0.563.0 - ISC
61
61
  *
62
62
  * This source code is licensed under the ISC license.
63
63
  * See the LICENSE file in the root directory of this source tree.
64
- */const Xx=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
64
+ */const Zx=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
65
65
  * @license lucide-react v0.563.0 - ISC
66
66
  *
67
67
  * This source code is licensed under the ISC license.
68
68
  * See the LICENSE file in the root directory of this source tree.
69
- */const Zx=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());/**
69
+ */const ev=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());/**
70
70
  * @license lucide-react v0.563.0 - ISC
71
71
  *
72
72
  * This source code is licensed under the ISC license.
73
73
  * See the LICENSE file in the root directory of this source tree.
74
- */const Vc=e=>{const t=Zx(e);return t.charAt(0).toUpperCase()+t.slice(1)};/**
74
+ */const Vc=e=>{const t=ev(e);return t.charAt(0).toUpperCase()+t.slice(1)};/**
75
75
  * @license lucide-react v0.563.0 - ISC
76
76
  *
77
77
  * This source code is licensed under the ISC license.
78
78
  * See the LICENSE file in the root directory of this source tree.
79
- */var ev={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"};/**
79
+ */var tv={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
80
  * @license lucide-react v0.563.0 - ISC
81
81
  *
82
82
  * This source code is licensed under the ISC license.
83
83
  * See the LICENSE file in the root directory of this source tree.
84
- */const tv=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};/**
84
+ */const nv=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};/**
85
85
  * @license lucide-react v0.563.0 - ISC
86
86
  *
87
87
  * This source code is licensed under the ISC license.
88
88
  * See the LICENSE file in the root directory of this source tree.
89
- */const nv=p.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:a,...c},l)=>p.createElement("svg",{ref:l,...ev,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:fp("lucide",o),...!i&&!tv(c)&&{"aria-hidden":"true"},...c},[...a.map(([u,h])=>p.createElement(u,h)),...Array.isArray(i)?i:[i]]));/**
89
+ */const rv=p.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:a,...c},l)=>p.createElement("svg",{ref:l,...tv,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:hp("lucide",o),...!i&&!nv(c)&&{"aria-hidden":"true"},...c},[...a.map(([u,h])=>p.createElement(u,h)),...Array.isArray(i)?i:[i]]));/**
90
90
  * @license lucide-react v0.563.0 - ISC
91
91
  *
92
92
  * This source code is licensed under the ISC license.
93
93
  * See the LICENSE file in the root directory of this source tree.
94
- */const ne=(e,t)=>{const n=p.forwardRef(({className:r,...o},i)=>p.createElement(nv,{ref:i,iconNode:t,className:fp(`lucide-${Xx(Vc(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Vc(e),n};/**
94
+ */const ne=(e,t)=>{const n=p.forwardRef(({className:r,...o},i)=>p.createElement(rv,{ref:i,iconNode:t,className:hp(`lucide-${Zx(Vc(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Vc(e),n};/**
95
95
  * @license lucide-react v0.563.0 - ISC
96
96
  *
97
97
  * This source code is licensed under the ISC license.
98
98
  * See the LICENSE file in the root directory of this source tree.
99
- */const rv=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],ov=ne("arrow-down",rv);/**
99
+ */const ov=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],sv=ne("arrow-down",ov);/**
100
100
  * @license lucide-react v0.563.0 - ISC
101
101
  *
102
102
  * This source code is licensed under the ISC license.
103
103
  * See the LICENSE file in the root directory of this source tree.
104
- */const sv=[["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"}]],iv=ne("arrow-right-left",sv);/**
104
+ */const iv=[["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"}]],av=ne("arrow-right-left",iv);/**
105
105
  * @license lucide-react v0.563.0 - ISC
106
106
  *
107
107
  * This source code is licensed under the ISC license.
108
108
  * See the LICENSE file in the root directory of this source tree.
109
- */const av=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],cv=ne("arrow-up",av);/**
109
+ */const cv=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],lv=ne("arrow-up",cv);/**
110
110
  * @license lucide-react v0.563.0 - ISC
111
111
  *
112
112
  * This source code is licensed under the ISC license.
113
113
  * See the LICENSE file in the root directory of this source tree.
114
- */const lv=[["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"}]],Oa=ne("blocks",lv);/**
114
+ */const dv=[["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"}]],Oa=ne("blocks",dv);/**
115
115
  * @license lucide-react v0.563.0 - ISC
116
116
  *
117
117
  * This source code is licensed under the ISC license.
118
118
  * See the LICENSE file in the root directory of this source tree.
119
- */const dv=[["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"}]],uv=ne("bookmark",dv);/**
119
+ */const uv=[["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"}]],pv=ne("bookmark",uv);/**
120
120
  * @license lucide-react v0.563.0 - ISC
121
121
  *
122
122
  * This source code is licensed under the ISC license.
123
123
  * See the LICENSE file in the root directory of this source tree.
124
- */const pv=[["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"}]],fv=ne("box",pv);/**
124
+ */const fv=[["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"}]],hv=ne("box",fv);/**
125
125
  * @license lucide-react v0.563.0 - ISC
126
126
  *
127
127
  * This source code is licensed under the ISC license.
128
128
  * See the LICENSE file in the root directory of this source tree.
129
- */const hv=[["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"}]],Fi=ne("boxes",hv);/**
129
+ */const mv=[["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"}]],Fi=ne("boxes",mv);/**
130
130
  * @license lucide-react v0.563.0 - ISC
131
131
  *
132
132
  * This source code is licensed under the ISC license.
133
133
  * See the LICENSE file in the root directory of this source tree.
134
- */const mv=[["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"}]],gv=ne("briefcase",mv);/**
134
+ */const gv=[["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"}]],yv=ne("briefcase",gv);/**
135
135
  * @license lucide-react v0.563.0 - ISC
136
136
  *
137
137
  * This source code is licensed under the ISC license.
138
138
  * See the LICENSE file in the root directory of this source tree.
139
- */const yv=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],bv=ne("check",yv);/**
139
+ */const bv=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],xv=ne("check",bv);/**
140
140
  * @license lucide-react v0.563.0 - ISC
141
141
  *
142
142
  * This source code is licensed under the ISC license.
143
143
  * See the LICENSE file in the root directory of this source tree.
144
- */const xv=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],_a=ne("chevron-down",xv);/**
144
+ */const vv=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],_a=ne("chevron-down",vv);/**
145
145
  * @license lucide-react v0.563.0 - ISC
146
146
  *
147
147
  * This source code is licensed under the ISC license.
148
148
  * See the LICENSE file in the root directory of this source tree.
149
- */const vv=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Is=ne("chevron-right",vv);/**
149
+ */const Sv=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Is=ne("chevron-right",Sv);/**
150
150
  * @license lucide-react v0.563.0 - ISC
151
151
  *
152
152
  * This source code is licensed under the ISC license.
153
153
  * See the LICENSE file in the root directory of this source tree.
154
- */const Sv=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],wv=ne("chevrons-left",Sv);/**
154
+ */const wv=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],kv=ne("chevrons-left",wv);/**
155
155
  * @license lucide-react v0.563.0 - ISC
156
156
  *
157
157
  * This source code is licensed under the ISC license.
158
158
  * See the LICENSE file in the root directory of this source tree.
159
- */const kv=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],Cv=ne("chevrons-right",kv);/**
159
+ */const Cv=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],jv=ne("chevrons-right",Cv);/**
160
160
  * @license lucide-react v0.563.0 - ISC
161
161
  *
162
162
  * This source code is licensed under the ISC license.
163
163
  * See the LICENSE file in the root directory of this source tree.
164
- */const jv=[["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"}]],Ev=ne("circle-alert",jv);/**
164
+ */const Ev=[["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"}]],Tv=ne("circle-alert",Ev);/**
165
165
  * @license lucide-react v0.563.0 - ISC
166
166
  *
167
167
  * This source code is licensed under the ISC license.
168
168
  * See the LICENSE file in the root directory of this source tree.
169
- */const Tv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],hp=ne("circle-check",Tv);/**
169
+ */const Av=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],mp=ne("circle-check",Av);/**
170
170
  * @license lucide-react v0.563.0 - ISC
171
171
  *
172
172
  * This source code is licensed under the ISC license.
173
173
  * See the LICENSE file in the root directory of this source tree.
174
- */const Av=[["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"}]],Rv=ne("circle-question-mark",Av);/**
174
+ */const Rv=[["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"}]],Ov=ne("circle-question-mark",Rv);/**
175
175
  * @license lucide-react v0.563.0 - ISC
176
176
  *
177
177
  * This source code is licensed under the ISC license.
178
178
  * See the LICENSE file in the root directory of this source tree.
179
- */const Ov=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],_v=ne("clock",Ov);/**
179
+ */const _v=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Pv=ne("clock",_v);/**
180
180
  * @license lucide-react v0.563.0 - ISC
181
181
  *
182
182
  * This source code is licensed under the ISC license.
183
183
  * See the LICENSE file in the root directory of this source tree.
184
- */const Pv=[["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"}]],Iv=ne("command",Pv);/**
184
+ */const Iv=[["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"}]],Dv=ne("command",Iv);/**
185
185
  * @license lucide-react v0.563.0 - ISC
186
186
  *
187
187
  * This source code is licensed under the ISC license.
188
188
  * See the LICENSE file in the root directory of this source tree.
189
- */const Dv=[["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"}]],To=ne("database",Dv);/**
189
+ */const $v=[["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"}]],To=ne("database",$v);/**
190
190
  * @license lucide-react v0.563.0 - ISC
191
191
  *
192
192
  * This source code is licensed under the ISC license.
193
193
  * See the LICENSE file in the root directory of this source tree.
194
- */const $v=[["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"}]],mp=ne("download",$v);/**
194
+ */const Mv=[["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"}]],gp=ne("download",Mv);/**
195
195
  * @license lucide-react v0.563.0 - ISC
196
196
  *
197
197
  * This source code is licensed under the ISC license.
198
198
  * See the LICENSE file in the root directory of this source tree.
199
- */const Mv=[["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"}]],Lv=ne("eye-off",Mv);/**
199
+ */const Lv=[["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"}]],Nv=ne("eye-off",Lv);/**
200
200
  * @license lucide-react v0.563.0 - ISC
201
201
  *
202
202
  * This source code is licensed under the ISC license.
203
203
  * See the LICENSE file in the root directory of this source tree.
204
- */const Nv=[["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"}]],Bv=ne("eye",Nv);/**
204
+ */const Bv=[["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"}]],Fv=ne("eye",Bv);/**
205
205
  * @license lucide-react v0.563.0 - ISC
206
206
  *
207
207
  * This source code is licensed under the ISC license.
208
208
  * See the LICENSE file in the root directory of this source tree.
209
- */const Fv=[["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"}]],zv=ne("file-check",Fv);/**
209
+ */const zv=[["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"}]],qv=ne("file-check",zv);/**
210
210
  * @license lucide-react v0.563.0 - ISC
211
211
  *
212
212
  * This source code is licensed under the ISC license.
213
213
  * See the LICENSE file in the root directory of this source tree.
214
- */const qv=[["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"}]],Uv=ne("file-pen",qv);/**
214
+ */const Uv=[["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"}]],Wv=ne("file-pen",Uv);/**
215
215
  * @license lucide-react v0.563.0 - ISC
216
216
  *
217
217
  * This source code is licensed under the ISC license.
218
218
  * See the LICENSE file in the root directory of this source tree.
219
- */const Wv=[["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"}]],gp=ne("file-plus",Wv);/**
219
+ */const Kv=[["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"}]],yp=ne("file-plus",Kv);/**
220
220
  * @license lucide-react v0.563.0 - ISC
221
221
  *
222
222
  * This source code is licensed under the ISC license.
223
223
  * See the LICENSE file in the root directory of this source tree.
224
- */const Kv=[["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"}]],Vv=ne("file-question-mark",Kv);/**
224
+ */const Vv=[["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"}]],Hv=ne("file-question-mark",Vv);/**
225
225
  * @license lucide-react v0.563.0 - ISC
226
226
  *
227
227
  * This source code is licensed under the ISC license.
228
228
  * See the LICENSE file in the root directory of this source tree.
229
- */const Hv=[["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"}]],Pa=ne("file-text",Hv);/**
229
+ */const Gv=[["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"}]],Pa=ne("file-text",Gv);/**
230
230
  * @license lucide-react v0.563.0 - ISC
231
231
  *
232
232
  * This source code is licensed under the ISC license.
233
233
  * See the LICENSE file in the root directory of this source tree.
234
- */const Gv=[["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"}]],Qv=ne("file-x",Gv);/**
234
+ */const Qv=[["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"}]],Jv=ne("file-x",Qv);/**
235
235
  * @license lucide-react v0.563.0 - ISC
236
236
  *
237
237
  * This source code is licensed under the ISC license.
238
238
  * See the LICENSE file in the root directory of this source tree.
239
- */const Jv=[["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"}]],Yv=ne("files",Jv);/**
239
+ */const Yv=[["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"}]],Xv=ne("files",Yv);/**
240
240
  * @license lucide-react v0.563.0 - ISC
241
241
  *
242
242
  * This source code is licensed under the ISC license.
243
243
  * See the LICENSE file in the root directory of this source tree.
244
- */const Xv=[["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"}]],yp=ne("folder-open",Xv);/**
244
+ */const Zv=[["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"}]],bp=ne("folder-open",Zv);/**
245
245
  * @license lucide-react v0.563.0 - ISC
246
246
  *
247
247
  * This source code is licensed under the ISC license.
248
248
  * See the LICENSE file in the root directory of this source tree.
249
- */const Zv=[["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"}]],ro=ne("folder",Zv);/**
249
+ */const eS=[["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"}]],ro=ne("folder",eS);/**
250
250
  * @license lucide-react v0.563.0 - ISC
251
251
  *
252
252
  * This source code is licensed under the ISC license.
253
253
  * See the LICENSE file in the root directory of this source tree.
254
- */const eS=[["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"}]],tS=ne("funnel",eS);/**
254
+ */const tS=[["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"}]],nS=ne("funnel",tS);/**
255
255
  * @license lucide-react v0.563.0 - ISC
256
256
  *
257
257
  * This source code is licensed under the ISC license.
258
258
  * See the LICENSE file in the root directory of this source tree.
259
- */const nS=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],rS=ne("gauge",nS);/**
259
+ */const rS=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],oS=ne("gauge",rS);/**
260
260
  * @license lucide-react v0.563.0 - ISC
261
261
  *
262
262
  * This source code is licensed under the ISC license.
263
263
  * See the LICENSE file in the root directory of this source tree.
264
- */const oS=[["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"}]],Nr=ne("git-branch",oS);/**
264
+ */const sS=[["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"}]],Nr=ne("git-branch",sS);/**
265
265
  * @license lucide-react v0.563.0 - ISC
266
266
  *
267
267
  * This source code is licensed under the ISC license.
268
268
  * See the LICENSE file in the root directory of this source tree.
269
- */const sS=[["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"}]],iS=ne("git-commit-horizontal",sS);/**
269
+ */const iS=[["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"}]],aS=ne("git-commit-horizontal",iS);/**
270
270
  * @license lucide-react v0.563.0 - ISC
271
271
  *
272
272
  * This source code is licensed under the ISC license.
273
273
  * See the LICENSE file in the root directory of this source tree.
274
- */const aS=[["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"}]],cS=ne("git-fork",aS);/**
274
+ */const cS=[["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"}]],lS=ne("git-fork",cS);/**
275
275
  * @license lucide-react v0.563.0 - ISC
276
276
  *
277
277
  * This source code is licensed under the ISC license.
278
278
  * See the LICENSE file in the root directory of this source tree.
279
- */const lS=[["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"}]],bp=ne("layers",lS);/**
279
+ */const dS=[["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"}]],xp=ne("layers",dS);/**
280
280
  * @license lucide-react v0.563.0 - ISC
281
281
  *
282
282
  * This source code is licensed under the ISC license.
283
283
  * See the LICENSE file in the root directory of this source tree.
284
- */const dS=[["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"}]],uS=ne("layout-dashboard",dS);/**
284
+ */const uS=[["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"}]],pS=ne("layout-dashboard",uS);/**
285
285
  * @license lucide-react v0.563.0 - ISC
286
286
  *
287
287
  * This source code is licensed under the ISC license.
288
288
  * See the LICENSE file in the root directory of this source tree.
289
- */const pS=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Un=ne("loader-circle",pS);/**
289
+ */const fS=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Un=ne("loader-circle",fS);/**
290
290
  * @license lucide-react v0.563.0 - ISC
291
291
  *
292
292
  * This source code is licensed under the ISC license.
293
293
  * See the LICENSE file in the root directory of this source tree.
294
- */const fS=[["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"}]],hS=ne("message-circle",fS);/**
294
+ */const hS=[["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"}]],mS=ne("message-circle",hS);/**
295
295
  * @license lucide-react v0.563.0 - ISC
296
296
  *
297
297
  * This source code is licensed under the ISC license.
298
298
  * See the LICENSE file in the root directory of this source tree.
299
- */const mS=[["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"}]],gS=ne("monitor",mS);/**
299
+ */const gS=[["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"}]],yS=ne("monitor",gS);/**
300
300
  * @license lucide-react v0.563.0 - ISC
301
301
  *
302
302
  * This source code is licensed under the ISC license.
303
303
  * See the LICENSE file in the root directory of this source tree.
304
- */const yS=[["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"}]],bS=ne("network",yS);/**
304
+ */const bS=[["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"}]],xS=ne("network",bS);/**
305
305
  * @license lucide-react v0.563.0 - ISC
306
306
  *
307
307
  * This source code is licensed under the ISC license.
308
308
  * See the LICENSE file in the root directory of this source tree.
309
- */const xS=[["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"}]],vS=ne("notebook-pen",xS);/**
309
+ */const vS=[["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"}]],SS=ne("notebook-pen",vS);/**
310
310
  * @license lucide-react v0.563.0 - ISC
311
311
  *
312
312
  * This source code is licensed under the ISC license.
313
313
  * See the LICENSE file in the root directory of this source tree.
314
- */const SS=[["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"}]],wS=ne("package",SS);/**
314
+ */const wS=[["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"}]],kS=ne("package",wS);/**
315
315
  * @license lucide-react v0.563.0 - ISC
316
316
  *
317
317
  * This source code is licensed under the ISC license.
318
318
  * See the LICENSE file in the root directory of this source tree.
319
- */const kS=[["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"}]],CS=ne("palette",kS);/**
319
+ */const CS=[["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"}]],jS=ne("palette",CS);/**
320
320
  * @license lucide-react v0.563.0 - ISC
321
321
  *
322
322
  * This source code is licensed under the ISC license.
323
323
  * See the LICENSE file in the root directory of this source tree.
324
- */const jS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],ES=ne("panel-left",jS);/**
324
+ */const ES=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],TS=ne("panel-left",ES);/**
325
325
  * @license lucide-react v0.563.0 - ISC
326
326
  *
327
327
  * This source code is licensed under the ISC license.
328
328
  * See the LICENSE file in the root directory of this source tree.
329
- */const TS=[["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"}]],AS=ne("plug",TS);/**
329
+ */const AS=[["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"}]],RS=ne("plug",AS);/**
330
330
  * @license lucide-react v0.563.0 - ISC
331
331
  *
332
332
  * This source code is licensed under the ISC license.
333
333
  * See the LICENSE file in the root directory of this source tree.
334
- */const RS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],OS=ne("plus",RS);/**
334
+ */const OS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],_S=ne("plus",OS);/**
335
335
  * @license lucide-react v0.563.0 - ISC
336
336
  *
337
337
  * This source code is licensed under the ISC license.
338
338
  * See the LICENSE file in the root directory of this source tree.
339
- */const _S=[["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"}]],ps=ne("refresh-cw",_S);/**
339
+ */const PS=[["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"}]],ps=ne("refresh-cw",PS);/**
340
340
  * @license lucide-react v0.563.0 - ISC
341
341
  *
342
342
  * This source code is licensed under the ISC license.
343
343
  * See the LICENSE file in the root directory of this source tree.
344
- */const PS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Hc=ne("search",PS);/**
344
+ */const IS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Hc=ne("search",IS);/**
345
345
  * @license lucide-react v0.563.0 - ISC
346
346
  *
347
347
  * This source code is licensed under the ISC license.
348
348
  * See the LICENSE file in the root directory of this source tree.
349
- */const IS=[["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"}]],DS=ne("settings-2",IS);/**
349
+ */const DS=[["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"}]],$S=ne("settings-2",DS);/**
350
350
  * @license lucide-react v0.563.0 - ISC
351
351
  *
352
352
  * This source code is licensed under the ISC license.
353
353
  * See the LICENSE file in the root directory of this source tree.
354
- */const $S=[["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"}]],MS=ne("settings",$S);/**
354
+ */const MS=[["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"}]],LS=ne("settings",MS);/**
355
355
  * @license lucide-react v0.563.0 - ISC
356
356
  *
357
357
  * This source code is licensed under the ISC license.
358
358
  * See the LICENSE file in the root directory of this source tree.
359
- */const LS=[["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"}]],NS=ne("shield-alert",LS);/**
359
+ */const NS=[["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"}]],BS=ne("shield-alert",NS);/**
360
360
  * @license lucide-react v0.563.0 - ISC
361
361
  *
362
362
  * This source code is licensed under the ISC license.
363
363
  * See the LICENSE file in the root directory of this source tree.
364
- */const BS=[["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"}]],FS=ne("shield-check",BS);/**
364
+ */const FS=[["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"}]],zS=ne("shield-check",FS);/**
365
365
  * @license lucide-react v0.563.0 - ISC
366
366
  *
367
367
  * This source code is licensed under the ISC license.
368
368
  * See the LICENSE file in the root directory of this source tree.
369
- */const zS=[["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"}]],qS=ne("sigma",zS);/**
369
+ */const qS=[["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"}]],US=ne("sigma",qS);/**
370
370
  * @license lucide-react v0.563.0 - ISC
371
371
  *
372
372
  * This source code is licensed under the ISC license.
373
373
  * See the LICENSE file in the root directory of this source tree.
374
- */const US=[["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"}]],xp=ne("sparkles",US);/**
374
+ */const WS=[["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"}]],vp=ne("sparkles",WS);/**
375
375
  * @license lucide-react v0.563.0 - ISC
376
376
  *
377
377
  * This source code is licensed under the ISC license.
378
378
  * See the LICENSE file in the root directory of this source tree.
379
- */const WS=[["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"}]],KS=ne("square-dashed",WS);/**
379
+ */const KS=[["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"}]],VS=ne("square-dashed",KS);/**
380
380
  * @license lucide-react v0.563.0 - ISC
381
381
  *
382
382
  * This source code is licensed under the ISC license.
383
383
  * See the LICENSE file in the root directory of this source tree.
384
- */const VS=[["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"}]],HS=ne("tag",VS);/**
384
+ */const HS=[["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"}]],GS=ne("tag",HS);/**
385
385
  * @license lucide-react v0.563.0 - ISC
386
386
  *
387
387
  * This source code is licensed under the ISC license.
388
388
  * See the LICENSE file in the root directory of this source tree.
389
- */const GS=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],QS=ne("terminal",GS);/**
389
+ */const QS=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],JS=ne("terminal",QS);/**
390
390
  * @license lucide-react v0.563.0 - ISC
391
391
  *
392
392
  * This source code is licensed under the ISC license.
393
393
  * See the LICENSE file in the root directory of this source tree.
394
- */const JS=[["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"}]],vp=ne("trash-2",JS);function YS(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 XS(e,t){const n=e.mode??"both";return n==="both"||n===t}function ZS({open:e,onClose:t}){const{state:n,dispatch:r}=et(),[o,i]=p.useState(""),[a,c]=p.useState(0),l=p.useRef(null);p.useEffect(()=>{e&&(i(""),c(0))},[e]);const u=p.useMemo(()=>{const m=x=>r(x),S=()=>t(),v=x=>()=>{x(),S()},b=[["Files","files",Yv],["Lineage","lineage",cS],["Git","git",Nr],["Block Library","block_library",Oa],["Apps","apps",bS],["Connections","connection",AS]],w=[{mode:"obsidian",label:"Obsidian"},{mode:"paper",label:"Paper"},{mode:"white",label:"White"}],j=[];j.push({id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",icon:ES,shortcut:"⌘B",mode:"studio",run:v(()=>m({type:"TOGGLE_SIDEBAR"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",icon:n.inspectorOpen?Lv:Bv,shortcut:"⌘⇧I",mode:"studio",run:v(()=>m({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",icon:uS,shortcut:"⌘D",run:v(()=>m({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:QS,shortcut:"⌘J",mode:"studio",run:v(()=>m({type:"TOGGLE_DEV_PANEL"}))});for(const[x,E,P]of b)j.push({id:`panel.${E}`,label:`Go to ${x}`,group:"Navigate",icon:P,mode:"studio",run:v(()=>{m({type:"SET_SIDEBAR_PANEL",panel:E}),E!=="lineage"&&!n.sidebarOpen&&m({type:"TOGGLE_SIDEBAR"})})});j.push({id:"notebook.new",label:"New notebook…",group:"Create",icon:gp,mode:"studio",run:v(()=>m({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:KS,mode:"studio",run:v(()=>m({type:"OPEN_NEW_BLOCK_MODAL"}))});const C=n.themeMode==="dark"||n.themeMode==="midnight"?"obsidian":n.themeMode==="light"?"paper":n.themeMode==="arctic"?"white":n.themeMode;for(const x of w)x.mode!==C&&j.push({id:`theme.${x.mode}`,label:`Switch to ${x.label}`,group:"Theme",icon:CS,keywords:"appearance color",run:v(()=>m({type:"SET_THEME",mode:x.mode}))});return j},[n.sidebarOpen,n.inspectorOpen,n.themeMode,n.dashboardMode,n.appMode,n.sidebarPanel,r,t]),h=p.useMemo(()=>{const S=u.filter(v=>XS(v,n.appMode)).map(v=>({a:v,s:YS(v,o)})).filter(v=>v.s>0);return S.sort((v,b)=>b.s-v.s),S.map(v=>v.a)},[u,o,n.appMode]);p.useEffect(()=>{c(0)},[o]),p.useEffect(()=>{var S;const m=(S=l.current)==null?void 0:S.querySelector(`[data-palette-idx="${a}"]`);m==null||m.scrollIntoView({block:"nearest"})},[a]);const d=m=>{var S;m.key==="ArrowDown"?(m.preventDefault(),c(v=>Math.min(h.length-1,v+1))):m.key==="ArrowUp"?(m.preventDefault(),c(v=>Math.max(0,v-1))):m.key==="Enter"&&(m.preventDefault(),(S=h[a])==null||S.run())};let f="";return s.jsx(Ny,{open:e,onOpenChange:m=>!m&&t(),children:s.jsxs(By,{children:[s.jsx(Fy,{style:{position:"fixed",inset:0,background:pe("surfaceOverlay"),zIndex:io.overlay}}),s.jsxs(zy,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:pe("surfaceRaised"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.lg,boxShadow:pe("shadowLg"),zIndex:io.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:d,children:[s.jsx(qy,{style:{position:"absolute",left:-9999},children:"Command palette"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:be[2],padding:`${be[3]}px ${be[4]}px`,borderBottom:`1px solid ${pe("borderSubtle")}`},children:[s.jsx(Iv,{size:14,strokeWidth:1.75,color:pe("textMuted")}),s.jsx("input",{autoFocus:!0,value:o,onChange:m=>i(m.target.value),placeholder:"Type a command…",style:{flex:1,border:"none",outline:"none",background:"transparent",color:pe("textPrimary"),fontSize:Ze.md}})]}),s.jsxs("div",{ref:l,style:{maxHeight:360,overflowY:"auto",padding:`${be[1]}px 0`},children:[h.length===0&&s.jsx("div",{style:{padding:be[4],fontSize:Ze.sm,color:pe("textMuted"),textAlign:"center"},children:"No matching commands"}),h.map((m,S)=>{const v=m.group!==f;f=m.group;const b=S===a,w=m.icon;return s.jsxs(qe.Fragment,{children:[v&&s.jsx("div",{style:{padding:`${be[2]}px ${be[4]}px ${be[1]}px`},children:s.jsx(up,{tone:"neutral",children:m.group})}),s.jsxs("div",{"data-palette-idx":S,role:"option","aria-selected":b,onMouseEnter:()=>c(S),onMouseDown:j=>{j.preventDefault(),m.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:be[3],padding:`${be[2]}px ${be[4]}px`,fontSize:Ze.sm,cursor:"pointer",background:b?pe("surfaceHover"):"transparent",color:pe("textPrimary")},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:be[2],minWidth:0,flex:1},children:[w&&s.jsx(w,{size:14,strokeWidth:1.75}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.label})]}),m.shortcut&&s.jsx(Ix,{shortcut:m.shortcut})]})]},m.id)})]})]})]})})}function zi(e){const t=Dt(e);if(!t)return;const n=wp(t.kind),r=tw(t.source);if(!n||!r)return;const o=Cp(t.limit);return{kind:n,source:r,name:yt(t.name),sourcePath:yt(t.sourcePath),metrics:qi(t.metrics),dimensions:qi(t.dimensions),filters:rw(t.filters),timeDimension:ow(t.timeDimension),orderBy:sw(t.orderBy),parameters:iw(t.parameters),parameterValues:dw(t.parameterValues),persistence:uw(t.persistence),trustState:kp(t.trustState),compiledSql:yt(t.compiledSql),executionReceipt:Sp(t.executionReceipt),executableArtifact:ew(t.executableArtifact),filterableColumns:nw(t.filterableColumns),...o===void 0?{}:{limit:o}}}function ew(e){const t=Dt(e);if(!t||t.version!==1)return;const n=wp(t.kind),r=kp(t.trustState),o=yt(t.semanticAdapter),i=Dt(t.previewPolicy),a=(i==null?void 0:i.mode)==="read_only_bounded"||(i==null?void 0:i.mode)==="compiler_governed"?i.mode:void 0,c=Sp(t.receipt),l={dqlFingerprint:pt(t.dqlFingerprint),sourceFingerprint:pt(t.sourceFingerprint),compiledSqlFingerprint:pt(t.compiledSqlFingerprint),normalizedSqlFingerprint:pt(t.normalizedSqlFingerprint),parameterFingerprint:pt(t.parameterFingerprint),provenanceFingerprint:pt(t.provenanceFingerprint),targetFingerprint:pt(t.targetFingerprint),snapshotFingerprint:pt(t.snapshotFingerprint),planFingerprint:pt(t.planFingerprint)};if(!n||!r||!o||!a||!c||Object.values(l).some(h=>!h))return;const u=Cp(i==null?void 0:i.rowLimit);if(!(a==="read_only_bounded"&&u===void 0))return{version:1,kind:n,...l,semanticAdapter:o,previewPolicy:{mode:a,...u===void 0?{}:{rowLimit:u}},trustState:r,receipt:c}}function tw(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function nw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n),o=yt(r==null?void 0:r.column),i=yt(r==null?void 0:r.predicateTarget);return o&&i?[{column:o,predicateTarget:i}]:[]});return t.length>0?t:void 0}function Sp(e){const t=Dt(e);if(!t)return;const n=pt(t.sourceFingerprint),r=pt(t.compiledSqlFingerprint),o=pt(t.parameterFingerprint),i=pt(t.resultFingerprint);return n&&r&&o&&i?{sourceFingerprint:n,compiledSqlFingerprint:r,parameterFingerprint:o,resultFingerprint:i}:void 0}function pt(e){return typeof e=="string"&&/^[a-f0-9]{64}$/i.test(e.trim())?e.trim().toLowerCase():void 0}function wp(e){return e==="certified_block"||e==="semantic_block"||e==="sql_block"?e:void 0}function rw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n);if(!r)return[];const o=yt(r.dimension),i=yt(r.operator);return!o||!i?[]:[{dimension:o,operator:i,values:qi(r.values)??[]}]});return t.length?t:void 0}function ow(e){const t=Dt(e);if(!t)return;const n=yt(t.name),r=yt(t.granularity);return n&&r?{name:n,granularity:r}:void 0}function sw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n);if(!r)return[];const o=yt(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 iw(e){if(!Array.isArray(e))return;const t=new Set,n=e.flatMap(r=>{const o=Dt(r),i=yt(o==null?void 0:o.name),a=aw(o==null?void 0:o.type),c=cw(o==null?void 0:o.policy);if(!o||!i||!a||!c||t.has(i))return[];t.add(i);const l=lw(o.binding);return[{name:i,type:a,required:o.required===!0,...o.default===void 0?{}:{default:o.default},policy:c,...l?{binding:l}:{}}]});return n.length?n:void 0}function aw(e){return e==="string"||e==="number"||e==="boolean"||e==="date"||e==="string[]"||e==="number[]"||e==="date[]"?e:void 0}function cw(e){return e==="dynamic"||e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:void 0}function lw(e){const t=Dt(e);if(!t)return;if(t.kind==="sql_value")return{kind:"sql_value"};if(t.kind==="limit")return{kind:"limit"};const n=yt(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 dw(e){const t=Dt(e);if(!t)return;const n=Object.entries(t).filter(([r])=>r.trim().length>0);return n.length?Object.fromEntries(n):void 0}function uw(e){return e==="transient"||e==="saved"?e:void 0}function kp(e){return e==="certified"||e==="governed"||e==="review_required"?e:void 0}function Dt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function yt(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function qi(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 Cp(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}const jp="dql_token",Gc="dql.server-token.v1";function pw(e){var r;return((r=new URLSearchParams(e.replace(/^#/,"")).get(jp))==null?void 0:r.trim())||void 0}function fw(e){const t=new URLSearchParams(e.replace(/^#/,""));t.delete(jp);const n=t.toString();return n?`#${n}`:""}function hw(){var e;if(!(typeof window>"u"))try{const t=pw(window.location.hash);if(t){window.sessionStorage.setItem(Gc,t);const n=fw(window.location.hash);return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${n}`),t}return((e=window.sessionStorage.getItem(Gc))==null?void 0:e.trim())||void 0}catch{return}}const Qc=hw();function lr(e){const t=new Headers(e);return Qc&&t.set("Authorization",`Bearer ${Qc}`),t}async function Ep(e,t,n){const r=await fetch(e,{headers:lr({Accept:"text/event-stream"}),credentials:"same-origin",cache:"no-store",signal:n});if(!r.ok)throw new Error(`Event stream failed with HTTP ${r.status}.`);if(!r.body)throw new Error("Event stream response did not include a body.");const o=r.body.getReader(),i=new TextDecoder;let a="",c="message",l=[];const u=()=>{l.length>0&&t({event:c,data:l.join(`
395
- `)}),c="message",l=[]};for(;!n.aborted;){const h=await o.read();a+=i.decode(h.value,{stream:!h.done});const d=a.split(/\r?\n/);a=d.pop()??"";for(const f of d)if(f==="")u();else if(!f.startsWith(":")){const m=f.indexOf(":"),S=m<0?f:f.slice(0,m),v=m<0?"":f.slice(m+1).replace(/^ /,"");S==="event"&&(c=v||"message"),S==="data"&&l.push(v)}if(h.done){u();return}}}const mw={totals:{modelsScanned:0,businessModels:0,plumbingExcluded:0,metricsFound:0},willGenerate:0,willSkip:0,domains:[],config:{businessLayers:[],excludeLayers:[],maxPerDomain:0,minScore:0,aiEnrichment:"auto"}};function Ko(){return{total:0,tracked:0,changed:0,untracked:0,ignored:0,paths:[]}}const Qr=window.location.origin;class St extends Error{constructor(n){super(n.message);Pe(this,"status");Pe(this,"code");Pe(this,"recoverable");Pe(this,"details");Pe(this,"nextActions");Pe(this,"requestId");Pe(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 Ui(e,t){const n=t.trim()||e.statusText||`HTTP ${e.status}`;if(!t.trim())return new St({message:n,status:e.status});try{const r=JSON.parse(t),o=Array.isArray(r==null?void 0:r.errors)?r.errors.filter(a=>typeof a=="string"&&a.trim().length>0):[],i=typeof(r==null?void 0:r.friendlyMessage)=="string"&&r.friendlyMessage.trim()?r.friendlyMessage: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:o.length>0?`${o.slice(0,3).join(" ")}${o.length>3?` ${o.length-3} more blockers.`:""}`:n;return new St({message:i,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)??(typeof(r==null?void 0:r.error)=="string"&&r.error.trim()&&r.error!==i?{technicalDetails:r.error}:o.length>0?{errors:o,draft:r==null?void 0:r.draft}:void 0),nextActions:Array.isArray(r==null?void 0:r.nextActions)?r.nextActions.filter(a=>typeof a=="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 St({message:n,status:e.status})}}const Js=new Map;async function k(e,t){if(((t==null?void 0:t.method)??"GET").toUpperCase()==="GET"&&!(t!=null&&t.signal)&&!(t!=null&&t.body)){const o=Js.get(e);if(o)return o;const i=Jc(e,t).finally(()=>{Js.delete(e)});return Js.set(e,i),i}return Jc(e,t)}async function Jc(e,t){var r;let n;try{const o=lr(t==null?void 0:t.headers);o.has("Content-Type")||o.set("Content-Type","application/json"),n=await fetch(`${Qr}${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 Ui(n,o)}if(n.status!==204)return n.json()}async function gw(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 a=c=>{const l=c.split(/\r?\n/);let u="message";const h=[];for(const f of l)f.startsWith("event:")&&(u=f.slice(6).trim()),f.startsWith("data:")&&h.push(f.slice(5).trimStart());if(h.length===0)return;const d=JSON.parse(h.join(`
396
- `));if(u==="agent-run-event")t({kind:"event",event:d});else if(u==="agent-run-answer-delta"){const f=typeof(d==null?void 0:d.delta)=="string"?d.delta:"";f&&t({kind:"answer-delta",delta:f})}else if(u==="agent-run-complete")i=d,t({kind:"complete",run:i});else if(u==="agent-run-error")throw new Error(typeof(d==null?void 0:d.error)=="string"?d.error:"Agent run failed.")};for(;;){const{value:c,done:l}=await n.read();if(c){o+=r.decode(c,{stream:!l});let u=o.search(/\r?\n\r?\n/);for(;u>=0;){const h=o.slice(0,u);o=o.slice(o[u]==="\r"?u+4:u+2),a(h),u=o.search(/\r?\n\r?\n/)}}if(l)break}if(o.trim()&&a(o),!i)throw new Error("Agent run stream ended before completion.");return i}function an(e){const t=Array.isArray(e==null?void 0:e.columns)?e.columns.map(a=>typeof a=="string"?a:typeof(a==null?void 0:a.name)=="string"?a.name:String(a)):[],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,r=Array.isArray(e==null?void 0:e.rows)?e.rows:[],o=t.length>0?t:r.find(a=>a&&typeof a=="object"&&!Array.isArray(a))?Object.keys(r.find(a=>a&&typeof a=="object"&&!Array.isArray(a))):r.find(a=>Array.isArray(a))?r.find(a=>Array.isArray(a)).map((a,c)=>`column_${c+1}`):[],i=r.map(a=>{if(Array.isArray(a))return Object.fromEntries(o.map((c,l)=>[c,a[l]]));if(a&&typeof a=="object"){const c=a;return Object.fromEntries(o.map(l=>[l,c[l]]))}return Object.fromEntries(o.map(c=>[c,void 0]))});return{columns:o,rows:i,...typeof(e==null?void 0:e.resultFingerprint)=="string"?{resultFingerprint:e.resultFingerprint}:{},...e!=null&&e.executionReceipt&&typeof e.executionReceipt=="object"?{executionReceipt:e.executionReceipt}:{},...typeof(e==null?void 0:e.trustState)=="string"?{trustState:e.trustState}:{},...typeof(e==null?void 0:e.answerTier)=="string"?{answerTier:e.answerTier}:{},rowCount:typeof(e==null?void 0:e.rowCount)=="number"?e.rowCount:i.length,executionTime:(e==null?void 0:e.executionTime)??(e==null?void 0:e.executionTimeMs)??0,...n?{semanticRefs:n}:{}}}function Vt(e){var n;const t=e!=null&&e.resultPreview&&typeof e.resultPreview=="object"?an(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:zi(e==null?void 0:e.dqlArtifact),dqlPromotionAction:Ew((e==null?void 0:e.dqlPromotionAction)??((n=e==null?void 0:e.dqlPromotion)==null?void 0:n.recommendedAction)),dqlPromotion:Tp(e==null?void 0:e.dqlPromotion),researchPlan:yw(e==null?void 0:e.researchPlan),reviewChecklist:Cw(e==null?void 0:e.reviewChecklist,e),...t?{resultPreview:t}:{resultPreview:void 0}}}function yw(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",a=r.status==="ready"||r.status==="error"?r.status:"not_run",c=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",l=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:bw(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:Ce(n.evidenceCount),relationCount:Ce(n.relationCount),missingContextCount:Ce(n.missingContextCount)},preview:{status:a,...l===void 0?{}:{rowCount:l}},promotion:{path:c,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 bw(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 Ce(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function rr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function xw(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{totalReviewCount:Ce(t.totalReviewCount),openReviewCount:Ce(t.openReviewCount),terminalReviewCount:Ce(t.terminalReviewCount),draftCreatedCount:Ce(t.draftCreatedCount),certifiedCount:Ce(t.certifiedCount),completedCount:Ce(t.completedCount),rejectedCount:Ce(t.rejectedCount),draftCreationRate:rr(t.draftCreationRate),certifyConversionRate:rr(t.certifyConversionRate),medianOpenReviewAgeMs:rr(t.medianOpenReviewAgeMs),medianTimeToDraftMs:rr(t.medianTimeToDraftMs),medianTimeToCertificationMs:rr(t.medianTimeToCertificationMs),medianTimeToTerminalMs:rr(t.medianTimeToTerminalMs)}}function vw(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:{},a=t.limits&&typeof t.limits=="object"?t.limits:{};return{counts:{totalRuns:Ce(n.totalRuns),activeRuns:Ce(n.activeRuns),closedRuns:Ce(n.closedRuns),notebooks:Ce(n.notebooks),domains:Ce(n.domains),owners:Ce(n.owners),sourceLinkedRuns:Ce(n.sourceLinkedRuns)},health:{staleOpenRuns:Ce(r.staleOpenRuns),expiredOpenRuns:Ce(r.expiredOpenRuns),staleThresholdDays:Ce(r.staleThresholdDays)||7,expiredThresholdDays:Ce(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:Ce(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:Ce(a.pageSize)||25,maxPageSize:Ce(a.maxPageSize)||500,sourceCoverageLimit:Ce(a.sourceCoverageLimit)||1e4,seedCellLimit:Ce(a.seedCellLimit)||1e3},warnings:Array.isArray(t.warnings)?t.warnings.filter(c=>typeof c=="string"):[]}}function Sw(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 ww(e){const t=typeof e=="string"?e:"";return(t.split(/[\\/]/).pop()??t).replace(/\.dqlnb$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()||"Untitled notebook"}function kw(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 Vo(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 Cw(e,t){var u,h;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(d=>typeof d=="string"):[],warnings:Array.isArray(e.warnings)?e.warnings.filter(d=>typeof d=="string"):[],items:e.items.map(d=>({id:typeof d.id=="string"?d.id:"item",label:typeof d.label=="string"?d.label:"Review item",status:d.status==="passed"||d.status==="pending"||d.status==="warning"||d.status==="blocked"?d.status:"pending",detail:typeof d.detail=="string"?d.detail:""}))};const n=!!t.reviewedSql,r=n||!!t.generatedSql,o=((u=t.resultPreview)==null?void 0:u.rowCount)??((h=t.resultPreview)==null?void 0:h.rows.length)??0,i=!!(t.resultPreview&&(t.resultPreview.columns.length>0||o>0)),a=!!t.draftBlockPath,c=!!(t.contextPackId||t.evidence),l=t.dqlPromotionAction==="reuse_existing";return{readyForDqlDraft:!!(!l&&t.question&&n&&c&&t.status!=="error"),readyForCertificationReview:!!(!l&&t.question&&n&&c&&i&&a),blockers:t.status==="error"?[t.error??"Preview failed."]:[],warnings:i||l?[]:["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||l?"passed":"blocked",detail:l&&!r?"Existing DQL should be reused; no new SQL is required.":r?"SQL is available.":"Add SQL before promotion."},{id:"evidence",label:"Evidence",status:c||l?"passed":"warning",detail:c?"Context evidence is saved.":l?"Reuse evidence is captured in the recommendation.":"Preview and save metadata context."},{id:"preview",label:"Preview",status:i||l?"passed":"pending",detail:i?"Preview result is available.":l?"Certified block reuse does not require a new raw SQL preview.":"Run a bounded preview."},{id:"dql_draft",label:"DQL draft",status:a||l?"passed":"pending",detail:a?`Draft saved at ${t.draftBlockPath}.`:l?"No new DQL draft is required.":"Create a DQL draft after review."}]}}function jw(e){var r,o,i,a;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(c=>({objectKey:typeof c.objectKey=="string"?c.objectKey:void 0,objectType:typeof c.objectType=="string"?c.objectType:void 0,name:typeof c.name=="string"?c.name:"Evidence",role:typeof c.role=="string"?c.role:void 0,reason:typeof c.reason=="string"?c.reason:""})):[],summaries:Array.isArray(t.summaries)?t.summaries.map(c=>({title:typeof c.title=="string"?c.title:"Context",detail:typeof c.detail=="string"?c.detail:"",objectType:typeof c.objectType=="string"?c.objectType:void 0,reason:typeof c.reason=="string"?c.reason:void 0})):[],relations:Array.isArray(t.relations)?t.relations.map(c=>({relation:typeof c.relation=="string"?c.relation:"",name:typeof c.name=="string"?c.name:"Relation",source:typeof c.source=="string"?c.source:"",columns:Array.isArray(c.columns)?c.columns.map(String):[]})).filter(c=>c.relation||c.name):[],missingContext:Array.isArray(t.missingContext)?t.missingContext.map(c=>({kind:typeof c.kind=="string"?c.kind:"metadata",message:typeof c.message=="string"?c.message:"",severity:typeof c.severity=="string"?c.severity:"warning"})).filter(c=>c.message):[],warnings:Array.isArray(t.warnings)?t.warnings.filter(c=>typeof c=="string"):[],topRejected:Array.isArray(t.topRejected)?t.topRejected.map(c=>({name:typeof c.name=="string"?c.name:"Rejected context",objectType:typeof c.objectType=="string"?c.objectType:void 0,reason:typeof c.reason=="string"?c.reason:"",score:typeof c.score=="number"&&Number.isFinite(c.score)?c.score:void 0})).filter(c=>c.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((a=t.counts)==null?void 0:a.warnings)=="number"?t.counts.warnings:0}}}function Ew(e){return e==="reuse_existing"||e==="extend_existing"||e==="create_replacement"||e==="create_new"||e==="review_required"?e:void 0}function Tp(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:""}}function Yc(e){return{id:e.sourceId,sourceId:e.sourceId,qualifiedIdentity:e.qualifiedIdentity,sourceRevision:e.sourceRevision,snapshotId:e.snapshotId,lifecycle:e.lifecycle,trust:e.trust,name:e.name,domain:e.domain??"Unassigned",status:e.lifecycle,owner:e.owner??null,tags:e.tags,path:e.executionRef,fingerprint:e.sourceRevision,lastModified:"",description:e.description??"",chartType:e.capabilities.chartType,filterIds:e.capabilities.filters,dimensionIds:e.capabilities.dimensions,capabilities:e.capabilities,eligibility:e.eligibility,score:e.score??0,reasons:e.reasons}}const B={async listOperations(e=50){return k(`/api/operations?limit=${Math.max(1,Math.min(100,Math.floor(e)))}`)},async getOperation(e){return k(`/api/operations/${encodeURIComponent(e)}`)},async cancelOperation(e){return k(`/api/operations/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestBlockStudioCertification(e){return k("/api/block-studio/certifications",{method:"POST",headers:{"Idempotency-Key":e.idempotencyKey},body:JSON.stringify({source:e.source,path:e.path,metadata:e.metadata,expectedSourceFingerprint:e.expectedSourceFingerprint,clientRevision:e.clientRevision})})},async getDbtFirstModeling(){return k("/api/modeling/dbt-first")},async getDbtModelingNode(e){return k(`/api/modeling/dbt-first/nodes/${encodeURIComponent(e)}`)},async getDbtModelingNodes(e){return k("/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)),e.physicalOnly&&t.set("physicalOnly","true"),k(`/api/modeling/dbt-first/inventory?${t.toString()}`)},async getDomainWorkspaces(){return k("/api/domain-workspaces")},async getRelatedDomainProducts(e){return k(`/api/domain-workspaces/${encodeURIComponent(e)}/related-products`)},async getAllRelatedDomainProducts(){return k("/api/domain-workspaces/related-products")},async getDomainKnowledge(e){return k(`/api/domain-workspaces/${encodeURIComponent(e)}/knowledge`)},async createContextProposal(e){return(await k("/api/context-proposals",{method:"POST",body:JSON.stringify(e)})).proposal},async getContextProposal(e){return(await k(`/api/context-proposals/${encodeURIComponent(e)}`)).proposal},async repreviewContextProposal(e,t,n){return(await k(`/api/context-proposals/${encodeURIComponent(e)}/repreview`,{method:"POST",body:JSON.stringify({selectedOperationIds:t,rebase:(n==null?void 0:n.rebase)===!0})})).proposal},async commitContextProposal(e,t,n){return k(`/api/context-proposals/${encodeURIComponent(e)}/commit`,{method:"POST",body:JSON.stringify({expectedProposalHash:t,idempotencyKey:n})})},async createModelingImport(e){return(await k("/api/modeling/dbt-first/imports",{method:"POST",body:JSON.stringify({source:e})})).session},async previewModelingImport(e,t){return k(`/api/modeling/dbt-first/imports/${encodeURIComponent(e)}/preview`,{method:"POST",body:JSON.stringify(t)})},async previewModelingChange(e,t){return k("/api/modeling/dbt-first/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyModelingChange(e,t,n){return k("/api/modeling/dbt-first/apply",{method:"POST",body:JSON.stringify({change:e,fingerprint:t,expectedSnapshotId:n})})},async validateModelingRelationship(e,t){return(await k("/api/modeling/dbt-first/relationships/validate",{method:"POST",body:JSON.stringify({relationship:e,expectedSnapshotId:t})})).evidence},async previewDbtSourcePatch(e,t){return k("/api/modeling/dbt-first/dbt-source/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyDbtSourcePatch(e,t,n){return k("/api/modeling/dbt-first/dbt-source/apply",{method:"POST",body:JSON.stringify({change:e,expectedFingerprint:t,expectedSnapshotId:n})})},async getSettingsEnvStatus(){try{return await k("/api/settings/env-status")}catch{return{groups:[]}}},async getProposeReadiness(e){try{return await k("/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:mw,proposals:[]}}},async generateProposeDrafts(e){try{return await k("/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 k(`/api/propose/preview?slug=${encodeURIComponent(e)}`)},async aiBuild(e){return k("/api/ai/build",{method:"POST",body:JSON.stringify(e)})},async createAgentRun(e){return(await k("/api/agent-runs",{method:"POST",body:JSON.stringify(e)})).run},async createAgentRunStream(e,t,n){let r;try{r=await fetch(`${Qr}/api/agent-runs?stream=1`,{method:"POST",headers:lr({"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 Ui(r,o)}return gw(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 k(`/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 k(`/api/agent-runs/${encodeURIComponent(e)}`)},async deriveAnalyticalRepair(e,t){return k(`/api/agent-runs/${encodeURIComponent(e)}/analytical-repair`,{method:"POST",body:JSON.stringify({repair:t})})},async repairAgentRunExecution(e,t){return k(`/api/agent-runs/${encodeURIComponent(e)}/repair-execution`,{method:"POST",body:JSON.stringify({threadId:t})})},async repairNotebookCellExecution(e,t,n){var o,i,a,c,l,u;const r=await k("/api/notebook/repair-execution",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig},error:t,failure:(o=e.execution)==null?void 0:o.error,attemptedSql:((i=e.execution)==null?void 0:i.compiledSql)??e.content,executionTarget:e.executionTarget,parameters:((a=e.blockBinding)==null?void 0:a.state)==="bound"?e.blockBinding.parameterValues:e.dqlParameterValues,executionContext:n})});if(n!=null&&n.runId&&typeof((c=r==null?void 0:r.executionContext)==null?void 0:c.runId)=="string"&&r.executionContext.runId!==n.runId)throw new St({message:"The notebook server returned a repair for a different cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:r.executionContext}});return{ok:!0,source:String(r.source??e.content),repairedSql:String(r.repairedSql??""),repairMode:r.repairMode==="ai"?"ai":"deterministic",result:an(r.result),executionTarget:((l=r==null?void 0:r.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((u=r==null?void 0:r.executionTarget)==null?void 0:u.target)==="connection"?{target:"connection",...typeof r.executionTarget.connectionName=="string"?{connectionName:r.executionTarget.connectionName}:{}}: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,executionReceipt:r!=null&&r.executionReceipt&&typeof r.executionReceipt=="object"?r.executionReceipt:void 0}},async cancelAgentRun(e){return k(`/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 k(`/api/agent/threads${n}`)},async createAgentThread(e={}){return(await k("/api/agent/threads",{method:"POST",body:JSON.stringify(e)})).thread},async getAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}`)},async updateAgentThread(e,t){return k(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async archiveAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}/archive`,{method:"POST"})},async deleteAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestCertification(e){return k("/api/agent-runs/request-certification",{method:"POST",body:JSON.stringify(e)})},async getIdentity(){return k("/api/identity")},async getProviderSettings(){try{return await k("/api/settings/providers")}catch{return{providers:[]}}},async getProviderCliStatus(){try{return await k("/api/settings/providers/cli-status")}catch{return{status:{}}}},async saveProviderSettings(e){return k("/api/settings/providers",{method:"POST",body:JSON.stringify(e)})},async startOAuth(e){return k(`/api/auth/${e}/start`,{method:"POST"})},async getOAuthStatus(e){return k(`/api/auth/${e}/status`)},async signOutOAuth(e){return k(`/api/auth/${e}/signout`,{method:"POST"})},async testProviderSettings(e,t){try{return await k("/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 k("/api/settings/mcp")}catch{return{settings:{path:"",entries:[],warnings:[]}}}},async saveRemoteMcpSettings(e){return k("/api/settings/mcp",{method:"POST",body:JSON.stringify({entries:e})})},async recordAgentCorrection(e){return k("/api/agent/learnings/correction",{method:"POST",body:JSON.stringify(e)})},async listAgentHints(e){const t=e?`?status=${encodeURIComponent(e)}`:"";return k(`/api/agent/hints${t}`)},async reviewAgentHint(e,t,n){return k(`/api/agent/hints/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({decision:t,...n?{note:n}:{}})})},async updateAgentHint(e,t){return k(`/api/agent/hints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async transitionAgentHint(e,t){return k(`/api/agent/hints/${encodeURIComponent(e)}/lifecycle`,{method:"POST",body:JSON.stringify(t)})},async listAgentMemory(e){const t=e?`?scope=${encodeURIComponent(e)}`:"";try{return await k(`/api/agent/memory${t}`)}catch{return{memories:[]}}},async saveAgentMemory(e){return k("/api/agent/memory",{method:"POST",body:JSON.stringify(e)})},async deleteAgentMemory(e){return k(`/api/agent/memory?id=${encodeURIComponent(e)}`,{method:"DELETE"})},async ensureAgentMemoryFiles(){return k("/api/agent/memory/default-files",{method:"POST"})},async listNotebooks(){try{return await k("/api/notebooks")}catch{return[]}},async readNotebook(e){return k(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async deleteNotebook(e){return k(`/api/notebooks?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async createNotebook(e,t,n={}){return k("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t,...n})})},async createBlock(e,t){return k("/api/blocks",{method:"POST",body:JSON.stringify({name:e,...t})})},async getBlockLibrary(){try{return await k("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await k("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return k("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await k(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return k("/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 k(`/api/block-studio/catalog${n?`?${n}`:""}`)},async getBlockStudioDbtStatus(){return k("/api/block-studio/dbt-status")},async openBlockStudio(e){return k(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return k(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t,n){return k("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t}),signal:n})},async runBlockStudio(e,t,n){return k("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t,parameters:n})})},async repairAndRunBlockStudio(e,t,n={},r){const o=await k("/api/block-studio/repair-and-run",{method:"POST",body:JSON.stringify({cell:{id:"block-studio-draft",type:"dql",source:e,title:r||"Block Studio draft"},error:t,attemptedSql:e,parameters:n})}),i=String(o.repairedSql??"");return{source:String(o.source??e),repairedSql:i,repairMode:o.repairMode==="ai"?"ai":"deterministic",preview:{sql:i,result:an(o.result)}}},async getCertifiedBlockParameters(e){return k(`/api/blocks/parameters?name=${encodeURIComponent(e)}`)},async invokeCertifiedBlock(e,t,n){var o,i,a,c,l,u;const r=await k("/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:{...an(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((a=r==null?void 0:r.result)==null?void 0:a.blockPath)=="string"?{blockPath:r.result.blockPath}:{},...(c=r==null?void 0:r.result)!=null&&c.chartConfig?{chartConfig:r.result.chartConfig}:{},...Array.isArray((l=r==null?void 0:r.result)==null?void 0:l.parameters)?{parameters:r.result.parameters}:{},...typeof((u=r==null?void 0:r.result)==null?void 0:u.auditId)=="string"?{auditId:r.result.auditId}:{}}}},async addDqlArtifactResultFilter(e,t,n,r,o){const i=await k("/api/dql/artifacts/add-filter",{method:"POST",body:JSON.stringify({artifact:e,resultColumns:t,column:n,value:r,executionTarget:o})}),a=zi(i==null?void 0:i.artifact);if(!a)throw new Error("Adding the filter input returned an invalid artifact contract.");return{artifact:a,parameterName:String((i==null?void 0:i.parameterName)??n)}},async invokeDqlArtifact(e,t,n,r,o){var c,l,u,h,d,f;const i=await k("/api/dql/artifacts/execute",{method:"POST",body:JSON.stringify({artifact:e,parameters:t,question:n,blockName:r,executionTarget:o})}),a=zi(i==null?void 0:i.artifact);if(!a)throw new Error("DQL artifact execution returned an invalid artifact contract.");return{artifact:a,parameters:a.parameters??[],result:{...an(i==null?void 0:i.result),...typeof((c=i==null?void 0:i.result)==null?void 0:c.sql)=="string"?{sql:i.result.sql}:{},...typeof((l=i==null?void 0:i.result)==null?void 0:l.blockName)=="string"?{blockName:i.result.blockName}:{},...typeof((u=i==null?void 0:i.result)==null?void 0:u.blockPath)=="string"?{blockPath:i.result.blockPath}:{},...(h=i==null?void 0:i.result)!=null&&h.chartConfig?{chartConfig:i.result.chartConfig}:{},...Array.isArray((d=i==null?void 0:i.result)==null?void 0:d.parameters)?{parameters:i.result.parameters}:{},...typeof((f=i==null?void 0:i.result)==null?void 0:f.auditId)=="string"?{auditId:i.result.auditId}:{}}}},async composeSemanticBlock(e){return k("/api/block-studio/compose-semantic",{method:"POST",body:JSON.stringify({question:e})})},async saveBlockStudio(e){return k("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAgentBlockDraft(e){return k("/api/block-studio/agent-drafts",{method:"POST",body:JSON.stringify(e)})},async deleteBlockStudio(e){return k(`/api/block-studio/block?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async previewBlockStudioImport(e){return k("/api/block-studio/import/preview",{method:"POST",body:JSON.stringify(e)})},async listBlockStudioImports(){return k("/api/block-studio/imports")},async createBlockStudioImport(e){return k("/api/block-studio/imports",{method:"POST",body:JSON.stringify(e)})},async createDqlGenerationSession(e){return k("/api/block-studio/ai-imports",{method:"POST",body:JSON.stringify(e)})},async getDqlGenerationSession(e){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}`)},async getBlockStudioImport(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}`)},async deleteBlockStudioImport(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}`,{method:"DELETE"})},async clearBlockStudioImports(){return k("/api/block-studio/imports",{method:"DELETE"})},async updateBlockStudioImportCandidate(e,t,n){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async updateDqlGenerationCandidate(e,t,n){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async matchSqlForBlockReuse(e,t){return k("/api/block-studio/match-sql",{method:"POST",body:JSON.stringify({sql:e,...t??{}})})},async previewDqlGenerationCandidate(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/preview`,{method:"POST"})},async certifyDqlGenerationCandidate(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/certify`,{method:"POST"})},async saveSelectedDqlGenerationCandidates(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify(t)})},async runBlockStudioImportCandidate(e,t){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/run`,{method:"POST"})},async saveBlockStudioImportCandidate(e,t){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/save`,{method:"POST"})},async saveAllBlockStudioImportCandidates(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/save-all`,{method:"POST"})},async assistBlockStudioImportCandidate(e,t,n){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/ai-assist`,{method:"POST",body:JSON.stringify({action:n})})},async getSemanticLayerDiagnostics(){return k("/api/semantic-layer/diagnostics")},async reloadSemanticLayer(){return k("/api/semantic-layer/reload",{method:"POST"})},async assessBlockStudioCertification(e){return k("/api/block-studio/certification-check",{method:"POST",body:JSON.stringify({source:e})})},async certifyBlockStudio(e){const t=await fetch(`${Qr}/api/block-studio/certify`,{headers:lr({"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 k("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await k("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await k("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return k("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t,n,r){var i,a,c;const o=await k("/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 St({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{...an(o),executionTarget:((a=o==null?void 0:o.executionTarget)==null?void 0:a.target)==="local"?{target:"local"}:((c=o==null?void 0:o.executionTarget)==null?void 0:c.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 k("/api/ai/sql-draft/preview",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return{ok:!0,result:an(n.result)}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async executeNotebookCell(e,t,n){var o,i,a,c,l,u;const r=await k("/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 St({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((a=r==null?void 0:r.executionContext)==null?void 0:a.cellId)=="string"?r.executionContext.cellId:void 0,runId:typeof((c=r==null?void 0:r.executionContext)==null?void 0:c.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?an(r.result):null,executionTarget:((l=r==null?void 0:r.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((u=r==null?void 0:r.executionTarget)==null?void 0:u.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 k("/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(`${Qr}/api/datasets/import`,{method:"POST",headers:lr(),body:t});if(!n.ok){const r=await n.text().catch(()=>"");throw Ui(n,r)}return n.json()}return k("/api/datasets/import",{method:"POST",body:JSON.stringify(e)})},async refreshDataset(e){return k(`/api/datasets/${encodeURIComponent(e)}/refresh`,{method:"POST"})},async updateDatasetSchema(e,t){return k(`/api/datasets/${encodeURIComponent(e)}/schema`,{method:"POST",body:JSON.stringify({overrides:t})})},async renameDataset(e,t,n){return k(`/api/datasets/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({name:t,alias:n})})},async pinDataset(e,t=!0){return k(`/api/datasets/${encodeURIComponent(e)}/pin`,{method:"POST",body:JSON.stringify({pinned:t})})},async removeDataset(e){await k(`/api/datasets/${encodeURIComponent(e)}`,{method:"DELETE"})},async stageDataset(e){return k("/api/datasets/stage",{method:"POST",body:JSON.stringify(e)})},async listNotebookResearch(e){var o,i,a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P,A;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 k(`/api/notebook/research${n}`);return{runs:r.runs.map(Vt),total:typeof r.total=="number"?r.total:r.runs.length,domains:Array.isArray(r.domains)?r.domains.map(g=>({domain:typeof g.domain=="string"&&g.domain.trim()?g.domain:"uncategorized",total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],owners:Array.isArray(r.owners)?r.owners.map(g=>({owner:typeof g.owner=="string"&&g.owner.trim()?g.owner:"unassigned",total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],intents:Array.isArray(r.intents)?r.intents.map(g=>({intent:Sw(g.intent),total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],notebooks:Array.isArray(r.notebooks)?r.notebooks.map(g=>({path:typeof g.path=="string"&&g.path.trim()?g.path:"notebooks/untitled.dqlnb",title:typeof g.title=="string"&&g.title.trim()?g.title:ww(g.path),total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.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((a=r.counts)==null?void 0:a.needsReview)=="number"?r.counts.needsReview:0,dqlDrafts:typeof((c=r.counts)==null?void 0:c.dqlDrafts)=="number"?r.counts.dqlDrafts:0,errors:typeof((l=r.counts)==null?void 0:l.errors)=="number"?r.counts.errors:0,reuseExisting:typeof((u=r.counts)==null?void 0:u.reuseExisting)=="number"?r.counts.reuseExisting:0,extendExisting:typeof((h=r.counts)==null?void 0:h.extendExisting)=="number"?r.counts.extendExisting:0,replacements:typeof((d=r.counts)==null?void 0:d.replacements)=="number"?r.counts.replacements:0,createNew:typeof((f=r.counts)==null?void 0:f.createNew)=="number"?r.counts.createNew:0,draftReady:typeof((m=r.counts)==null?void 0:m.draftReady)=="number"?r.counts.draftReady:0,certificationReady:typeof((S=r.counts)==null?void 0:S.certificationReady)=="number"?r.counts.certificationReady:0,blocked:typeof((v=r.counts)==null?void 0:v.blocked)=="number"?r.counts.blocked:0,staleOpen:typeof((b=r.counts)==null?void 0:b.staleOpen)=="number"?r.counts.staleOpen:0,expiredOpen:typeof((w=r.counts)==null?void 0:w.expiredOpen)=="number"?r.counts.expiredOpen:0,sourceLinked:typeof((j=r.counts)==null?void 0:j.sourceLinked)=="number"?r.counts.sourceLinked:0,nextActions:kw((C=r.counts)==null?void 0:C.nextActions)},groupCounts:{domains:typeof((x=r.groupCounts)==null?void 0:x.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((E=r.groupCounts)==null?void 0:E.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((P=r.groupCounts)==null?void 0:P.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((A=r.groupCounts)==null?void 0:A.notebooks)=="number"&&Number.isFinite(r.groupCounts.notebooks)?Math.max(0,Math.floor(r.groupCounts.notebooks)):Array.isArray(r.notebooks)?r.notebooks.length:0},reviewMetrics:xw(r.reviewMetrics),limit:r.limit,offset:typeof r.offset=="number"?r.offset:0}},async getNotebookResearchDiagnostics(){const e=await k("/api/notebook/research/diagnostics");return vw(e)},async createNotebookResearch(e){const t=await k("/api/notebook/research",{method:"POST",body:JSON.stringify(e)});return Vt(t.run)},async seedNotebookResearchFromCells(e){const t=await k("/api/notebook/research/seed-cells",{method:"POST",body:JSON.stringify(e)});return{created:Array.isArray(t.created)?t.created.map(Vt):[],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 k("/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(Vt):[],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 k("/api/notebook/research/context-preview",{method:"POST",body:JSON.stringify(e)});return jw(t)},async getNotebookResearch(e){const t=await k(`/api/notebook/research/${encodeURIComponent(e)}`);return Vt(t.run)},async updateNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});return Vt(n.run)},async runNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t??{})});return Vt(n.run)},async checkNotebookResearchReuse(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/reuse-check`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Vt(n.run),promotion:Tp(n.promotion)??n.promotion}},async promoteNotebookResearchToDql(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/promote-dql`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Vt(n.run)}},async getSchema(){try{const e=await fetch(`${Qr}/api/schema`,{headers:lr()});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 k("/api/connections")}catch{return{default:"unknown",connections:{}}}},async previewDbtProfiles(e){return k("/api/connections/dbt-profiles/preview",{method:"POST",body:JSON.stringify({path:e})})},async saveConnections(e,t){return k("/api/connections",{method:"PUT",body:JSON.stringify({connections:e,defaultConnectionName:t})})},async previewConnectionMetadataScope(e,t={}){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope/preview`,{method:"POST",body:JSON.stringify(t)})},async discoverConnectionMetadataScopes(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope/discovery`,{method:"POST"})},async getConnectionMetadataScope(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope`)},async applyConnectionMetadataScope(e,t){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope`,{method:"PUT",body:JSON.stringify(t)})},async refreshConnectionMetadata(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-sync`,{method:"POST"})},async installConnector(e){return k("/api/connectors/install",{method:"POST",body:JSON.stringify({driver:e})})},async testConnection(){try{return await k("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticRuntimeSettings(){return k("/api/semantic-runtime")},async getMetricFlowInstallerStatus(){return k("/api/semantic-runtime/metricflow/installer")},async installMetricFlow(e){return k("/api/semantic-runtime/metricflow/install",{method:"POST",body:JSON.stringify(e?{adapter:e}:{})})},async testDbtCloudSemanticRuntime(e){try{return await k("/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 k("/api/semantic-runtime/dbt-cloud/apply",{method:"POST",body:JSON.stringify(e)})},async setSemanticRuntimePreference(e){return k("/api/semantic-runtime/preference",{method:"POST",body:JSON.stringify({preference:e})})},async getSemanticLayer(){try{return await k("/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 k("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return k(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async getSetupLaunch(){return k("/api/onboarding/launch")},async acknowledgeSetupLaunch(){return k("/api/onboarding/acknowledge",{method:"POST",body:"{}"})},async getOnboardingStatus(){return k("/api/onboarding/status")},async previewDbtOnboarding(e){return k("/api/onboarding/dbt/preview",{method:"POST",body:JSON.stringify(e)})},async applyDbtOnboarding(e){return k("/api/onboarding/dbt/apply",{method:"POST",body:JSON.stringify({...e,fingerprint:e.expectedFingerprint})})},async refreshDbtOnboarding(e={}){return k("/api/onboarding/refresh",{method:"POST",body:JSON.stringify(e)})},async getOnboardingJob(e){return k(`/api/onboarding/jobs/${encodeURIComponent(e)}`)},async cancelOnboardingJob(e){return k(`/api/onboarding/jobs/${encodeURIComponent(e)}`,{method:"DELETE"})},async discoverOnboardingDomains(e={}){return k("/api/onboarding/domains/discover",{method:"POST",body:JSON.stringify(e)})},async applyOnboardingDomains(e){return k("/api/onboarding/domains/apply",{method:"POST",body:JSON.stringify(e)})},async importSemanticLayer(e){return k("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return k("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return k("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return k("/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 k(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[]}}},async getFavorites(){try{return(await k("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await k("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await k("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await k("/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 k(`/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 k(`/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 k("/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 k("/api/semantic-builder/preview",{method:"POST",body:JSON.stringify(e)})}catch(t){return t instanceof St?{error:t.message,code:t.code,details:t.details}:{error:t instanceof Error?t.message:"Failed to preview semantic block"}}},async saveSemanticBuilder(e){return k("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await k("/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=new URLSearchParams({relation:e});try{return await k(`/api/describe-table?${t.toString()}`)}catch{return[]}},async fetchLineage(){try{return await k("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await k(`/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 k(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await k(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBusiness360(e){try{return await k(`/api/lineage/business-360/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await k(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await k(`/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 k(o)}catch{return null}},async fetchGitStatus(){try{return await k("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await k(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await k(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await k("/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 k(`/api/git/diff${r?`?${r}`:""}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}},async fetchGitBranches(){try{return await k("/api/git/branches")}catch{return{inRepo:!1,current:null,branches:[]}}},async fetchGitRemote(){try{return await k("/api/git/remote")}catch{return{inRepo:!1,url:null,name:null}}},async fetchGitGovernedContext(){try{return await k("/api/git/governed-context")}catch{return{inRepo:!1,trackingReady:!1,legacyBroadIgnore:!1,domains:Ko(),skills:Ko(),artifacts:Ko(),learning:Ko()}}},async enableGitGovernedContextTracking(){try{return await k("/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 k("/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 k("/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 k("/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 k("/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 k("/api/git/push",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitPull(){try{return await k("/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 k("/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 k("/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 k("/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 k("/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 k("/api/apps");return e}catch{return[]}},async listAppsStrict(){const{apps:e}=await k("/api/apps");return e},async recommendAppBlocks(e,t){const{blocks:n}=await k("/api/apps/recommend-blocks",{method:"POST",body:JSON.stringify(e),signal:t});return n},async listAppSourceCandidates(e,t={},n){var i;const r=new URLSearchParams;(i=t.query)!=null&&i.trim()&&r.set("q",t.query.trim()),t.cursor&&r.set("cursor",t.cursor),r.set("limit",String(t.limit??50));for(const a of t.lifecycles??[])r.append("lifecycle",a);for(const a of t.domains??[])r.append("domain",a);t.includeDeprecated&&r.set("includeDeprecated","true");const o=await k(`/api/app-builds/${encodeURIComponent(e)}/source-candidates?${r.toString()}`,{signal:n});return{...o,items:o.items.map(Yc)}},async resolveAppSourceCandidates(e,t){const n=await k(`/api/app-builds/${encodeURIComponent(e)}/source-candidates`,{method:"POST",body:JSON.stringify({sourceIds:t})});return{...n,items:n.items.map(Yc)}},async createApp(e){return k("/api/apps",{method:"POST",body:JSON.stringify(e)})},async createAppBuild(e){return k("/api/app-builds",{method:"POST",body:JSON.stringify(e)})},async listAppBuilds(){return k("/api/app-builds")},async proposeAppBuildChanges(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals`,{method:"POST",body:JSON.stringify(t)})},async reviseAppBuildProposal(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals/${encodeURIComponent(t)}/revisions`,{method:"POST",body:JSON.stringify(n)})},async generateAppBuildGap(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals/${encodeURIComponent(t)}/gaps`,{method:"POST",body:JSON.stringify(n)})},async patchAppBuild(e,t,n,r){return k(`/api/app-builds/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({expectedRevision:t,expectedProposalHash:r,operations:n})})},async composeAppBuild(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/compose`,{method:"POST",body:JSON.stringify(t)})},async addAskResultToAppBuild(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/ask-results`,{method:"POST",body:JSON.stringify(t)})},async preflightAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/preflight`,{method:"POST",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async publishAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/publish-to-project`,{method:"POST",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async deleteAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async commitAppBuild(e,t,n){return this.publishAppBuild(e,t,n)},async generateApp(e){try{return await k("/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 k("/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 k(`/api/apps/ai-builds/${encodeURIComponent(e)}`);return t}catch{return null}},async proposeAppAiBuild(e){try{return await k("/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 proposeAppAiBuildInBackground(e){return k("/api/apps/ai-builds/propose-background",{method:"POST",body:JSON.stringify(e)})},async commitAppAiBuild(e,t={}){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}`)}catch{return null}},async deleteApp(e,t){return k(`/api/apps/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({expectedFingerprint:t})})},async restoreApp(e){return k(`/api/app-recoveries/${encodeURIComponent(e)}/restore`,{method:"POST",body:"{}"})},async renameApp(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async attachAppNotebook(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/notebook-candidates`);return t}catch{return[]}},async createAppNotebook(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/notebooks/preview?path=${encodeURIComponent(t)}`)}catch{return null}},async runAppNotebook(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/conversations`);return t}catch{return[]}},async createAppConversation(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`);return n}catch{return null}},async updateAppConversation(e,t,n){try{return await k(`/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 k(`/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 k(`/api/apps/${encodeURIComponent(e)}/investigations${r?`?${r}`:""}`);return o}catch{return[]}},async createAppInvestigation(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}`);return n}catch{return null}},async runAppInvestigation(e,t,n){try{return await k(`/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 k(`/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 k(`/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 k(`/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 k(`/api/apps/${encodeURIComponent(e)}/editor/catalog${r?`?${r}`:""}`)}catch{return null}},async createAppDashboard(e,t){try{return await k(`/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 k(`/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 k(`/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 publishAppToProject(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/publish-to-project`,{method:"POST",body:JSON.stringify(t??{})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteApp(e,t){return B.publishAppToProject(e,t)},async approveAppSemanticTiles(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/approve-semantic`,{method:"POST",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async recommendVisualization(e){try{return await k("/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 k(`/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 k(`/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 k(`/api/apps/${encodeURIComponent(e)}/ai-pins${r?`?${r}`:""}`);return o}catch{return[]}},async refreshAiPin(e,t){try{return await k(`/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 k(`/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 k(`/api/lineage/scope?${t.toString()}`)}catch{return null}},async runDashboard(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})}catch{return null}},async runAppBuildPreview(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})},async retryDashboardTile(e,t,n,r){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:r??{},tileId:n})})}catch{return null}},async getDashboardStory(e,t,n){try{return await k(`/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 k(`/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 k("/api/persona");return e}catch{return null}},async setPersona(e,t){try{const{persona:n}=await k("/api/persona",{method:"POST",body:JSON.stringify({userId:e,appId:t})});return n}catch{return null}},async clearPersona(){try{await k("/api/persona",{method:"DELETE"})}catch{}},async getSkills(){return k("/api/skills")},async getSkillPathSettings(){return k("/api/skills/settings")},async updateSkillPath(e){return k("/api/skills/settings",{method:"PUT",body:JSON.stringify({path:e})})},async getSkillOptions(e=""){const t=e.trim()?`?q=${encodeURIComponent(e.trim())}`:"";return k(`/api/skills/options${t}`)},async createSkill(e){return k("/api/skills",{method:"POST",body:JSON.stringify({skill:e})})},async updateSkill(e,t){return k(`/api/skills/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({skill:t})})},async getEmbeddingSettings(){return k("/api/settings/embeddings")},async saveEmbeddingSettings(e){return k("/api/settings/embeddings",{method:"PUT",body:JSON.stringify(e)})},async listEmbeddingModels(e){const t=e?`?endpoint=${encodeURIComponent(e)}`:"";return k(`/api/settings/embeddings/models${t}`)},async installEmbeddingModel(e,t){return k("/api/settings/embeddings/install",{method:"POST",body:JSON.stringify({model:e,endpoint:t})})},async testEmbeddingProvider(){return k("/api/settings/embeddings/test",{method:"POST"})},async reindexEmbeddings(){return k("/api/settings/embeddings/reindex",{method:"POST"})},async deleteSkill(e){return k(`/api/skills/${encodeURIComponent(e)}`,{method:"DELETE"})},async getDomains(){try{return await k("/api/domains")}catch{return{domains:[]}}},async createDomain(e){return k("/api/domains",{method:"POST",body:JSON.stringify({domain:e})})},async updateDomain(e,t){return k(`/api/domains/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({domain:t})})},async deleteDomain(e){return k(`/api/domains/${encodeURIComponent(e)}`,{method:"DELETE"})},async startContextBootstrap(e={}){return k("/api/context-bootstrap",{method:"POST",body:JSON.stringify(e)})},async getContextBootstrap(e){return k(`/api/context-bootstrap/${encodeURIComponent(e)}`)},async getLatestContextBootstrap(){return(await k("/api/context-bootstrap/latest")).session??null},async saveContextBootstrapSelected(e,t){return k(`/api/context-bootstrap/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify({candidateIds:t})})}},Tw={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"},Aw={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"},Ap={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"},Mj={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"},Lj={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"},Rw={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Xc={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Zc=["source","transform","answer","consumption"],Nj=["term","business_view","block","metric","dimension","domain","source_table","dbt_source","dbt_model","chart","notebook","dashboard","app"],Bj=["source_table","dbt_source","dbt_model"],Ow=["term","domain","business_view","metric","dimension","block"];[...Ow];function _w(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 Pw(){const{state:e,dispatch:t}=et(),n=e.inspectorContext;return s.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${pe("borderSubtle")}`,background:pe("surfaceBase"),color:pe("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${be[3]}px ${be[4]}px`,borderBottom:`1px solid ${pe("borderSubtle")}`},children:[s.jsx("div",{style:{fontSize:Ze.sm,fontWeight:Xi.semibold},children:n?Iw(n):"Inspector"}),s.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:pe("textMuted"),cursor:"pointer",fontSize:Ze.md,padding:2,borderRadius:wn.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:be[4]},children:n?s.jsx(Dw,{context:n}):s.jsx(Nw,{})})]})}function Iw(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function Dw({context:e}){return e.kind==="cell"?s.jsx($w,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx(Mw,{nodeId:e.nodeId}):s.jsx(Lw,{name:e.name})}function $w({cellId:e}){const{state:t}=et(),n=t.cells.find(r=>r.id===e);return n?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3],fontSize:Ze.sm},children:[s.jsx(Ie,{label:"Type",children:n.type}),s.jsx(Ie,{label:"ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),s.jsxs(Ie,{label:"Length",children:[n.content.length," chars"]}),n.status&&s.jsx(Ie,{label:"Status",children:n.status})]}):s.jsx(fs,{children:"No matching cell in the active notebook."})}function Mw({nodeId:e}){const[t,n]=p.useState(null),[r,o]=p.useState(!0);if(p.useEffect(()=>{let c=!1;return o(!0),B.fetchLineageNode(e).then(l=>{c||(n(l),o(!1))}).catch(()=>{c||o(!1)}),()=>{c=!0}},[e]),r)return s.jsx(fs,{children:"Loading node…"});if(!t||!t.node)return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Node ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),s.jsx(fs,{children:"No metadata available for this node."})]});const i=t.node,a=i.metadata??{};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Name",children:i.name??e}),s.jsx(Ie,{label:"Type",children:Ap[i.type]??i.type}),i.domain&&s.jsx(Ie,{label:"Domain",children:i.domain}),i.owner&&s.jsx(Ie,{label:"Owner",children:i.owner}),i.status&&s.jsx(Ie,{label:"Status",children:i.status}),typeof a.termType=="string"&&s.jsx(Ie,{label:"Term Type",children:a.termType}),typeof a.description=="string"&&s.jsx(Ie,{label:"Description",children:a.description}),Array.isArray(a.identifiers)&&a.identifiers.length>0&&s.jsx(Ie,{label:"Identifiers",children:a.identifiers.map(String).join(", ")}),Array.isArray(a.synonyms)&&a.synonyms.length>0&&s.jsx(Ie,{label:"Synonyms",children:a.synonyms.map(String).join(", ")}),typeof a.businessOutcome=="string"&&s.jsx(Ie,{label:"Business Outcome",children:a.businessOutcome}),i.layer&&s.jsx(Ie,{label:"Layer",children:i.layer}),s.jsx(Ie,{label:"Upstream",children:t.incoming.length}),s.jsx(Ie,{label:"Downstream",children:t.outgoing.length}),(i.path||a.filePath)&&s.jsx(Ie,{label:"Path",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ze.xs},children:i.path??a.filePath})})]})}function Lw({name:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Metric",children:e}),s.jsx(fs,{children:"Definition, dimensions, and governance surface will render here."})]})}function Ie({label:e,children:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[s.jsx("div",{style:{fontSize:Ze.xs,color:pe("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Xi.medium},children:e}),s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textPrimary")},children:t})]})}function fs({children:e}){return s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textSecondary"),lineHeight:1.5,background:pe("surfaceSunken"),border:`1px solid ${pe("borderSubtle")}`,borderRadius:wn.md,padding:be[3]},children:e})}function Nw(){return s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const Jr={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"},el={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 tl(e){if(typeof document>"u")return el[e];const t=Jr[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||el[e]}function Bw(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Jr)return tl(t)},has(e,t){return typeof t=="string"&&t in Jr},ownKeys(){return Object.keys(Jr)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Jr)))return{enumerable:!0,configurable:!0,value:tl(t)}}})}const On=Bw(),Qe={obsidian:On,paper:On,white:On,dark:On,light:On,midnight:On,arctic:On};function Ct(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 Fw=Ct(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"})]}));Ct(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 zw=Ct(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"})]})),Fj=Ct(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"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),s.jsx("path",{d:"M16 20l4 4"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 3v18h18"}),s.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]}));Ct(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"})]}));Ct(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 zj=Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),s.jsx("circle",{cx:"18",cy:"17",r:"2"})]}));Ct(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));Ct(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"})]}));Ct(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 Rp=44,Op=188,_p="dql-activitybar-expanded";function qw(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(_p))==="1"}catch{return!1}}function Uw(e){var t;try{(t=window.localStorage)==null||t.setItem(_p,e?"1":"0")}catch{}}function nl({title:e,icon:t,active:n,expanded:r,onClick:o,t:i}){const[a,c]=p.useState(!1),l=s.jsxs("button",{"aria-label":e,onClick:o,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{width:r?Op-12:Rp-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":a?i.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?i.accent:a?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?l:s.jsx(Qd,{content:e,side:"right",children:l})}function Ww(){const e=Ge(Lr(l=>({mainView:l.mainView,sidebarOpen:l.sidebarOpen,sidebarPanel:l.sidebarPanel,themeMode:l.themeMode}))),t=jn(),n=Qe[e.themeMode],[r,o]=p.useState(qw);p.useEffect(()=>{Uw(r)},[r]);function i(l){if(l==="home"||l==="ask"||l==="modeling"){t({type:"SET_MAIN_VIEW",view:l});return}if(l==="lineage"){t({type:"SET_SIDEBAR_PANEL",panel:"lineage"});return}if(l==="connection"||l==="git"||l==="apps"||l==="readiness"||l==="skills"||l==="domains"||l==="settings"){t({type:"SET_SIDEBAR_PANEL",panel:l});return}e.sidebarPanel===l&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:l})}const a=[{label:"Insights",items:[{key:"apps",title:"Apps",icon:s.jsx(wS,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"ask",title:"Ask",icon:s.jsx(hS,{size:16,strokeWidth:1.75}),active:e.mainView==="ask"}]},{label:"Build",items:[{key:"files",title:"Notebooks",icon:s.jsx(Pa,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"block_library",title:"Blocks",icon:s.jsx(Fw,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(zw,{size:16}),active:e.mainView==="lineage"||e.mainView==="lineage_detail"}]},{label:"Govern",items:[{key:"domains",title:"Modeling",icon:s.jsx(Fi,{size:16,strokeWidth:1.75}),active:e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills"},{key:"git",title:"Source control",icon:s.jsx(Nr,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"settings",title:"Settings",icon:s.jsx(MS,{size:16,strokeWidth:1.75}),active:e.mainView==="settings"||e.mainView==="connection"}]}],c=[{key:"help",title:"Help",icon:s.jsx(Rv,{size:16,strokeWidth:1.75}),active:e.mainView==="help",onClick:()=>t({type:"SET_MAIN_VIEW",view:"help"})}];return s.jsxs("div",{style:{width:r?Op:Rp,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(Qd,{content:r?"Collapse":"Expand",side:"right",children:s.jsx("button",{"aria-label":r?"Collapse sidebar rail":"Expand sidebar rail",onClick:()=>o(l=>!l),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:l=>{l.currentTarget.style.color=n.textPrimary,l.currentTarget.style.background=n.textPrimary+"0f"},onMouseLeave:l=>{l.currentTarget.style.color=n.textMuted,l.currentTarget.style.background="transparent"},children:r?s.jsx(wv,{size:14,strokeWidth:2}):s.jsx(Cv,{size:14,strokeWidth:2})})})}),a.map((l,u)=>s.jsxs(qe.Fragment,{children:[u>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:l.label}):null,l.items.map(h=>s.jsx(nl,{title:h.title,icon:h.icon,active:h.active,expanded:r,onClick:()=>i(h.key),t:n},h.key))]},l.label)),s.jsx("div",{style:{flex:1}}),c.map(l=>s.jsx(nl,{title:l.title,icon:l.icon,active:l.active,expanded:r,onClick:l.onClick,t:n},l.key))]})}const Kw=2e4,qj="application/dql-semantic-ref",rl=new Map;let po=null;function Vw(e){B.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function ol(e,t){const n=`${e}:${t.toLowerCase()}`,r=rl.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 a=await i.json(),c=Array.isArray(a.completions)?a.completions:[];return rl.set(n,{items:c,expiresAt:Date.now()+Kw}),c}function Pp(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 Uj(e){po=e}function Wj(e){po===e&&(po=null)}function Hw(e){return po?(Pp(po,e),!0):!1}function Kj(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;Pp(e,t,r)}function sl(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
394
+ */const YS=[["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"}]],Sp=ne("trash-2",YS);function XS(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 ZS(e,t){const n=e.mode??"both";return n==="both"||n===t}function ew({open:e,onClose:t}){const{state:n,dispatch:r}=et(),[o,i]=p.useState(""),[a,c]=p.useState(0),l=p.useRef(null);p.useEffect(()=>{e&&(i(""),c(0))},[e]);const u=p.useMemo(()=>{const m=x=>r(x),S=()=>t(),v=x=>()=>{x(),S()},b=[["Files","files",Xv],["Lineage","lineage",lS],["Git","git",Nr],["Block Library","block_library",Oa],["Apps","apps",xS],["Connections","connection",RS]],w=[{mode:"obsidian",label:"Obsidian"},{mode:"paper",label:"Paper"},{mode:"white",label:"White"}],j=[];j.push({id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",icon:TS,shortcut:"⌘B",mode:"studio",run:v(()=>m({type:"TOGGLE_SIDEBAR"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",icon:n.inspectorOpen?Nv:Fv,shortcut:"⌘⇧I",mode:"studio",run:v(()=>m({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",icon:pS,shortcut:"⌘D",run:v(()=>m({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:JS,shortcut:"⌘J",mode:"studio",run:v(()=>m({type:"TOGGLE_DEV_PANEL"}))});for(const[x,E,P]of b)j.push({id:`panel.${E}`,label:`Go to ${x}`,group:"Navigate",icon:P,mode:"studio",run:v(()=>{m({type:"SET_SIDEBAR_PANEL",panel:E}),E!=="lineage"&&!n.sidebarOpen&&m({type:"TOGGLE_SIDEBAR"})})});j.push({id:"notebook.new",label:"New notebook…",group:"Create",icon:yp,mode:"studio",run:v(()=>m({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:VS,mode:"studio",run:v(()=>m({type:"OPEN_NEW_BLOCK_MODAL"}))});const C=n.themeMode==="dark"||n.themeMode==="midnight"?"obsidian":n.themeMode==="light"?"paper":n.themeMode==="arctic"?"white":n.themeMode;for(const x of w)x.mode!==C&&j.push({id:`theme.${x.mode}`,label:`Switch to ${x.label}`,group:"Theme",icon:jS,keywords:"appearance color",run:v(()=>m({type:"SET_THEME",mode:x.mode}))});return j},[n.sidebarOpen,n.inspectorOpen,n.themeMode,n.dashboardMode,n.appMode,n.sidebarPanel,r,t]),h=p.useMemo(()=>{const S=u.filter(v=>ZS(v,n.appMode)).map(v=>({a:v,s:XS(v,o)})).filter(v=>v.s>0);return S.sort((v,b)=>b.s-v.s),S.map(v=>v.a)},[u,o,n.appMode]);p.useEffect(()=>{c(0)},[o]),p.useEffect(()=>{var S;const m=(S=l.current)==null?void 0:S.querySelector(`[data-palette-idx="${a}"]`);m==null||m.scrollIntoView({block:"nearest"})},[a]);const d=m=>{var S;m.key==="ArrowDown"?(m.preventDefault(),c(v=>Math.min(h.length-1,v+1))):m.key==="ArrowUp"?(m.preventDefault(),c(v=>Math.max(0,v-1))):m.key==="Enter"&&(m.preventDefault(),(S=h[a])==null||S.run())};let f="";return s.jsx(By,{open:e,onOpenChange:m=>!m&&t(),children:s.jsxs(Fy,{children:[s.jsx(zy,{style:{position:"fixed",inset:0,background:pe("surfaceOverlay"),zIndex:io.overlay}}),s.jsxs(qy,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:pe("surfaceRaised"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.lg,boxShadow:pe("shadowLg"),zIndex:io.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:d,children:[s.jsx(Uy,{style:{position:"absolute",left:-9999},children:"Command palette"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:be[2],padding:`${be[3]}px ${be[4]}px`,borderBottom:`1px solid ${pe("borderSubtle")}`},children:[s.jsx(Dv,{size:14,strokeWidth:1.75,color:pe("textMuted")}),s.jsx("input",{autoFocus:!0,value:o,onChange:m=>i(m.target.value),placeholder:"Type a command…",style:{flex:1,border:"none",outline:"none",background:"transparent",color:pe("textPrimary"),fontSize:Ze.md}})]}),s.jsxs("div",{ref:l,style:{maxHeight:360,overflowY:"auto",padding:`${be[1]}px 0`},children:[h.length===0&&s.jsx("div",{style:{padding:be[4],fontSize:Ze.sm,color:pe("textMuted"),textAlign:"center"},children:"No matching commands"}),h.map((m,S)=>{const v=m.group!==f;f=m.group;const b=S===a,w=m.icon;return s.jsxs(qe.Fragment,{children:[v&&s.jsx("div",{style:{padding:`${be[2]}px ${be[4]}px ${be[1]}px`},children:s.jsx(pp,{tone:"neutral",children:m.group})}),s.jsxs("div",{"data-palette-idx":S,role:"option","aria-selected":b,onMouseEnter:()=>c(S),onMouseDown:j=>{j.preventDefault(),m.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:be[3],padding:`${be[2]}px ${be[4]}px`,fontSize:Ze.sm,cursor:"pointer",background:b?pe("surfaceHover"):"transparent",color:pe("textPrimary")},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:be[2],minWidth:0,flex:1},children:[w&&s.jsx(w,{size:14,strokeWidth:1.75}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.label})]}),m.shortcut&&s.jsx(Dx,{shortcut:m.shortcut})]})]},m.id)})]})]})]})})}function zi(e){const t=Dt(e);if(!t)return;const n=kp(t.kind),r=nw(t.source);if(!n||!r)return;const o=jp(t.limit);return{kind:n,source:r,name:yt(t.name),sourcePath:yt(t.sourcePath),metrics:qi(t.metrics),dimensions:qi(t.dimensions),filters:ow(t.filters),timeDimension:sw(t.timeDimension),orderBy:iw(t.orderBy),parameters:aw(t.parameters),parameterValues:uw(t.parameterValues),persistence:pw(t.persistence),trustState:Cp(t.trustState),compiledSql:yt(t.compiledSql),executionReceipt:wp(t.executionReceipt),executableArtifact:tw(t.executableArtifact),filterableColumns:rw(t.filterableColumns),...o===void 0?{}:{limit:o}}}function tw(e){const t=Dt(e);if(!t||t.version!==1)return;const n=kp(t.kind),r=Cp(t.trustState),o=yt(t.semanticAdapter),i=Dt(t.previewPolicy),a=(i==null?void 0:i.mode)==="read_only_bounded"||(i==null?void 0:i.mode)==="compiler_governed"?i.mode:void 0,c=wp(t.receipt),l={dqlFingerprint:pt(t.dqlFingerprint),sourceFingerprint:pt(t.sourceFingerprint),compiledSqlFingerprint:pt(t.compiledSqlFingerprint),normalizedSqlFingerprint:pt(t.normalizedSqlFingerprint),parameterFingerprint:pt(t.parameterFingerprint),provenanceFingerprint:pt(t.provenanceFingerprint),targetFingerprint:pt(t.targetFingerprint),snapshotFingerprint:pt(t.snapshotFingerprint),planFingerprint:pt(t.planFingerprint)};if(!n||!r||!o||!a||!c||Object.values(l).some(h=>!h))return;const u=jp(i==null?void 0:i.rowLimit);if(!(a==="read_only_bounded"&&u===void 0))return{version:1,kind:n,...l,semanticAdapter:o,previewPolicy:{mode:a,...u===void 0?{}:{rowLimit:u}},trustState:r,receipt:c}}function nw(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function rw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n),o=yt(r==null?void 0:r.column),i=yt(r==null?void 0:r.predicateTarget);return o&&i?[{column:o,predicateTarget:i}]:[]});return t.length>0?t:void 0}function wp(e){const t=Dt(e);if(!t)return;const n=pt(t.sourceFingerprint),r=pt(t.compiledSqlFingerprint),o=pt(t.parameterFingerprint),i=pt(t.resultFingerprint);return n&&r&&o&&i?{sourceFingerprint:n,compiledSqlFingerprint:r,parameterFingerprint:o,resultFingerprint:i}:void 0}function pt(e){return typeof e=="string"&&/^[a-f0-9]{64}$/i.test(e.trim())?e.trim().toLowerCase():void 0}function kp(e){return e==="certified_block"||e==="semantic_block"||e==="sql_block"?e:void 0}function ow(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n);if(!r)return[];const o=yt(r.dimension),i=yt(r.operator);return!o||!i?[]:[{dimension:o,operator:i,values:qi(r.values)??[]}]});return t.length?t:void 0}function sw(e){const t=Dt(e);if(!t)return;const n=yt(t.name),r=yt(t.granularity);return n&&r?{name:n,granularity:r}:void 0}function iw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n);if(!r)return[];const o=yt(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 aw(e){if(!Array.isArray(e))return;const t=new Set,n=e.flatMap(r=>{const o=Dt(r),i=yt(o==null?void 0:o.name),a=cw(o==null?void 0:o.type),c=lw(o==null?void 0:o.policy);if(!o||!i||!a||!c||t.has(i))return[];t.add(i);const l=dw(o.binding);return[{name:i,type:a,required:o.required===!0,...o.default===void 0?{}:{default:o.default},policy:c,...l?{binding:l}:{}}]});return n.length?n:void 0}function cw(e){return e==="string"||e==="number"||e==="boolean"||e==="date"||e==="string[]"||e==="number[]"||e==="date[]"?e:void 0}function lw(e){return e==="dynamic"||e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:void 0}function dw(e){const t=Dt(e);if(!t)return;if(t.kind==="sql_value")return{kind:"sql_value"};if(t.kind==="limit")return{kind:"limit"};const n=yt(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 uw(e){const t=Dt(e);if(!t)return;const n=Object.entries(t).filter(([r])=>r.trim().length>0);return n.length?Object.fromEntries(n):void 0}function pw(e){return e==="transient"||e==="saved"?e:void 0}function Cp(e){return e==="certified"||e==="governed"||e==="review_required"?e:void 0}function Dt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function yt(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function qi(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 jp(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}const Ep="dql_token",Gc="dql.server-token.v1";function fw(e){var r;return((r=new URLSearchParams(e.replace(/^#/,"")).get(Ep))==null?void 0:r.trim())||void 0}function hw(e){const t=new URLSearchParams(e.replace(/^#/,""));t.delete(Ep);const n=t.toString();return n?`#${n}`:""}function mw(){var e;if(!(typeof window>"u"))try{const t=fw(window.location.hash);if(t){window.sessionStorage.setItem(Gc,t);const n=hw(window.location.hash);return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${n}`),t}return((e=window.sessionStorage.getItem(Gc))==null?void 0:e.trim())||void 0}catch{return}}const Qc=mw();function lr(e){const t=new Headers(e);return Qc&&t.set("Authorization",`Bearer ${Qc}`),t}async function Tp(e,t,n){const r=await fetch(e,{headers:lr({Accept:"text/event-stream"}),credentials:"same-origin",cache:"no-store",signal:n});if(!r.ok)throw new Error(`Event stream failed with HTTP ${r.status}.`);if(!r.body)throw new Error("Event stream response did not include a body.");const o=r.body.getReader(),i=new TextDecoder;let a="",c="message",l=[];const u=()=>{l.length>0&&t({event:c,data:l.join(`
395
+ `)}),c="message",l=[]};for(;!n.aborted;){const h=await o.read();a+=i.decode(h.value,{stream:!h.done});const d=a.split(/\r?\n/);a=d.pop()??"";for(const f of d)if(f==="")u();else if(!f.startsWith(":")){const m=f.indexOf(":"),S=m<0?f:f.slice(0,m),v=m<0?"":f.slice(m+1).replace(/^ /,"");S==="event"&&(c=v||"message"),S==="data"&&l.push(v)}if(h.done){u();return}}}const gw={totals:{modelsScanned:0,businessModels:0,plumbingExcluded:0,metricsFound:0},willGenerate:0,willSkip:0,domains:[],config:{businessLayers:[],excludeLayers:[],maxPerDomain:0,minScore:0,aiEnrichment:"auto"}};function Ko(){return{total:0,tracked:0,changed:0,untracked:0,ignored:0,paths:[]}}const Qr=window.location.origin;class St extends Error{constructor(n){super(n.message);Pe(this,"status");Pe(this,"code");Pe(this,"recoverable");Pe(this,"details");Pe(this,"nextActions");Pe(this,"requestId");Pe(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 Ui(e,t){const n=t.trim()||e.statusText||`HTTP ${e.status}`;if(!t.trim())return new St({message:n,status:e.status});try{const r=JSON.parse(t),o=Array.isArray(r==null?void 0:r.errors)?r.errors.filter(a=>typeof a=="string"&&a.trim().length>0):[],i=typeof(r==null?void 0:r.friendlyMessage)=="string"&&r.friendlyMessage.trim()?r.friendlyMessage: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:o.length>0?`${o.slice(0,3).join(" ")}${o.length>3?` ${o.length-3} more blockers.`:""}`:n;return new St({message:i,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)??(typeof(r==null?void 0:r.error)=="string"&&r.error.trim()&&r.error!==i?{technicalDetails:r.error}:o.length>0?{errors:o,draft:r==null?void 0:r.draft}:void 0),nextActions:Array.isArray(r==null?void 0:r.nextActions)?r.nextActions.filter(a=>typeof a=="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 St({message:n,status:e.status})}}const Js=new Map;async function k(e,t){if(((t==null?void 0:t.method)??"GET").toUpperCase()==="GET"&&!(t!=null&&t.signal)&&!(t!=null&&t.body)){const o=Js.get(e);if(o)return o;const i=Jc(e,t).finally(()=>{Js.delete(e)});return Js.set(e,i),i}return Jc(e,t)}async function Jc(e,t){var r;let n;try{const o=lr(t==null?void 0:t.headers);o.has("Content-Type")||o.set("Content-Type","application/json"),n=await fetch(`${Qr}${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 Ui(n,o)}if(n.status!==204)return n.json()}async function yw(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 a=c=>{const l=c.split(/\r?\n/);let u="message";const h=[];for(const f of l)f.startsWith("event:")&&(u=f.slice(6).trim()),f.startsWith("data:")&&h.push(f.slice(5).trimStart());if(h.length===0)return;const d=JSON.parse(h.join(`
396
+ `));if(u==="agent-run-accepted"){const f=typeof(d==null?void 0:d.runId)=="string"?d.runId:void 0,m=typeof(d==null?void 0:d.operationId)=="string"?d.operationId:void 0;f&&t({kind:"accepted",runId:f,...m?{operationId:m}:{}})}else if(u==="agent-run-event")t({kind:"event",event:d});else if(u==="agent-run-answer-delta"){const f=typeof(d==null?void 0:d.delta)=="string"?d.delta:"";f&&t({kind:"answer-delta",delta:f})}else if(u==="agent-run-complete")i=d,t({kind:"complete",run:i});else if(u==="agent-run-error")throw new Error(typeof(d==null?void 0:d.error)=="string"?d.error:"Agent run failed.")};for(;;){const{value:c,done:l}=await n.read();if(c){o+=r.decode(c,{stream:!l});let u=o.search(/\r?\n\r?\n/);for(;u>=0;){const h=o.slice(0,u);o=o.slice(o[u]==="\r"?u+4:u+2),a(h),u=o.search(/\r?\n\r?\n/)}}if(l)break}if(o.trim()&&a(o),!i)throw new Error("Agent run stream ended before completion.");return i}function Yc(e){const{runId:t,...n}=e;return JSON.stringify(n)}function an(e){const t=Array.isArray(e==null?void 0:e.columns)?e.columns.map(a=>typeof a=="string"?a:typeof(a==null?void 0:a.name)=="string"?a.name:String(a)):[],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,r=Array.isArray(e==null?void 0:e.rows)?e.rows:[],o=t.length>0?t:r.find(a=>a&&typeof a=="object"&&!Array.isArray(a))?Object.keys(r.find(a=>a&&typeof a=="object"&&!Array.isArray(a))):r.find(a=>Array.isArray(a))?r.find(a=>Array.isArray(a)).map((a,c)=>`column_${c+1}`):[],i=r.map(a=>{if(Array.isArray(a))return Object.fromEntries(o.map((c,l)=>[c,a[l]]));if(a&&typeof a=="object"){const c=a;return Object.fromEntries(o.map(l=>[l,c[l]]))}return Object.fromEntries(o.map(c=>[c,void 0]))});return{columns:o,rows:i,...typeof(e==null?void 0:e.resultFingerprint)=="string"?{resultFingerprint:e.resultFingerprint}:{},...e!=null&&e.executionReceipt&&typeof e.executionReceipt=="object"?{executionReceipt:e.executionReceipt}:{},...typeof(e==null?void 0:e.trustState)=="string"?{trustState:e.trustState}:{},...typeof(e==null?void 0:e.answerTier)=="string"?{answerTier:e.answerTier}:{},rowCount:typeof(e==null?void 0:e.rowCount)=="number"?e.rowCount:i.length,executionTime:(e==null?void 0:e.executionTime)??(e==null?void 0:e.executionTimeMs)??0,...n?{semanticRefs:n}:{}}}function Vt(e){var n;const t=e!=null&&e.resultPreview&&typeof e.resultPreview=="object"?an(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:zi(e==null?void 0:e.dqlArtifact),dqlPromotionAction:Tw((e==null?void 0:e.dqlPromotionAction)??((n=e==null?void 0:e.dqlPromotion)==null?void 0:n.recommendedAction)),dqlPromotion:Ap(e==null?void 0:e.dqlPromotion),researchPlan:bw(e==null?void 0:e.researchPlan),reviewChecklist:jw(e==null?void 0:e.reviewChecklist,e),...t?{resultPreview:t}:{resultPreview:void 0}}}function bw(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",a=r.status==="ready"||r.status==="error"?r.status:"not_run",c=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",l=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:xw(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:Ce(n.evidenceCount),relationCount:Ce(n.relationCount),missingContextCount:Ce(n.missingContextCount)},preview:{status:a,...l===void 0?{}:{rowCount:l}},promotion:{path:c,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 xw(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 Ce(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function rr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function vw(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{totalReviewCount:Ce(t.totalReviewCount),openReviewCount:Ce(t.openReviewCount),terminalReviewCount:Ce(t.terminalReviewCount),draftCreatedCount:Ce(t.draftCreatedCount),certifiedCount:Ce(t.certifiedCount),completedCount:Ce(t.completedCount),rejectedCount:Ce(t.rejectedCount),draftCreationRate:rr(t.draftCreationRate),certifyConversionRate:rr(t.certifyConversionRate),medianOpenReviewAgeMs:rr(t.medianOpenReviewAgeMs),medianTimeToDraftMs:rr(t.medianTimeToDraftMs),medianTimeToCertificationMs:rr(t.medianTimeToCertificationMs),medianTimeToTerminalMs:rr(t.medianTimeToTerminalMs)}}function Sw(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:{},a=t.limits&&typeof t.limits=="object"?t.limits:{};return{counts:{totalRuns:Ce(n.totalRuns),activeRuns:Ce(n.activeRuns),closedRuns:Ce(n.closedRuns),notebooks:Ce(n.notebooks),domains:Ce(n.domains),owners:Ce(n.owners),sourceLinkedRuns:Ce(n.sourceLinkedRuns)},health:{staleOpenRuns:Ce(r.staleOpenRuns),expiredOpenRuns:Ce(r.expiredOpenRuns),staleThresholdDays:Ce(r.staleThresholdDays)||7,expiredThresholdDays:Ce(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:Ce(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:Ce(a.pageSize)||25,maxPageSize:Ce(a.maxPageSize)||500,sourceCoverageLimit:Ce(a.sourceCoverageLimit)||1e4,seedCellLimit:Ce(a.seedCellLimit)||1e3},warnings:Array.isArray(t.warnings)?t.warnings.filter(c=>typeof c=="string"):[]}}function ww(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 kw(e){const t=typeof e=="string"?e:"";return(t.split(/[\\/]/).pop()??t).replace(/\.dqlnb$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()||"Untitled notebook"}function Cw(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 Vo(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 jw(e,t){var u,h;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(d=>typeof d=="string"):[],warnings:Array.isArray(e.warnings)?e.warnings.filter(d=>typeof d=="string"):[],items:e.items.map(d=>({id:typeof d.id=="string"?d.id:"item",label:typeof d.label=="string"?d.label:"Review item",status:d.status==="passed"||d.status==="pending"||d.status==="warning"||d.status==="blocked"?d.status:"pending",detail:typeof d.detail=="string"?d.detail:""}))};const n=!!t.reviewedSql,r=n||!!t.generatedSql,o=((u=t.resultPreview)==null?void 0:u.rowCount)??((h=t.resultPreview)==null?void 0:h.rows.length)??0,i=!!(t.resultPreview&&(t.resultPreview.columns.length>0||o>0)),a=!!t.draftBlockPath,c=!!(t.contextPackId||t.evidence),l=t.dqlPromotionAction==="reuse_existing";return{readyForDqlDraft:!!(!l&&t.question&&n&&c&&t.status!=="error"),readyForCertificationReview:!!(!l&&t.question&&n&&c&&i&&a),blockers:t.status==="error"?[t.error??"Preview failed."]:[],warnings:i||l?[]:["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||l?"passed":"blocked",detail:l&&!r?"Existing DQL should be reused; no new SQL is required.":r?"SQL is available.":"Add SQL before promotion."},{id:"evidence",label:"Evidence",status:c||l?"passed":"warning",detail:c?"Context evidence is saved.":l?"Reuse evidence is captured in the recommendation.":"Preview and save metadata context."},{id:"preview",label:"Preview",status:i||l?"passed":"pending",detail:i?"Preview result is available.":l?"Certified block reuse does not require a new raw SQL preview.":"Run a bounded preview."},{id:"dql_draft",label:"DQL draft",status:a||l?"passed":"pending",detail:a?`Draft saved at ${t.draftBlockPath}.`:l?"No new DQL draft is required.":"Create a DQL draft after review."}]}}function Ew(e){var r,o,i,a;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(c=>({objectKey:typeof c.objectKey=="string"?c.objectKey:void 0,objectType:typeof c.objectType=="string"?c.objectType:void 0,name:typeof c.name=="string"?c.name:"Evidence",role:typeof c.role=="string"?c.role:void 0,reason:typeof c.reason=="string"?c.reason:""})):[],summaries:Array.isArray(t.summaries)?t.summaries.map(c=>({title:typeof c.title=="string"?c.title:"Context",detail:typeof c.detail=="string"?c.detail:"",objectType:typeof c.objectType=="string"?c.objectType:void 0,reason:typeof c.reason=="string"?c.reason:void 0})):[],relations:Array.isArray(t.relations)?t.relations.map(c=>({relation:typeof c.relation=="string"?c.relation:"",name:typeof c.name=="string"?c.name:"Relation",source:typeof c.source=="string"?c.source:"",columns:Array.isArray(c.columns)?c.columns.map(String):[]})).filter(c=>c.relation||c.name):[],missingContext:Array.isArray(t.missingContext)?t.missingContext.map(c=>({kind:typeof c.kind=="string"?c.kind:"metadata",message:typeof c.message=="string"?c.message:"",severity:typeof c.severity=="string"?c.severity:"warning"})).filter(c=>c.message):[],warnings:Array.isArray(t.warnings)?t.warnings.filter(c=>typeof c=="string"):[],topRejected:Array.isArray(t.topRejected)?t.topRejected.map(c=>({name:typeof c.name=="string"?c.name:"Rejected context",objectType:typeof c.objectType=="string"?c.objectType:void 0,reason:typeof c.reason=="string"?c.reason:"",score:typeof c.score=="number"&&Number.isFinite(c.score)?c.score:void 0})).filter(c=>c.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((a=t.counts)==null?void 0:a.warnings)=="number"?t.counts.warnings:0}}}function Tw(e){return e==="reuse_existing"||e==="extend_existing"||e==="create_replacement"||e==="create_new"||e==="review_required"?e:void 0}function Ap(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:""}}function Xc(e){return{id:e.sourceId,sourceId:e.sourceId,qualifiedIdentity:e.qualifiedIdentity,sourceRevision:e.sourceRevision,snapshotId:e.snapshotId,lifecycle:e.lifecycle,trust:e.trust,name:e.name,domain:e.domain??"Unassigned",status:e.lifecycle,owner:e.owner??null,tags:e.tags,path:e.executionRef,fingerprint:e.sourceRevision,lastModified:"",description:e.description??"",chartType:e.capabilities.chartType,filterIds:e.capabilities.filters,dimensionIds:e.capabilities.dimensions,capabilities:e.capabilities,eligibility:e.eligibility,score:e.score??0,reasons:e.reasons}}const B={async listOperations(e=50){return k(`/api/operations?limit=${Math.max(1,Math.min(100,Math.floor(e)))}`)},async getOperation(e){return k(`/api/operations/${encodeURIComponent(e)}`)},async cancelOperation(e){return k(`/api/operations/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestBlockStudioCertification(e){return k("/api/block-studio/certifications",{method:"POST",headers:{"Idempotency-Key":e.idempotencyKey},body:JSON.stringify({source:e.source,path:e.path,metadata:e.metadata,expectedSourceFingerprint:e.expectedSourceFingerprint,clientRevision:e.clientRevision})})},async getDbtFirstModeling(){return k("/api/modeling/dbt-first")},async getDbtModelingNode(e){return k(`/api/modeling/dbt-first/nodes/${encodeURIComponent(e)}`)},async getDbtModelingNodes(e){return k("/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)),e.physicalOnly&&t.set("physicalOnly","true"),k(`/api/modeling/dbt-first/inventory?${t.toString()}`)},async getDomainWorkspaces(){return k("/api/domain-workspaces")},async getRelatedDomainProducts(e){return k(`/api/domain-workspaces/${encodeURIComponent(e)}/related-products`)},async getAllRelatedDomainProducts(){return k("/api/domain-workspaces/related-products")},async getDomainKnowledge(e){return k(`/api/domain-workspaces/${encodeURIComponent(e)}/knowledge`)},async createContextProposal(e){return(await k("/api/context-proposals",{method:"POST",body:JSON.stringify(e)})).proposal},async getContextProposal(e){return(await k(`/api/context-proposals/${encodeURIComponent(e)}`)).proposal},async repreviewContextProposal(e,t,n){return(await k(`/api/context-proposals/${encodeURIComponent(e)}/repreview`,{method:"POST",body:JSON.stringify({selectedOperationIds:t,rebase:(n==null?void 0:n.rebase)===!0})})).proposal},async commitContextProposal(e,t,n){return k(`/api/context-proposals/${encodeURIComponent(e)}/commit`,{method:"POST",body:JSON.stringify({expectedProposalHash:t,idempotencyKey:n})})},async createModelingImport(e){return(await k("/api/modeling/dbt-first/imports",{method:"POST",body:JSON.stringify({source:e})})).session},async previewModelingImport(e,t){return k(`/api/modeling/dbt-first/imports/${encodeURIComponent(e)}/preview`,{method:"POST",body:JSON.stringify(t)})},async previewModelingChange(e,t){return k("/api/modeling/dbt-first/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyModelingChange(e,t,n){return k("/api/modeling/dbt-first/apply",{method:"POST",body:JSON.stringify({change:e,fingerprint:t,expectedSnapshotId:n})})},async validateModelingRelationship(e,t){return(await k("/api/modeling/dbt-first/relationships/validate",{method:"POST",body:JSON.stringify({relationship:e,expectedSnapshotId:t})})).evidence},async previewDbtSourcePatch(e,t){return k("/api/modeling/dbt-first/dbt-source/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyDbtSourcePatch(e,t,n){return k("/api/modeling/dbt-first/dbt-source/apply",{method:"POST",body:JSON.stringify({change:e,expectedFingerprint:t,expectedSnapshotId:n})})},async getSettingsEnvStatus(){try{return await k("/api/settings/env-status")}catch{return{groups:[]}}},async getProposeReadiness(e){try{return await k("/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:gw,proposals:[]}}},async generateProposeDrafts(e){try{return await k("/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 k(`/api/propose/preview?slug=${encodeURIComponent(e)}`)},async aiBuild(e){return k("/api/ai/build",{method:"POST",body:JSON.stringify(e)})},async createAgentRun(e){return(await k("/api/agent-runs",{method:"POST",body:Yc(e)})).run},async createAgentRunStream(e,t,n){let r;try{r=await fetch(`${Qr}/api/agent-runs?stream=1`,{method:"POST",headers:lr({"Content-Type":"application/json"}),body:Yc(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 Ui(r,o)}return yw(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 k(`/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 k(`/api/agent-runs/${encodeURIComponent(e)}`)},async deriveAnalyticalRepair(e,t){return k(`/api/agent-runs/${encodeURIComponent(e)}/analytical-repair`,{method:"POST",body:JSON.stringify({repair:t})})},async repairAgentRunExecution(e,t){return k(`/api/agent-runs/${encodeURIComponent(e)}/repair-execution`,{method:"POST",body:JSON.stringify({threadId:t})})},async repairNotebookCellExecution(e,t,n){var o,i,a,c,l,u;const r=await k("/api/notebook/repair-execution",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig},error:t,failure:(o=e.execution)==null?void 0:o.error,attemptedSql:((i=e.execution)==null?void 0:i.compiledSql)??e.content,executionTarget:e.executionTarget,parameters:((a=e.blockBinding)==null?void 0:a.state)==="bound"?e.blockBinding.parameterValues:e.dqlParameterValues,executionContext:n})});if(n!=null&&n.runId&&typeof((c=r==null?void 0:r.executionContext)==null?void 0:c.runId)=="string"&&r.executionContext.runId!==n.runId)throw new St({message:"The notebook server returned a repair for a different cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:r.executionContext}});return{ok:!0,source:String(r.source??e.content),repairedSql:String(r.repairedSql??""),repairMode:r.repairMode==="ai"?"ai":"deterministic",result:an(r.result),executionTarget:((l=r==null?void 0:r.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((u=r==null?void 0:r.executionTarget)==null?void 0:u.target)==="connection"?{target:"connection",...typeof r.executionTarget.connectionName=="string"?{connectionName:r.executionTarget.connectionName}:{}}: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,executionReceipt:r!=null&&r.executionReceipt&&typeof r.executionReceipt=="object"?r.executionReceipt:void 0}},async cancelAgentRun(e){return k(`/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 k(`/api/agent/threads${n}`)},async createAgentThread(e={}){return(await k("/api/agent/threads",{method:"POST",body:JSON.stringify(e)})).thread},async getAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}`)},async updateAgentThread(e,t){return k(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async archiveAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}/archive`,{method:"POST"})},async deleteAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestCertification(e){return k("/api/agent-runs/request-certification",{method:"POST",body:JSON.stringify(e)})},async getIdentity(){return k("/api/identity")},async getProviderSettings(){try{return await k("/api/settings/providers")}catch{return{providers:[]}}},async getProviderCliStatus(){try{return await k("/api/settings/providers/cli-status")}catch{return{status:{}}}},async saveProviderSettings(e){return k("/api/settings/providers",{method:"POST",body:JSON.stringify(e)})},async startOAuth(e){return k(`/api/auth/${e}/start`,{method:"POST"})},async getOAuthStatus(e){return k(`/api/auth/${e}/status`)},async signOutOAuth(e){return k(`/api/auth/${e}/signout`,{method:"POST"})},async testProviderSettings(e,t){try{return await k("/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 k("/api/settings/mcp")}catch{return{settings:{path:"",entries:[],warnings:[]}}}},async saveRemoteMcpSettings(e){return k("/api/settings/mcp",{method:"POST",body:JSON.stringify({entries:e})})},async recordAgentCorrection(e){return k("/api/agent/learnings/correction",{method:"POST",body:JSON.stringify(e)})},async listAgentHints(e){const t=e?`?status=${encodeURIComponent(e)}`:"";return k(`/api/agent/hints${t}`)},async reviewAgentHint(e,t,n){return k(`/api/agent/hints/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({decision:t,...n?{note:n}:{}})})},async updateAgentHint(e,t){return k(`/api/agent/hints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async transitionAgentHint(e,t){return k(`/api/agent/hints/${encodeURIComponent(e)}/lifecycle`,{method:"POST",body:JSON.stringify(t)})},async listAgentMemory(e){const t=e?`?scope=${encodeURIComponent(e)}`:"";try{return await k(`/api/agent/memory${t}`)}catch{return{memories:[]}}},async saveAgentMemory(e){return k("/api/agent/memory",{method:"POST",body:JSON.stringify(e)})},async deleteAgentMemory(e){return k(`/api/agent/memory?id=${encodeURIComponent(e)}`,{method:"DELETE"})},async ensureAgentMemoryFiles(){return k("/api/agent/memory/default-files",{method:"POST"})},async listNotebooks(){try{return await k("/api/notebooks")}catch{return[]}},async readNotebook(e){return k(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async deleteNotebook(e){return k(`/api/notebooks?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async createNotebook(e,t,n={}){return k("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t,...n})})},async createBlock(e,t){return k("/api/blocks",{method:"POST",body:JSON.stringify({name:e,...t})})},async getBlockLibrary(){try{return await k("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await k("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return k("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await k(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return k("/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 k(`/api/block-studio/catalog${n?`?${n}`:""}`)},async getBlockStudioDbtStatus(){return k("/api/block-studio/dbt-status")},async openBlockStudio(e){return k(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return k(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t,n){return k("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t}),signal:n})},async runBlockStudio(e,t,n){return k("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t,parameters:n})})},async repairAndRunBlockStudio(e,t,n={},r){const o=await k("/api/block-studio/repair-and-run",{method:"POST",body:JSON.stringify({cell:{id:"block-studio-draft",type:"dql",source:e,title:r||"Block Studio draft"},error:t,attemptedSql:e,parameters:n})}),i=String(o.repairedSql??"");return{source:String(o.source??e),repairedSql:i,repairMode:o.repairMode==="ai"?"ai":"deterministic",preview:{sql:i,result:an(o.result)}}},async getCertifiedBlockParameters(e){return k(`/api/blocks/parameters?name=${encodeURIComponent(e)}`)},async invokeCertifiedBlock(e,t,n){var o,i,a,c,l,u;const r=await k("/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:{...an(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((a=r==null?void 0:r.result)==null?void 0:a.blockPath)=="string"?{blockPath:r.result.blockPath}:{},...(c=r==null?void 0:r.result)!=null&&c.chartConfig?{chartConfig:r.result.chartConfig}:{},...Array.isArray((l=r==null?void 0:r.result)==null?void 0:l.parameters)?{parameters:r.result.parameters}:{},...typeof((u=r==null?void 0:r.result)==null?void 0:u.auditId)=="string"?{auditId:r.result.auditId}:{}}}},async addDqlArtifactResultFilter(e,t,n,r,o){const i=await k("/api/dql/artifacts/add-filter",{method:"POST",body:JSON.stringify({artifact:e,resultColumns:t,column:n,value:r,executionTarget:o})}),a=zi(i==null?void 0:i.artifact);if(!a)throw new Error("Adding the filter input returned an invalid artifact contract.");return{artifact:a,parameterName:String((i==null?void 0:i.parameterName)??n)}},async invokeDqlArtifact(e,t,n,r,o){var c,l,u,h,d,f;const i=await k("/api/dql/artifacts/execute",{method:"POST",body:JSON.stringify({artifact:e,parameters:t,question:n,blockName:r,executionTarget:o})}),a=zi(i==null?void 0:i.artifact);if(!a)throw new Error("DQL artifact execution returned an invalid artifact contract.");return{artifact:a,parameters:a.parameters??[],result:{...an(i==null?void 0:i.result),...typeof((c=i==null?void 0:i.result)==null?void 0:c.sql)=="string"?{sql:i.result.sql}:{},...typeof((l=i==null?void 0:i.result)==null?void 0:l.blockName)=="string"?{blockName:i.result.blockName}:{},...typeof((u=i==null?void 0:i.result)==null?void 0:u.blockPath)=="string"?{blockPath:i.result.blockPath}:{},...(h=i==null?void 0:i.result)!=null&&h.chartConfig?{chartConfig:i.result.chartConfig}:{},...Array.isArray((d=i==null?void 0:i.result)==null?void 0:d.parameters)?{parameters:i.result.parameters}:{},...typeof((f=i==null?void 0:i.result)==null?void 0:f.auditId)=="string"?{auditId:i.result.auditId}:{}}}},async composeSemanticBlock(e){return k("/api/block-studio/compose-semantic",{method:"POST",body:JSON.stringify({question:e})})},async saveBlockStudio(e){return k("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAgentBlockDraft(e){return k("/api/block-studio/agent-drafts",{method:"POST",body:JSON.stringify(e)})},async deleteBlockStudio(e){return k(`/api/block-studio/block?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async previewBlockStudioImport(e){return k("/api/block-studio/import/preview",{method:"POST",body:JSON.stringify(e)})},async listBlockStudioImports(){return k("/api/block-studio/imports")},async createBlockStudioImport(e){return k("/api/block-studio/imports",{method:"POST",body:JSON.stringify(e)})},async createDqlGenerationSession(e){return k("/api/block-studio/ai-imports",{method:"POST",body:JSON.stringify(e)})},async getDqlGenerationSession(e){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}`)},async getBlockStudioImport(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}`)},async deleteBlockStudioImport(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}`,{method:"DELETE"})},async clearBlockStudioImports(){return k("/api/block-studio/imports",{method:"DELETE"})},async updateBlockStudioImportCandidate(e,t,n){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async updateDqlGenerationCandidate(e,t,n){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async matchSqlForBlockReuse(e,t){return k("/api/block-studio/match-sql",{method:"POST",body:JSON.stringify({sql:e,...t??{}})})},async previewDqlGenerationCandidate(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/preview`,{method:"POST"})},async certifyDqlGenerationCandidate(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/certify`,{method:"POST"})},async saveSelectedDqlGenerationCandidates(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify(t)})},async runBlockStudioImportCandidate(e,t){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/run`,{method:"POST"})},async saveBlockStudioImportCandidate(e,t){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/save`,{method:"POST"})},async saveAllBlockStudioImportCandidates(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/save-all`,{method:"POST"})},async assistBlockStudioImportCandidate(e,t,n){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/ai-assist`,{method:"POST",body:JSON.stringify({action:n})})},async getSemanticLayerDiagnostics(){return k("/api/semantic-layer/diagnostics")},async reloadSemanticLayer(){return k("/api/semantic-layer/reload",{method:"POST"})},async assessBlockStudioCertification(e){return k("/api/block-studio/certification-check",{method:"POST",body:JSON.stringify({source:e})})},async certifyBlockStudio(e){const t=await fetch(`${Qr}/api/block-studio/certify`,{headers:lr({"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 k("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await k("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await k("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return k("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t,n,r){var i,a,c;const o=await k("/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 St({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{...an(o),executionTarget:((a=o==null?void 0:o.executionTarget)==null?void 0:a.target)==="local"?{target:"local"}:((c=o==null?void 0:o.executionTarget)==null?void 0:c.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 k("/api/ai/sql-draft/preview",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return{ok:!0,result:an(n.result)}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async executeNotebookCell(e,t,n){var o,i,a,c,l,u;const r=await k("/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 St({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((a=r==null?void 0:r.executionContext)==null?void 0:a.cellId)=="string"?r.executionContext.cellId:void 0,runId:typeof((c=r==null?void 0:r.executionContext)==null?void 0:c.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?an(r.result):null,executionTarget:((l=r==null?void 0:r.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((u=r==null?void 0:r.executionTarget)==null?void 0:u.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 k("/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(`${Qr}/api/datasets/import`,{method:"POST",headers:lr(),body:t});if(!n.ok){const r=await n.text().catch(()=>"");throw Ui(n,r)}return n.json()}return k("/api/datasets/import",{method:"POST",body:JSON.stringify(e)})},async refreshDataset(e){return k(`/api/datasets/${encodeURIComponent(e)}/refresh`,{method:"POST"})},async updateDatasetSchema(e,t){return k(`/api/datasets/${encodeURIComponent(e)}/schema`,{method:"POST",body:JSON.stringify({overrides:t})})},async renameDataset(e,t,n){return k(`/api/datasets/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({name:t,alias:n})})},async pinDataset(e,t=!0){return k(`/api/datasets/${encodeURIComponent(e)}/pin`,{method:"POST",body:JSON.stringify({pinned:t})})},async removeDataset(e){await k(`/api/datasets/${encodeURIComponent(e)}`,{method:"DELETE"})},async stageDataset(e){return k("/api/datasets/stage",{method:"POST",body:JSON.stringify(e)})},async listNotebookResearch(e){var o,i,a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P,A;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 k(`/api/notebook/research${n}`);return{runs:r.runs.map(Vt),total:typeof r.total=="number"?r.total:r.runs.length,domains:Array.isArray(r.domains)?r.domains.map(g=>({domain:typeof g.domain=="string"&&g.domain.trim()?g.domain:"uncategorized",total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],owners:Array.isArray(r.owners)?r.owners.map(g=>({owner:typeof g.owner=="string"&&g.owner.trim()?g.owner:"unassigned",total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],intents:Array.isArray(r.intents)?r.intents.map(g=>({intent:ww(g.intent),total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],notebooks:Array.isArray(r.notebooks)?r.notebooks.map(g=>({path:typeof g.path=="string"&&g.path.trim()?g.path:"notebooks/untitled.dqlnb",title:typeof g.title=="string"&&g.title.trim()?g.title:kw(g.path),total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.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((a=r.counts)==null?void 0:a.needsReview)=="number"?r.counts.needsReview:0,dqlDrafts:typeof((c=r.counts)==null?void 0:c.dqlDrafts)=="number"?r.counts.dqlDrafts:0,errors:typeof((l=r.counts)==null?void 0:l.errors)=="number"?r.counts.errors:0,reuseExisting:typeof((u=r.counts)==null?void 0:u.reuseExisting)=="number"?r.counts.reuseExisting:0,extendExisting:typeof((h=r.counts)==null?void 0:h.extendExisting)=="number"?r.counts.extendExisting:0,replacements:typeof((d=r.counts)==null?void 0:d.replacements)=="number"?r.counts.replacements:0,createNew:typeof((f=r.counts)==null?void 0:f.createNew)=="number"?r.counts.createNew:0,draftReady:typeof((m=r.counts)==null?void 0:m.draftReady)=="number"?r.counts.draftReady:0,certificationReady:typeof((S=r.counts)==null?void 0:S.certificationReady)=="number"?r.counts.certificationReady:0,blocked:typeof((v=r.counts)==null?void 0:v.blocked)=="number"?r.counts.blocked:0,staleOpen:typeof((b=r.counts)==null?void 0:b.staleOpen)=="number"?r.counts.staleOpen:0,expiredOpen:typeof((w=r.counts)==null?void 0:w.expiredOpen)=="number"?r.counts.expiredOpen:0,sourceLinked:typeof((j=r.counts)==null?void 0:j.sourceLinked)=="number"?r.counts.sourceLinked:0,nextActions:Cw((C=r.counts)==null?void 0:C.nextActions)},groupCounts:{domains:typeof((x=r.groupCounts)==null?void 0:x.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((E=r.groupCounts)==null?void 0:E.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((P=r.groupCounts)==null?void 0:P.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((A=r.groupCounts)==null?void 0:A.notebooks)=="number"&&Number.isFinite(r.groupCounts.notebooks)?Math.max(0,Math.floor(r.groupCounts.notebooks)):Array.isArray(r.notebooks)?r.notebooks.length:0},reviewMetrics:vw(r.reviewMetrics),limit:r.limit,offset:typeof r.offset=="number"?r.offset:0}},async getNotebookResearchDiagnostics(){const e=await k("/api/notebook/research/diagnostics");return Sw(e)},async createNotebookResearch(e){const t=await k("/api/notebook/research",{method:"POST",body:JSON.stringify(e)});return Vt(t.run)},async seedNotebookResearchFromCells(e){const t=await k("/api/notebook/research/seed-cells",{method:"POST",body:JSON.stringify(e)});return{created:Array.isArray(t.created)?t.created.map(Vt):[],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 k("/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(Vt):[],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 k("/api/notebook/research/context-preview",{method:"POST",body:JSON.stringify(e)});return Ew(t)},async getNotebookResearch(e){const t=await k(`/api/notebook/research/${encodeURIComponent(e)}`);return Vt(t.run)},async updateNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});return Vt(n.run)},async runNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t??{})});return Vt(n.run)},async checkNotebookResearchReuse(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/reuse-check`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Vt(n.run),promotion:Ap(n.promotion)??n.promotion}},async promoteNotebookResearchToDql(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/promote-dql`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Vt(n.run)}},async getSchema(){try{const e=await fetch(`${Qr}/api/schema`,{headers:lr()});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 k("/api/connections")}catch{return{default:"unknown",connections:{}}}},async previewDbtProfiles(e){return k("/api/connections/dbt-profiles/preview",{method:"POST",body:JSON.stringify({path:e})})},async saveConnections(e,t){return k("/api/connections",{method:"PUT",body:JSON.stringify({connections:e,defaultConnectionName:t})})},async previewConnectionMetadataScope(e,t={}){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope/preview`,{method:"POST",body:JSON.stringify(t)})},async discoverConnectionMetadataScopes(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope/discovery`,{method:"POST"})},async getConnectionMetadataScope(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope`)},async applyConnectionMetadataScope(e,t){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope`,{method:"PUT",body:JSON.stringify(t)})},async refreshConnectionMetadata(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-sync`,{method:"POST"})},async installConnector(e){return k("/api/connectors/install",{method:"POST",body:JSON.stringify({driver:e})})},async testConnection(){try{return await k("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticRuntimeSettings(){return k("/api/semantic-runtime")},async getMetricFlowInstallerStatus(){return k("/api/semantic-runtime/metricflow/installer")},async installMetricFlow(e){return k("/api/semantic-runtime/metricflow/install",{method:"POST",body:JSON.stringify(e?{adapter:e}:{})})},async testDbtCloudSemanticRuntime(e){try{return await k("/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 k("/api/semantic-runtime/dbt-cloud/apply",{method:"POST",body:JSON.stringify(e)})},async setSemanticRuntimePreference(e){return k("/api/semantic-runtime/preference",{method:"POST",body:JSON.stringify({preference:e})})},async getSemanticLayer(){try{return await k("/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 k("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return k(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async getSetupLaunch(){return k("/api/onboarding/launch")},async acknowledgeSetupLaunch(){return k("/api/onboarding/acknowledge",{method:"POST",body:"{}"})},async getOnboardingStatus(){return k("/api/onboarding/status")},async previewDbtOnboarding(e){return k("/api/onboarding/dbt/preview",{method:"POST",body:JSON.stringify(e)})},async applyDbtOnboarding(e){return k("/api/onboarding/dbt/apply",{method:"POST",body:JSON.stringify({...e,fingerprint:e.expectedFingerprint})})},async refreshDbtOnboarding(e={}){return k("/api/onboarding/refresh",{method:"POST",body:JSON.stringify(e)})},async getOnboardingJob(e){return k(`/api/onboarding/jobs/${encodeURIComponent(e)}`)},async cancelOnboardingJob(e){return k(`/api/onboarding/jobs/${encodeURIComponent(e)}`,{method:"DELETE"})},async discoverOnboardingDomains(e={}){return k("/api/onboarding/domains/discover",{method:"POST",body:JSON.stringify(e)})},async applyOnboardingDomains(e){return k("/api/onboarding/domains/apply",{method:"POST",body:JSON.stringify(e)})},async importSemanticLayer(e){return k("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return k("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return k("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return k("/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 k(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[]}}},async getFavorites(){try{return(await k("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await k("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await k("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await k("/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 k(`/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 k(`/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 k("/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 k("/api/semantic-builder/preview",{method:"POST",body:JSON.stringify(e)})}catch(t){return t instanceof St?{error:t.message,code:t.code,details:t.details}:{error:t instanceof Error?t.message:"Failed to preview semantic block"}}},async saveSemanticBuilder(e){return k("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await k("/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=new URLSearchParams({relation:e});try{return await k(`/api/describe-table?${t.toString()}`)}catch{return[]}},async fetchLineage(){try{return await k("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await k(`/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 k(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await k(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBusiness360(e){try{return await k(`/api/lineage/business-360/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await k(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await k(`/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 k(o)}catch{return null}},async fetchGitStatus(){try{return await k("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await k(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await k(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await k("/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 k(`/api/git/diff${r?`?${r}`:""}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}},async fetchGitBranches(){try{return await k("/api/git/branches")}catch{return{inRepo:!1,current:null,branches:[]}}},async fetchGitRemote(){try{return await k("/api/git/remote")}catch{return{inRepo:!1,url:null,name:null}}},async fetchGitGovernedContext(){try{return await k("/api/git/governed-context")}catch{return{inRepo:!1,trackingReady:!1,legacyBroadIgnore:!1,domains:Ko(),skills:Ko(),artifacts:Ko(),learning:Ko()}}},async enableGitGovernedContextTracking(){try{return await k("/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 k("/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 k("/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 k("/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 k("/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 k("/api/git/push",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitPull(){try{return await k("/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 k("/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 k("/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 k("/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 k("/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 k("/api/apps");return e}catch{return[]}},async listAppsStrict(){const{apps:e}=await k("/api/apps");return e},async recommendAppBlocks(e,t){const{blocks:n}=await k("/api/apps/recommend-blocks",{method:"POST",body:JSON.stringify(e),signal:t});return n},async listAppSourceCandidates(e,t={},n){var i;const r=new URLSearchParams;(i=t.query)!=null&&i.trim()&&r.set("q",t.query.trim()),t.cursor&&r.set("cursor",t.cursor),r.set("limit",String(t.limit??50));for(const a of t.lifecycles??[])r.append("lifecycle",a);for(const a of t.domains??[])r.append("domain",a);t.includeDeprecated&&r.set("includeDeprecated","true");const o=await k(`/api/app-builds/${encodeURIComponent(e)}/source-candidates?${r.toString()}`,{signal:n});return{...o,items:o.items.map(Xc)}},async resolveAppSourceCandidates(e,t){const n=await k(`/api/app-builds/${encodeURIComponent(e)}/source-candidates`,{method:"POST",body:JSON.stringify({sourceIds:t})});return{...n,items:n.items.map(Xc)}},async createApp(e){return k("/api/apps",{method:"POST",body:JSON.stringify(e)})},async createAppBuild(e){return k("/api/app-builds",{method:"POST",body:JSON.stringify(e)})},async listAppBuilds(){return k("/api/app-builds")},async proposeAppBuildChanges(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals`,{method:"POST",body:JSON.stringify(t)})},async reviseAppBuildProposal(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals/${encodeURIComponent(t)}/revisions`,{method:"POST",body:JSON.stringify(n)})},async generateAppBuildGap(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals/${encodeURIComponent(t)}/gaps`,{method:"POST",body:JSON.stringify(n)})},async patchAppBuild(e,t,n,r){return k(`/api/app-builds/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({expectedRevision:t,expectedProposalHash:r,operations:n})})},async composeAppBuild(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/compose`,{method:"POST",body:JSON.stringify(t)})},async addAskResultToAppBuild(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/ask-results`,{method:"POST",body:JSON.stringify(t)})},async preflightAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/preflight`,{method:"POST",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async publishAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/publish-to-project`,{method:"POST",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async deleteAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async commitAppBuild(e,t,n){return this.publishAppBuild(e,t,n)},async generateApp(e){try{return await k("/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 k("/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 k(`/api/apps/ai-builds/${encodeURIComponent(e)}`);return t}catch{return null}},async proposeAppAiBuild(e){try{return await k("/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 proposeAppAiBuildInBackground(e){return k("/api/apps/ai-builds/propose-background",{method:"POST",body:JSON.stringify(e)})},async commitAppAiBuild(e,t={}){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}`)}catch{return null}},async deleteApp(e,t){return k(`/api/apps/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({expectedFingerprint:t})})},async restoreApp(e){return k(`/api/app-recoveries/${encodeURIComponent(e)}/restore`,{method:"POST",body:"{}"})},async renameApp(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async attachAppNotebook(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/notebook-candidates`);return t}catch{return[]}},async createAppNotebook(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/notebooks/preview?path=${encodeURIComponent(t)}`)}catch{return null}},async runAppNotebook(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/conversations`);return t}catch{return[]}},async createAppConversation(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`);return n}catch{return null}},async updateAppConversation(e,t,n){try{return await k(`/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 k(`/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 k(`/api/apps/${encodeURIComponent(e)}/investigations${r?`?${r}`:""}`);return o}catch{return[]}},async createAppInvestigation(e,t){try{return await k(`/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 k(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}`);return n}catch{return null}},async runAppInvestigation(e,t,n){try{return await k(`/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 k(`/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 k(`/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 k(`/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 k(`/api/apps/${encodeURIComponent(e)}/editor/catalog${r?`?${r}`:""}`)}catch{return null}},async createAppDashboard(e,t){try{return await k(`/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 k(`/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 k(`/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 publishAppToProject(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/publish-to-project`,{method:"POST",body:JSON.stringify(t??{})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteApp(e,t){return B.publishAppToProject(e,t)},async approveAppSemanticTiles(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/approve-semantic`,{method:"POST",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async recommendVisualization(e){try{return await k("/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 k(`/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 k(`/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 k(`/api/apps/${encodeURIComponent(e)}/ai-pins${r?`?${r}`:""}`);return o}catch{return[]}},async refreshAiPin(e,t){try{return await k(`/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 k(`/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 k(`/api/lineage/scope?${t.toString()}`)}catch{return null}},async runDashboard(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})}catch{return null}},async runAppBuildPreview(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})},async retryDashboardTile(e,t,n,r){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:r??{},tileId:n})})}catch{return null}},async getDashboardStory(e,t,n){try{return await k(`/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 k(`/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 k("/api/persona");return e}catch{return null}},async setPersona(e,t){try{const{persona:n}=await k("/api/persona",{method:"POST",body:JSON.stringify({userId:e,appId:t})});return n}catch{return null}},async clearPersona(){try{await k("/api/persona",{method:"DELETE"})}catch{}},async getSkills(){return k("/api/skills")},async getSkillPathSettings(){return k("/api/skills/settings")},async updateSkillPath(e){return k("/api/skills/settings",{method:"PUT",body:JSON.stringify({path:e})})},async getSkillOptions(e=""){const t=e.trim()?`?q=${encodeURIComponent(e.trim())}`:"";return k(`/api/skills/options${t}`)},async createSkill(e){return k("/api/skills",{method:"POST",body:JSON.stringify({skill:e})})},async updateSkill(e,t){return k(`/api/skills/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({skill:t})})},async getEmbeddingSettings(){return k("/api/settings/embeddings")},async saveEmbeddingSettings(e){return k("/api/settings/embeddings",{method:"PUT",body:JSON.stringify(e)})},async listEmbeddingModels(e){const t=e?`?endpoint=${encodeURIComponent(e)}`:"";return k(`/api/settings/embeddings/models${t}`)},async installEmbeddingModel(e,t){return k("/api/settings/embeddings/install",{method:"POST",body:JSON.stringify({model:e,endpoint:t})})},async testEmbeddingProvider(){return k("/api/settings/embeddings/test",{method:"POST"})},async reindexEmbeddings(){return k("/api/settings/embeddings/reindex",{method:"POST"})},async deleteSkill(e){return k(`/api/skills/${encodeURIComponent(e)}`,{method:"DELETE"})},async getDomains(){try{return await k("/api/domains")}catch{return{domains:[]}}},async createDomain(e){return k("/api/domains",{method:"POST",body:JSON.stringify({domain:e})})},async updateDomain(e,t){return k(`/api/domains/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({domain:t})})},async deleteDomain(e){return k(`/api/domains/${encodeURIComponent(e)}`,{method:"DELETE"})},async startContextBootstrap(e={}){return k("/api/context-bootstrap",{method:"POST",body:JSON.stringify(e)})},async getContextBootstrap(e){return k(`/api/context-bootstrap/${encodeURIComponent(e)}`)},async getLatestContextBootstrap(){return(await k("/api/context-bootstrap/latest")).session??null},async saveContextBootstrapSelected(e,t){return k(`/api/context-bootstrap/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify({candidateIds:t})})}},Aw={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"},Rw={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"},Rp={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"},Lj={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"},Nj={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"},Ow={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Zc={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},el=["source","transform","answer","consumption"],Bj=["term","business_view","block","metric","dimension","domain","source_table","dbt_source","dbt_model","chart","notebook","dashboard","app"],Fj=["source_table","dbt_source","dbt_model"],_w=["term","domain","business_view","metric","dimension","block"];[..._w];function Pw(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 Iw(){const{state:e,dispatch:t}=et(),n=e.inspectorContext;return s.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${pe("borderSubtle")}`,background:pe("surfaceBase"),color:pe("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${be[3]}px ${be[4]}px`,borderBottom:`1px solid ${pe("borderSubtle")}`},children:[s.jsx("div",{style:{fontSize:Ze.sm,fontWeight:Xi.semibold},children:n?Dw(n):"Inspector"}),s.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:pe("textMuted"),cursor:"pointer",fontSize:Ze.md,padding:2,borderRadius:wn.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:be[4]},children:n?s.jsx($w,{context:n}):s.jsx(Bw,{})})]})}function Dw(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function $w({context:e}){return e.kind==="cell"?s.jsx(Mw,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx(Lw,{nodeId:e.nodeId}):s.jsx(Nw,{name:e.name})}function Mw({cellId:e}){const{state:t}=et(),n=t.cells.find(r=>r.id===e);return n?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3],fontSize:Ze.sm},children:[s.jsx(Ie,{label:"Type",children:n.type}),s.jsx(Ie,{label:"ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),s.jsxs(Ie,{label:"Length",children:[n.content.length," chars"]}),n.status&&s.jsx(Ie,{label:"Status",children:n.status})]}):s.jsx(fs,{children:"No matching cell in the active notebook."})}function Lw({nodeId:e}){const[t,n]=p.useState(null),[r,o]=p.useState(!0);if(p.useEffect(()=>{let c=!1;return o(!0),B.fetchLineageNode(e).then(l=>{c||(n(l),o(!1))}).catch(()=>{c||o(!1)}),()=>{c=!0}},[e]),r)return s.jsx(fs,{children:"Loading node…"});if(!t||!t.node)return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Node ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),s.jsx(fs,{children:"No metadata available for this node."})]});const i=t.node,a=i.metadata??{};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Name",children:i.name??e}),s.jsx(Ie,{label:"Type",children:Rp[i.type]??i.type}),i.domain&&s.jsx(Ie,{label:"Domain",children:i.domain}),i.owner&&s.jsx(Ie,{label:"Owner",children:i.owner}),i.status&&s.jsx(Ie,{label:"Status",children:i.status}),typeof a.termType=="string"&&s.jsx(Ie,{label:"Term Type",children:a.termType}),typeof a.description=="string"&&s.jsx(Ie,{label:"Description",children:a.description}),Array.isArray(a.identifiers)&&a.identifiers.length>0&&s.jsx(Ie,{label:"Identifiers",children:a.identifiers.map(String).join(", ")}),Array.isArray(a.synonyms)&&a.synonyms.length>0&&s.jsx(Ie,{label:"Synonyms",children:a.synonyms.map(String).join(", ")}),typeof a.businessOutcome=="string"&&s.jsx(Ie,{label:"Business Outcome",children:a.businessOutcome}),i.layer&&s.jsx(Ie,{label:"Layer",children:i.layer}),s.jsx(Ie,{label:"Upstream",children:t.incoming.length}),s.jsx(Ie,{label:"Downstream",children:t.outgoing.length}),(i.path||a.filePath)&&s.jsx(Ie,{label:"Path",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ze.xs},children:i.path??a.filePath})})]})}function Nw({name:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Metric",children:e}),s.jsx(fs,{children:"Definition, dimensions, and governance surface will render here."})]})}function Ie({label:e,children:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[s.jsx("div",{style:{fontSize:Ze.xs,color:pe("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Xi.medium},children:e}),s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textPrimary")},children:t})]})}function fs({children:e}){return s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textSecondary"),lineHeight:1.5,background:pe("surfaceSunken"),border:`1px solid ${pe("borderSubtle")}`,borderRadius:wn.md,padding:be[3]},children:e})}function Bw(){return s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const Jr={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"},tl={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 nl(e){if(typeof document>"u")return tl[e];const t=Jr[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||tl[e]}function Fw(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Jr)return nl(t)},has(e,t){return typeof t=="string"&&t in Jr},ownKeys(){return Object.keys(Jr)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Jr)))return{enumerable:!0,configurable:!0,value:nl(t)}}})}const On=Fw(),Qe={obsidian:On,paper:On,white:On,dark:On,light:On,midnight:On,arctic:On};function Ct(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 zw=Ct(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"})]}));Ct(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 qw=Ct(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"})]})),zj=Ct(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"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),s.jsx("path",{d:"M16 20l4 4"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 3v18h18"}),s.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]}));Ct(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"})]}));Ct(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 qj=Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),s.jsx("circle",{cx:"18",cy:"17",r:"2"})]}));Ct(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));Ct(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"})]}));Ct(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 Op=44,_p=188,Pp="dql-activitybar-expanded";function Uw(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(Pp))==="1"}catch{return!1}}function Ww(e){var t;try{(t=window.localStorage)==null||t.setItem(Pp,e?"1":"0")}catch{}}function rl({title:e,icon:t,active:n,expanded:r,onClick:o,t:i}){const[a,c]=p.useState(!1),l=s.jsxs("button",{"aria-label":e,onClick:o,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{width:r?_p-12:Op-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":a?i.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?i.accent:a?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?l:s.jsx(Jd,{content:e,side:"right",children:l})}function Kw(){const e=Ge(Lr(l=>({mainView:l.mainView,sidebarOpen:l.sidebarOpen,sidebarPanel:l.sidebarPanel,themeMode:l.themeMode}))),t=jn(),n=Qe[e.themeMode],[r,o]=p.useState(Uw);p.useEffect(()=>{Ww(r)},[r]);function i(l){if(l==="home"||l==="ask"||l==="modeling"){t({type:"SET_MAIN_VIEW",view:l});return}if(l==="lineage"){t({type:"SET_SIDEBAR_PANEL",panel:"lineage"});return}if(l==="connection"||l==="git"||l==="apps"||l==="readiness"||l==="skills"||l==="domains"||l==="settings"){t({type:"SET_SIDEBAR_PANEL",panel:l});return}e.sidebarPanel===l&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:l})}const a=[{label:"Insights",items:[{key:"apps",title:"Apps",icon:s.jsx(kS,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"ask",title:"Ask",icon:s.jsx(mS,{size:16,strokeWidth:1.75}),active:e.mainView==="ask"}]},{label:"Build",items:[{key:"files",title:"Notebooks",icon:s.jsx(Pa,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"block_library",title:"Blocks",icon:s.jsx(zw,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(qw,{size:16}),active:e.mainView==="lineage"||e.mainView==="lineage_detail"}]},{label:"Govern",items:[{key:"domains",title:"Modeling",icon:s.jsx(Fi,{size:16,strokeWidth:1.75}),active:e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills"},{key:"git",title:"Source control",icon:s.jsx(Nr,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"settings",title:"Settings",icon:s.jsx(LS,{size:16,strokeWidth:1.75}),active:e.mainView==="settings"||e.mainView==="connection"}]}],c=[{key:"help",title:"Help",icon:s.jsx(Ov,{size:16,strokeWidth:1.75}),active:e.mainView==="help",onClick:()=>t({type:"SET_MAIN_VIEW",view:"help"})}];return s.jsxs("div",{style:{width:r?_p:Op,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(Jd,{content:r?"Collapse":"Expand",side:"right",children:s.jsx("button",{"aria-label":r?"Collapse sidebar rail":"Expand sidebar rail",onClick:()=>o(l=>!l),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:l=>{l.currentTarget.style.color=n.textPrimary,l.currentTarget.style.background=n.textPrimary+"0f"},onMouseLeave:l=>{l.currentTarget.style.color=n.textMuted,l.currentTarget.style.background="transparent"},children:r?s.jsx(kv,{size:14,strokeWidth:2}):s.jsx(jv,{size:14,strokeWidth:2})})})}),a.map((l,u)=>s.jsxs(qe.Fragment,{children:[u>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:l.label}):null,l.items.map(h=>s.jsx(rl,{title:h.title,icon:h.icon,active:h.active,expanded:r,onClick:()=>i(h.key),t:n},h.key))]},l.label)),s.jsx("div",{style:{flex:1}}),c.map(l=>s.jsx(rl,{title:l.title,icon:l.icon,active:l.active,expanded:r,onClick:l.onClick,t:n},l.key))]})}const Vw=2e4,Uj="application/dql-semantic-ref",ol=new Map;let po=null;function Hw(e){B.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function sl(e,t){const n=`${e}:${t.toLowerCase()}`,r=ol.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 a=await i.json(),c=Array.isArray(a.completions)?a.completions:[];return ol.set(n,{items:c,expiresAt:Date.now()+Vw}),c}function Ip(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 Wj(e){po=e}function Kj(e){po===e&&(po=null)}function Gw(e){return po?(Ip(po,e),!0):!1}function Vj(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;Ip(e,t,r)}function il(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
397
397
  ${e.description}`:""}${e.sql?`
398
- ${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}}),Vw(e.name)}}}function Gw(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 Vj=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 c=o[1].trim().toLowerCase(),l=n-o[1].length,u=await ol("metric",c);return{from:l,options:u.map(h=>sl(h,l,n)),validFor:/^[\w-]*$/}}const i=/@dim\(([^)]*)$/i.exec(r);if(i){const c=i[1].trim().toLowerCase(),l=n-i[1].length,u=await ol("dimension",c);return{from:l,options:u.map(h=>sl(h,l,n)),validFor:/^[\w-]*$/}}const a=/@([md][a-z_]*)?$/i.exec(r);return a?Gw(n-a[0].length):(e.explicit,null)};function Hj(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 Qw=6,Jw=999,Yw={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 Re(e,t={}){const{variant:n="secondary",size:r="sm",active:o=!1,disabled:i=!1,pill:a=!1}=t,c=Yw[r],l=n==="danger"?e.error:n==="success"?e.success:n==="accent"?e.accent:void 0,u={boxSizing:"border-box",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:c.gap,height:c.height,padding:`0 ${c.paddingX}px`,borderRadius:a?Jw:Qw,fontSize:c.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"?{...u,background:e.accent,border:`1px solid ${e.accent}`,color:"#ffffff"}:n==="ghost"?{...u,background:o?`${e.accent}14`:"transparent",border:"1px solid transparent",color:o?e.accent:e.textMuted,fontWeight:550}:l?{...u,background:o?`${l}22`:`${l}12`,border:`1px solid ${l}${o?"66":"33"}`,color:l}:{...u,background:o?`${e.accent}14`:e.btnBg,border:`1px solid ${o?e.accent:e.btnBorder}`,color:o?e.accent:e.textSecondary}}const Xw=new Set(["metric","measure","dimension","time_dimension"]);function Ds(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 Wi(e){const t=Ds(e);return e.kind==="metric"||e.kind==="measure"?`@metric(${t})`:`@dim(${t})`}function Ip(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():"")||Ds(e)}function Ia(e,t){return!t||e.label.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||Ds(e).toLowerCase().includes(t)||Ip(e).toLowerCase().includes(t)?!0:(e.children??[]).some(n=>Ia(n,t))}function Dp(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,a=i?`group:${o.label.toLowerCase()}`:`leaf:${Wi(o).toLowerCase()}`,c=n.get(a);if(c){i&&c.children&&(c.children=c.children.concat(o.children??[]));continue}const l=o.children?{...o,children:[...o.children]}:o;n.set(a,l),t.push(l)}for(const o of t)o.children&&(o.children=Dp(o.children));return t}const Ys={metric:{Icon:rS,tone:e=>e.accent},measure:{Icon:qS,tone:e=>e.accent},dimension:{Icon:HS,tone:e=>e.success},time_dimension:{Icon:_v,tone:e=>e.warning},entity:{Icon:fv,tone:e=>e.textSecondary},segment:{Icon:tS,tone:e=>e.textMuted},hierarchy:{Icon:Nr,tone:e=>e.textMuted},pre_aggregation:{Icon:bp,tone:e=>e.textMuted},cube:{Icon:Fi,tone:e=>e.textSecondary},semantic_model:{Icon:Fi,tone:e=>e.textSecondary},saved_query:{Icon:uv,tone:e=>e.textMuted},provider:{Icon:ro,tone:e=>e.textMuted},domain:{Icon:ro,tone:e=>e.textMuted},group:{Icon:ro,tone:e=>e.textMuted}};function Zw(e){var t;if(e.kind==="group"){const n=typeof((t=e.meta)==null?void 0:t.objectKind)=="string"?e.meta.objectKind:"";return Ys[n]??Ys.group}return Ys[e.kind]}function e0({tree:e,themeMode:t,search:n="",onInsert:r,selectionMode:o=!1,selected:i=new Set,onToggleSelection:a,canSelect:c=()=>({allowed:!0})}){const l=Qe[t],u=n.trim().toLowerCase(),h=Dp(e.children??[]).filter(d=>Ia(d,u));return h.length===0?s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:l.textMuted,textAlign:"center"},children:u?"No matches.":"No semantic objects."}):s.jsx(s.Fragment,{children:h.map(d=>s.jsx($p,{node:d,t:l,q:u,onInsert:r,depth:0,selectionMode:o,selected:i,onToggleSelection:a,canSelect:c},d.id))})}function $p({node:e,t,q:n,onInsert:r,depth:o,selectionMode:i,selected:a,onToggleSelection:c,canSelect:l}){var A;const u=(((A=e.children)==null?void 0:A.length)??0)>0,[h,d]=p.useState(o<1||!!n);p.useEffect(()=>{n&&d(!0)},[n]);const f=Xw.has(e.kind),m=Zw(e),S=m==null?void 0:m.Icon,v=10+o*13,b=e.kind==="metric"||e.kind==="measure"?"metric":e.kind==="dimension"||e.kind==="time_dimension"?"dimension":null,w=Ds(e),j=Ip(e),C=w!==j?` · DQL ${w}`:"",x=b?`${b}:${w}`:"",E=b?l(b,w):{allowed:!1};if(!u)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&&E.allowed?c==null||c(b,w):!i&&f&&r(Wi(e))},disabled:i&&!!b&&!E.allowed,title:i&&b?E.allowed?`Select ${e.label} · dbt ${j}${C}`:E.reason||"Not compatible with the current selection":f?`Insert ${Wi(e)} · dbt ${j}${C}`:e.label,style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,boxSizing:"border-box",padding:`5px 6px 5px ${v+15}px`,border:"none",background:"transparent",cursor:i&&b?E.allowed?"pointer":"not-allowed":f?"pointer":"default",textAlign:"left",fontFamily:t.font,color:E.allowed||!b?t.textPrimary:t.textMuted,opacity:i&&b&&!E.allowed?.55:1},children:[i&&b&&s.jsx("input",{type:"checkbox",readOnly:!0,checked:a.has(x),disabled:!E.allowed,style:{accentColor:t.accent,margin:0,flexShrink:0}}),S&&s.jsx(S,{size:13,color:m.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}),j!==e.label?s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:9.5,fontFamily:t.fontMono,color:t.textMuted},children:j}):null]})]})});const P=(e.children??[]).filter(g=>Ia(g,n));return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>d(g=>!g),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,boxSizing:"border-box",padding:`6px 10px 6px ${v}px`,border:"none",borderBottom:`1px solid ${t.cellBorder}`,background:"transparent",cursor:"pointer",textAlign:"left",fontFamily:t.font,color:t.textPrimary},children:[h?s.jsx(_a,{size:13,color:t.textMuted,style:{flexShrink:0}}):s.jsx(Is,{size:13,color:t.textMuted,style:{flexShrink:0}}),S&&s.jsx(S,{size:13,color:m.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??P.length})]}),h&&P.map(g=>s.jsx($p,{node:g,t,q:n,onInsert:r,depth:o+1,selectionMode:i,selected:a,onToggleSelection:c,canSelect:l},g.id))]})}function qt(e){return(e==null?void 0:e.trim())??""}function Jn(e){const t=new Map;for(const r of e){const o=qt(r.id);o&&!t.has(o)&&t.set(o,{...r,id:o})}const n=r=>{const o=[qt(r.name)||r.id],i=new Set([r.id]);let a=qt(r.parent);for(;a&&!i.has(a);){i.add(a);const c=t.get(a);if(!c)break;o.unshift(qt(c.name)||c.id),a=qt(c.parent)}return o.join(" / ")};return[...t.values()].map(r=>({value:r.id,label:n(r)})).sort((r,o)=>r.label.localeCompare(o.label))}function Gj(e,t){const n=Jn(t),r=qt(e??void 0);return!r||n.some(o=>o.value===r)?n:[{value:r,label:`${r} (missing Domain page)`,disabled:!0},...n]}function Ao(e){return new Set(Jn(e).map(t=>t.value))}function Qj(e,t){const n=qt(e??void 0).toLowerCase();if(!n)return"";const r=t.find(o=>qt(o.id).toLowerCase()===n||qt(o.name).toLowerCase()===n);return qt(r==null?void 0:r.id)}function t0(e,t){const n=Ao(t),r=e.some(o=>{var i;return!n.has(((i=o.domain)==null?void 0:i.trim())??"")});return[...Jn(t).map(o=>o.value),...r?["uncategorized"]:[]]}function n0(e,t,n="",r=[]){const o=n.trim().toLowerCase(),i=Ao(r);return Array.from(new Map(e.map(a=>[a.path,a])).values()).filter(a=>{var l;const c=((l=a.domain)==null?void 0:l.trim())??"";return t==="uncategorized"&&i.has(c)||t&&t!=="uncategorized"&&(!i.has(t)||c!==t)?!1:!o||a.name.toLowerCase().includes(o)||(a.description??"").toLowerCase().includes(o)})}var Q;(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"})(Q||(Q={}));var dr;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(dr||(dr={}));class r0{constructor(){Pe(this,"diagnostics",[])}report(t){this.diagnostics.push(t)}error(t,n,r){this.report({severity:dr.Error,message:t,span:n,hint:r})}warning(t,n,r){this.report({severity:dr.Warning,message:t,span:n,hint:r})}hasErrors(){return this.diagnostics.some(t=>t.severity===dr.Error)}getErrors(){return this.diagnostics.filter(t=>t.severity===dr.Error)}getAll(){return[...this.diagnostics]}clear(){this.diagnostics=[]}format(t){return this.diagnostics.map(n=>o0(n,t)).join(`
398
+ ${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}}),Hw(e.name)}}}function Qw(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 Hj=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 c=o[1].trim().toLowerCase(),l=n-o[1].length,u=await sl("metric",c);return{from:l,options:u.map(h=>il(h,l,n)),validFor:/^[\w-]*$/}}const i=/@dim\(([^)]*)$/i.exec(r);if(i){const c=i[1].trim().toLowerCase(),l=n-i[1].length,u=await sl("dimension",c);return{from:l,options:u.map(h=>il(h,l,n)),validFor:/^[\w-]*$/}}const a=/@([md][a-z_]*)?$/i.exec(r);return a?Qw(n-a[0].length):(e.explicit,null)};function Gj(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 Jw=6,Yw=999,Xw={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 Re(e,t={}){const{variant:n="secondary",size:r="sm",active:o=!1,disabled:i=!1,pill:a=!1}=t,c=Xw[r],l=n==="danger"?e.error:n==="success"?e.success:n==="accent"?e.accent:void 0,u={boxSizing:"border-box",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:c.gap,height:c.height,padding:`0 ${c.paddingX}px`,borderRadius:a?Yw:Jw,fontSize:c.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"?{...u,background:e.accent,border:`1px solid ${e.accent}`,color:"#ffffff"}:n==="ghost"?{...u,background:o?`${e.accent}14`:"transparent",border:"1px solid transparent",color:o?e.accent:e.textMuted,fontWeight:550}:l?{...u,background:o?`${l}22`:`${l}12`,border:`1px solid ${l}${o?"66":"33"}`,color:l}:{...u,background:o?`${e.accent}14`:e.btnBg,border:`1px solid ${o?e.accent:e.btnBorder}`,color:o?e.accent:e.textSecondary}}const Zw=new Set(["metric","measure","dimension","time_dimension"]);function Ds(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 Wi(e){const t=Ds(e);return e.kind==="metric"||e.kind==="measure"?`@metric(${t})`:`@dim(${t})`}function Dp(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():"")||Ds(e)}function Ia(e,t){return!t||e.label.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||Ds(e).toLowerCase().includes(t)||Dp(e).toLowerCase().includes(t)?!0:(e.children??[]).some(n=>Ia(n,t))}function $p(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,a=i?`group:${o.label.toLowerCase()}`:`leaf:${Wi(o).toLowerCase()}`,c=n.get(a);if(c){i&&c.children&&(c.children=c.children.concat(o.children??[]));continue}const l=o.children?{...o,children:[...o.children]}:o;n.set(a,l),t.push(l)}for(const o of t)o.children&&(o.children=$p(o.children));return t}const Ys={metric:{Icon:oS,tone:e=>e.accent},measure:{Icon:US,tone:e=>e.accent},dimension:{Icon:GS,tone:e=>e.success},time_dimension:{Icon:Pv,tone:e=>e.warning},entity:{Icon:hv,tone:e=>e.textSecondary},segment:{Icon:nS,tone:e=>e.textMuted},hierarchy:{Icon:Nr,tone:e=>e.textMuted},pre_aggregation:{Icon:xp,tone:e=>e.textMuted},cube:{Icon:Fi,tone:e=>e.textSecondary},semantic_model:{Icon:Fi,tone:e=>e.textSecondary},saved_query:{Icon:pv,tone:e=>e.textMuted},provider:{Icon:ro,tone:e=>e.textMuted},domain:{Icon:ro,tone:e=>e.textMuted},group:{Icon:ro,tone:e=>e.textMuted}};function e0(e){var t;if(e.kind==="group"){const n=typeof((t=e.meta)==null?void 0:t.objectKind)=="string"?e.meta.objectKind:"";return Ys[n]??Ys.group}return Ys[e.kind]}function t0({tree:e,themeMode:t,search:n="",onInsert:r,selectionMode:o=!1,selected:i=new Set,onToggleSelection:a,canSelect:c=()=>({allowed:!0})}){const l=Qe[t],u=n.trim().toLowerCase(),h=$p(e.children??[]).filter(d=>Ia(d,u));return h.length===0?s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:l.textMuted,textAlign:"center"},children:u?"No matches.":"No semantic objects."}):s.jsx(s.Fragment,{children:h.map(d=>s.jsx(Mp,{node:d,t:l,q:u,onInsert:r,depth:0,selectionMode:o,selected:i,onToggleSelection:a,canSelect:c},d.id))})}function Mp({node:e,t,q:n,onInsert:r,depth:o,selectionMode:i,selected:a,onToggleSelection:c,canSelect:l}){var A;const u=(((A=e.children)==null?void 0:A.length)??0)>0,[h,d]=p.useState(o<1||!!n);p.useEffect(()=>{n&&d(!0)},[n]);const f=Zw.has(e.kind),m=e0(e),S=m==null?void 0:m.Icon,v=10+o*13,b=e.kind==="metric"||e.kind==="measure"?"metric":e.kind==="dimension"||e.kind==="time_dimension"?"dimension":null,w=Ds(e),j=Dp(e),C=w!==j?` · DQL ${w}`:"",x=b?`${b}:${w}`:"",E=b?l(b,w):{allowed:!1};if(!u)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&&E.allowed?c==null||c(b,w):!i&&f&&r(Wi(e))},disabled:i&&!!b&&!E.allowed,title:i&&b?E.allowed?`Select ${e.label} · dbt ${j}${C}`:E.reason||"Not compatible with the current selection":f?`Insert ${Wi(e)} · dbt ${j}${C}`:e.label,style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,boxSizing:"border-box",padding:`5px 6px 5px ${v+15}px`,border:"none",background:"transparent",cursor:i&&b?E.allowed?"pointer":"not-allowed":f?"pointer":"default",textAlign:"left",fontFamily:t.font,color:E.allowed||!b?t.textPrimary:t.textMuted,opacity:i&&b&&!E.allowed?.55:1},children:[i&&b&&s.jsx("input",{type:"checkbox",readOnly:!0,checked:a.has(x),disabled:!E.allowed,style:{accentColor:t.accent,margin:0,flexShrink:0}}),S&&s.jsx(S,{size:13,color:m.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}),j!==e.label?s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:9.5,fontFamily:t.fontMono,color:t.textMuted},children:j}):null]})]})});const P=(e.children??[]).filter(g=>Ia(g,n));return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>d(g=>!g),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,boxSizing:"border-box",padding:`6px 10px 6px ${v}px`,border:"none",borderBottom:`1px solid ${t.cellBorder}`,background:"transparent",cursor:"pointer",textAlign:"left",fontFamily:t.font,color:t.textPrimary},children:[h?s.jsx(_a,{size:13,color:t.textMuted,style:{flexShrink:0}}):s.jsx(Is,{size:13,color:t.textMuted,style:{flexShrink:0}}),S&&s.jsx(S,{size:13,color:m.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??P.length})]}),h&&P.map(g=>s.jsx(Mp,{node:g,t,q:n,onInsert:r,depth:o+1,selectionMode:i,selected:a,onToggleSelection:c,canSelect:l},g.id))]})}function qt(e){return(e==null?void 0:e.trim())??""}function Jn(e){const t=new Map;for(const r of e){const o=qt(r.id);o&&!t.has(o)&&t.set(o,{...r,id:o})}const n=r=>{const o=[qt(r.name)||r.id],i=new Set([r.id]);let a=qt(r.parent);for(;a&&!i.has(a);){i.add(a);const c=t.get(a);if(!c)break;o.unshift(qt(c.name)||c.id),a=qt(c.parent)}return o.join(" / ")};return[...t.values()].map(r=>({value:r.id,label:n(r)})).sort((r,o)=>r.label.localeCompare(o.label))}function Qj(e,t){const n=Jn(t),r=qt(e??void 0);return!r||n.some(o=>o.value===r)?n:[{value:r,label:`${r} (missing Domain page)`,disabled:!0},...n]}function Ao(e){return new Set(Jn(e).map(t=>t.value))}function Jj(e,t){const n=qt(e??void 0).toLowerCase();if(!n)return"";const r=t.find(o=>qt(o.id).toLowerCase()===n||qt(o.name).toLowerCase()===n);return qt(r==null?void 0:r.id)}function n0(e,t){const n=Ao(t),r=e.some(o=>{var i;return!n.has(((i=o.domain)==null?void 0:i.trim())??"")});return[...Jn(t).map(o=>o.value),...r?["uncategorized"]:[]]}function r0(e,t,n="",r=[]){const o=n.trim().toLowerCase(),i=Ao(r);return Array.from(new Map(e.map(a=>[a.path,a])).values()).filter(a=>{var l;const c=((l=a.domain)==null?void 0:l.trim())??"";return t==="uncategorized"&&i.has(c)||t&&t!=="uncategorized"&&(!i.has(t)||c!==t)?!1:!o||a.name.toLowerCase().includes(o)||(a.description??"").toLowerCase().includes(o)})}var Q;(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"})(Q||(Q={}));var dr;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(dr||(dr={}));class o0{constructor(){Pe(this,"diagnostics",[])}report(t){this.diagnostics.push(t)}error(t,n,r){this.report({severity:dr.Error,message:t,span:n,hint:r})}warning(t,n,r){this.report({severity:dr.Warning,message:t,span:n,hint:r})}hasErrors(){return this.diagnostics.some(t=>t.severity===dr.Error)}getErrors(){return this.diagnostics.filter(t=>t.severity===dr.Error)}getAll(){return[...this.diagnostics]}clear(){this.diagnostics=[]}format(t){return this.diagnostics.map(n=>s0(n,t)).join(`
399
399
 
400
- `)}}function o0(e,t){const{severity:n,message:r,span:o,hint:i}=e,c=t.split(`
400
+ `)}}function s0(e,t){const{severity:n,message:r,span:o,hint:i}=e,c=t.split(`
401
401
  `)[o.start.line-1]??"",l=String(o.start.line),u=" ".repeat(l.length),h=o.start.file?`${o.start.file}:`:"";let d=`${n}: ${r}
402
402
  `;d+=` --> ${h}${o.start.line}:${o.start.column}
403
403
  `,d+=`${u} |
404
404
  `,d+=`${l} | ${c}
405
405
  `;const f=o.start.column-1,m=Math.max(1,o.start.line===o.end.line?o.end.column-o.start.column:c.length-f);return d+=`${u} | ${" ".repeat(f)}${"^".repeat(m)}`,i&&(d+=`
406
- ${u} = hint: ${i}`),d}class s0 extends Error{constructor(n,r){super(n);Pe(this,"diagnostics");this.diagnostics=r,this.name="DQLSyntaxError"}}var y;(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"})(y||(y={}));const i0={dashboard:y.DashboardKeyword,workbook:y.WorkbookKeyword,page:y.PageKeyword,let:y.LetKeyword,param:y.ParamKeyword,chart:y.ChartKeyword,filter:y.FilterKeyword,true:y.BooleanLiteral,false:y.BooleanLiteral,INTERVAL:y.IntervalKeyword,import:y.ImportKeyword,from:y.FromKeyword,use:y.UseKeyword,layout:y.LayoutKeyword,row:y.RowKeyword,block:y.BlockKeyword,term:y.TermKeyword,terms:y.TermsKeyword,business_view:y.BusinessViewKeyword,includes:y.IncludesKeyword,domain:y.DomainKeyword,type:y.TypeKeyword,description:y.DescriptionKeyword,tags:y.TagsKeyword,owner:y.OwnerKeyword,query:y.QueryKeyword,visualization:y.VisualizationKeyword,tests:y.TestsKeyword,params:y.ParamsKeyword,assert:y.AssertKeyword,var:y.VarKeyword,default:y.DefaultKeyword,IN:y.InKeyword,metric:y.MetricKeyword,metrics:y.MetricsKeyword,dimensions:y.DimensionsKeyword,digest:y.DigestKeyword,narrative:y.NarrativeKeyword};function a0(e){return i0[e]??y.Identifier}const Xs=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"]),c0={"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 l0(e){return c0[e]??e}const Zs=new Set(["dropdown","date_range","text","multi_select","range"]),d0=new Set(["SELECT","WITH"]);class hs{constructor(t,n){Pe(this,"source");Pe(this,"pos",0);Pe(this,"line",1);Pe(this,"column",1);Pe(this,"file");this.source=t,this.file=n}tokenize(){const t=[];for(;!this.isAtEnd()&&(this.skipWhitespace(),!this.isAtEnd());){const n=this.nextToken();n.type!==y.Comment&&t.push(n)}return t.push(this.makeToken(y.EOF,"",this.location())),t}nextToken(){if(this.skipWhitespace(),this.isAtEnd())return this.makeToken(y.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(y.GreaterThanOrEqual,">=",t)):n==="<"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(y.LessThanOrEqual,"<=",t)):n==="="&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(y.DoubleEquals,"==",t)):n==="!"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(y.NotEquals,"!=",t)):this.readPunctuation(t)}static scanSQLBoundary(t,n,r){let o=n,i=r;const a=t.length;for(;o<a;){const l=t[o];if(l==="'"||l==='"'){o=hs.skipStringInSQL(t,o);continue}if(l==="("){i++,o++;continue}if(l===")"){if(i===1)return{sql:t.substring(n,o).trim(),endOffset:o};i--,o++;continue}if(l===","&&i===1){let u=o+1;for(;u<a&&/\s/.test(t[u]);)u++;if(u<a&&/[a-zA-Z_]/.test(t[u])){let h=u;for(;h<a&&/[a-zA-Z0-9_]/.test(t[h]);)h++;let d=h;for(;d<a&&/\s/.test(t[d]);)d++;if(d<a&&t[d]==="="&&(d+1>=a||t[d+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()!==`
406
+ ${u} = hint: ${i}`),d}class i0 extends Error{constructor(n,r){super(n);Pe(this,"diagnostics");this.diagnostics=r,this.name="DQLSyntaxError"}}var y;(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"})(y||(y={}));const a0={dashboard:y.DashboardKeyword,workbook:y.WorkbookKeyword,page:y.PageKeyword,let:y.LetKeyword,param:y.ParamKeyword,chart:y.ChartKeyword,filter:y.FilterKeyword,true:y.BooleanLiteral,false:y.BooleanLiteral,INTERVAL:y.IntervalKeyword,import:y.ImportKeyword,from:y.FromKeyword,use:y.UseKeyword,layout:y.LayoutKeyword,row:y.RowKeyword,block:y.BlockKeyword,term:y.TermKeyword,terms:y.TermsKeyword,business_view:y.BusinessViewKeyword,includes:y.IncludesKeyword,domain:y.DomainKeyword,type:y.TypeKeyword,description:y.DescriptionKeyword,tags:y.TagsKeyword,owner:y.OwnerKeyword,query:y.QueryKeyword,visualization:y.VisualizationKeyword,tests:y.TestsKeyword,params:y.ParamsKeyword,assert:y.AssertKeyword,var:y.VarKeyword,default:y.DefaultKeyword,IN:y.InKeyword,metric:y.MetricKeyword,metrics:y.MetricsKeyword,dimensions:y.DimensionsKeyword,digest:y.DigestKeyword,narrative:y.NarrativeKeyword};function c0(e){return a0[e]??y.Identifier}const Xs=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"]),l0={"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 d0(e){return l0[e]??e}const Zs=new Set(["dropdown","date_range","text","multi_select","range"]),u0=new Set(["SELECT","WITH"]);class hs{constructor(t,n){Pe(this,"source");Pe(this,"pos",0);Pe(this,"line",1);Pe(this,"column",1);Pe(this,"file");this.source=t,this.file=n}tokenize(){const t=[];for(;!this.isAtEnd()&&(this.skipWhitespace(),!this.isAtEnd());){const n=this.nextToken();n.type!==y.Comment&&t.push(n)}return t.push(this.makeToken(y.EOF,"",this.location())),t}nextToken(){if(this.skipWhitespace(),this.isAtEnd())return this.makeToken(y.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(y.GreaterThanOrEqual,">=",t)):n==="<"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(y.LessThanOrEqual,"<=",t)):n==="="&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(y.DoubleEquals,"==",t)):n==="!"&&this.peekNext()==="="?(this.advance(),this.advance(),this.makeToken(y.NotEquals,"!=",t)):this.readPunctuation(t)}static scanSQLBoundary(t,n,r){let o=n,i=r;const a=t.length;for(;o<a;){const l=t[o];if(l==="'"||l==='"'){o=hs.skipStringInSQL(t,o);continue}if(l==="("){i++,o++;continue}if(l===")"){if(i===1)return{sql:t.substring(n,o).trim(),endOffset:o};i--,o++;continue}if(l===","&&i===1){let u=o+1;for(;u<a&&/\s/.test(t[u]);)u++;if(u<a&&/[a-zA-Z_]/.test(t[u])){let h=u;for(;h<a&&/[a-zA-Z0-9_]/.test(t[h]);)h++;let d=h;for(;d<a&&/\s/.test(t[d]);)d++;if(d<a&&t[d]==="="&&(d+1>=a||t[d+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()!==`
407
407
  `;)n+=this.advance();return this.makeToken(y.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+=`
408
- `;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(y.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(y.NumberLiteral,n,t)}readIdentifierOrKeyword(t){let n="";for(;!this.isAtEnd()&&(this.isAlphaNumeric(this.peek())||this.peek()==="_");)n+=this.advance();const r=a0(n);return this.makeToken(r,n,t)}readPunctuation(t){const n=this.advance();switch(n){case"(":return this.makeToken(y.LeftParen,n,t);case")":return this.makeToken(y.RightParen,n,t);case"{":return this.makeToken(y.LeftBrace,n,t);case"}":return this.makeToken(y.RightBrace,n,t);case"[":return this.makeToken(y.LeftBracket,n,t);case"]":return this.makeToken(y.RightBracket,n,t);case",":return this.makeToken(y.Comma,n,t);case".":return this.makeToken(y.Dot,n,t);case"=":return this.makeToken(y.Equals,n,t);case"+":return this.makeToken(y.Plus,n,t);case"-":return this.makeToken(y.Minus,n,t);case"*":return this.makeToken(y.Star,n,t);case"@":return this.makeToken(y.AtSign,n,t);case":":return this.makeToken(y.ColonToken,n,t);case">":return this.makeToken(y.GreaterThan,n,t);case"<":return this.makeToken(y.LessThan,n,t);default:return this.makeToken(y.Identifier,n,t)}}skipWhitespace(){for(;!this.isAtEnd();){const t=this.peek();if(t===" "||t===" "||t==="\r"||t===`
408
+ `;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(y.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(y.NumberLiteral,n,t)}readIdentifierOrKeyword(t){let n="";for(;!this.isAtEnd()&&(this.isAlphaNumeric(this.peek())||this.peek()==="_");)n+=this.advance();const r=c0(n);return this.makeToken(r,n,t)}readPunctuation(t){const n=this.advance();switch(n){case"(":return this.makeToken(y.LeftParen,n,t);case")":return this.makeToken(y.RightParen,n,t);case"{":return this.makeToken(y.LeftBrace,n,t);case"}":return this.makeToken(y.RightBrace,n,t);case"[":return this.makeToken(y.LeftBracket,n,t);case"]":return this.makeToken(y.RightBracket,n,t);case",":return this.makeToken(y.Comma,n,t);case".":return this.makeToken(y.Dot,n,t);case"=":return this.makeToken(y.Equals,n,t);case"+":return this.makeToken(y.Plus,n,t);case"-":return this.makeToken(y.Minus,n,t);case"*":return this.makeToken(y.Star,n,t);case"@":return this.makeToken(y.AtSign,n,t);case":":return this.makeToken(y.ColonToken,n,t);case">":return this.makeToken(y.GreaterThan,n,t);case"<":return this.makeToken(y.LessThan,n,t);default:return this.makeToken(y.Identifier,n,t)}}skipWhitespace(){for(;!this.isAtEnd();){const t=this.peek();if(t===" "||t===" "||t==="\r"||t===`
409
409
  `)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===`
410
410
  `?(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()===`
411
- `&&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(y.TripleQuoteString,n,t);n+=this.advance()}return this.makeToken(y.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 u0=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"]),p0=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 f0(e){return u0.has(e)}function h0(e){return p0.has(e)}class m0{constructor(t,n){Pe(this,"tokens");Pe(this,"pos",0);Pe(this,"source");Pe(this,"file");Pe(this,"reporter");this.source=t,this.file=n,this.reporter=new r0;const r=new hs(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 s0(`Parse errors in ${this.file??"<input>"}`,this.reporter.getErrors());return{kind:Q.Program,statements:n,span:this.makeSpan(t,this.currentSpan())}}parseStatement(){const t=this.parseDecoratorList();return this.check(y.WorkbookKeyword)?this.parseWorkbook(t):this.check(y.DashboardKeyword)?this.parseDashboard(t):this.check(y.DigestKeyword)?this.parseDigest(t):this.check(y.ChartKeyword)?this.parseChartCall(t):this.check(y.BlockKeyword)?this.parseBlockDecl(t):this.check(y.DomainKeyword)?this.parseDomainDecl(t):this.check(y.TermKeyword)?this.parseTermDecl(t):this.check(y.BusinessViewKeyword)?this.parseBusinessViewDecl(t):this.check(y.ImportKeyword)?(t.length>0&&this.error("Decorators cannot be applied to import statements."),this.parseImportDecl()):(this.check(y.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(y.FilterKeyword),this.expect(y.Dot);const n=this.expect(y.Identifier);Zs.has(n.value)||this.reporter.error(`Unknown filter type '${n.value}'. Valid types: ${[...Zs].join(", ")}`,n.span,`Did you mean one of: ${[...Zs].join(", ")}?`),this.expect(y.LeftParen);let r;const i=this.current().value.toUpperCase();(i==="SELECT"||i==="WITH")&&(r=this.parseSQLQuery());const a=[];for(;(this.check(y.Comma)||!r&&(this.check(y.Identifier)||this.isKeywordUsableAsArgName(this.current().type)))&&(this.check(y.Comma)&&this.advance(),!this.check(y.RightParen));)a.push(this.parseNamedArg());return this.expect(y.RightParen),{kind:Q.FilterCall,filterType:n.value,query:r,args:a,span:this.makeSpan(t,this.previousSpan())}}parseDashboard(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.DashboardKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);const o=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const i=this.parseDecoratorList();if(this.check(y.LetKeyword))i.length>0&&this.error("Decorators cannot be applied to variable declarations."),o.push(this.parseVariableDecl());else if(this.check(y.ParamKeyword))i.length>0&&this.error("Decorators cannot be applied to param declarations."),o.push(this.parseParamDecl());else if(this.check(y.ChartKeyword))o.push(this.parseChartCall(i));else if(this.check(y.FilterKeyword))i.length>0&&this.error("Decorators cannot be applied to filter declarations."),o.push(this.parseFilterCall());else if(this.check(y.UseKeyword))i.length>0&&this.error("Decorators cannot be applied to use declarations."),o.push(this.parseUseDecl());else if(this.check(y.LayoutKeyword))i.length>0&&this.error("Decorators cannot be applied to layout blocks."),o.push(this.parseLayoutBlock());else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside dashboard. Expected 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(y.RightBrace),{kind:Q.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(y.DigestKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);const o=[];let i;for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const a=this.parseDecoratorList();if(this.check(y.NarrativeKeyword))a.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(y.LetKeyword))a.length>0&&this.error("Decorators cannot be applied to variable declarations."),o.push(this.parseVariableDecl());else if(this.check(y.ParamKeyword))a.length>0&&this.error("Decorators cannot be applied to param declarations."),o.push(this.parseParamDecl());else if(this.check(y.ChartKeyword))o.push(this.parseChartCall(a));else if(this.check(y.FilterKeyword))a.length>0&&this.error("Decorators cannot be applied to filter declarations."),o.push(this.parseFilterCall());else if(this.check(y.UseKeyword))a.length>0&&this.error("Decorators cannot be applied to use declarations."),o.push(this.parseUseDecl());else if(this.check(y.LayoutKeyword))a.length>0&&this.error("Decorators cannot be applied to layout blocks."),o.push(this.parseLayoutBlock());else{if(this.check(y.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(y.RightBrace),{kind:Q.Digest,title:r.value,decorators:t,narrative:i,body:o,span:this.makeSpan(n,this.previousSpan())}}parseNarrative(){const t=this.currentSpan();this.expect(y.NarrativeKeyword),this.expect(y.LeftBrace);const n=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)n.push(this.parseNamedArg());return this.expect(y.RightBrace),{kind:Q.Narrative,properties:n,span:this.makeSpan(t,this.previousSpan())}}parseChartCall(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.ChartKeyword),this.expect(y.Dot);const r=this.currentSpan();let i=this.expect(y.Identifier).value;for(;this.check(y.Minus);)this.advance(),i+=`-${this.expect(y.Identifier).value}`;const a=this.makeSpan(r,this.previousSpan());Xs.has(i)||this.reporter.error(`Unknown chart type '${i}'. Valid types: ${[...Xs].join(", ")}`,a,`Did you mean one of: ${[...Xs].join(", ")}?`);const c=l0(i);this.expect(y.LeftParen);const l=this.parseSQLQuery(),u=[];for(;this.check(y.Comma)&&(this.advance(),!this.check(y.RightParen));)u.push(this.parseNamedArg());return this.expect(y.RightParen),{kind:Q.ChartCall,chartType:c,query:l,args:u,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseSQLQuery(){const t=this.currentSpan(),r=this.current().span.start.offset,{sql:o,endOffset:i}=hs.scanSQLBoundary(this.source,r,1),a=this.extractInterpolations(o,t);for(;!this.isAtEnd()&&this.current().span.start.offset<i;)this.advance();const c=this.makeSpan(t,this.currentSpan());return{kind:Q.SQLQuery,rawSQL:o,interpolations:a,span:c}}extractInterpolations(t,n){const r=[],o=/\$\{(\w+)\}|\{(\w+)\}/g;let i;for(;(i=o.exec(t))!==null;){const a=i[1]||i[2];a&&r.push({variableName:a,offsetInSQL:i.index,span:n})}return r}parseNamedArg(){const t=this.currentSpan(),n=this.current();n.type===y.Identifier||this.isKeywordUsableAsArgName(n.type)?this.advance():(this.error(`Expected argument name, got '${n.value}'.`),this.advance()),this.expect(y.Equals);const r=this.parseExpression();return{kind:Q.NamedArg,name:n.value,value:r,span:this.makeSpan(t,this.previousSpan())}}isKeywordUsableAsArgName(t){return t===y.ParamKeyword||t===y.FromKeyword||t===y.LayoutKeyword||t===y.RowKeyword||t===y.UseKeyword||t===y.ImportKeyword||t===y.MetricKeyword||t===y.MetricsKeyword||t===y.TermsKeyword||t===y.IncludesKeyword}parseVariableDecl(){const t=this.currentSpan();this.expect(y.LetKeyword);const n=this.expect(y.Identifier);this.expect(y.Equals);const r=this.parseExpression();return{kind:Q.VariableDecl,name:n.value,initializer:r,span:this.makeSpan(t,this.previousSpan())}}parseDecoratorList(){const t=[];for(;this.check(y.AtSign);)t.push(this.parseDecorator());return t}parseDecorator(){const t=this.currentSpan();this.expect(y.AtSign);const n=this.expect(y.Identifier),r=[];if(this.check(y.LeftParen)){if(this.advance(),!this.check(y.RightParen))for(r.push(this.parseExpression());this.check(y.Comma);)this.advance(),r.push(this.parseExpression());this.expect(y.RightParen)}return{kind:Q.Decorator,name:n.value,arguments:r,span:this.makeSpan(t,this.previousSpan())}}parseExpression(){let t=this.parsePrimary();for(;this.check(y.Plus)||this.check(y.Minus);){const n=this.advance(),r=this.parsePrimary();t={kind:Q.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(y.StringLiteral))return this.advance(),{kind:Q.StringLiteral,value:t.value,span:t.span};if(this.check(y.NumberLiteral))return this.advance(),{kind:Q.NumberLiteral,value:Number(t.value),span:t.span};if(this.check(y.BooleanLiteral))return this.advance(),{kind:Q.BooleanLiteral,value:t.value==="true",span:t.span};if(this.check(y.LeftBracket))return this.parseArrayLiteral();if(this.check(y.IntervalKeyword)){const n=this.currentSpan();this.advance();const r=this.expect(y.StringLiteral);return{kind:Q.IntervalExpr,value:r.value,span:this.makeSpan(n,this.previousSpan())}}if(this.check(y.Identifier)){this.advance();const n=t.value;return this.check(y.LeftParen)?this.parseFunctionCall(n,t.span):{kind:Q.Identifier,name:n,span:t.span}}if(this.check(y.Minus)){const n=this.currentSpan();this.advance();const r=this.expect(y.NumberLiteral);return{kind:Q.NumberLiteral,value:-Number(r.value),span:this.makeSpan(n,r.span)}}return this.error(`Unexpected token '${t.value}'. Expected an expression.`),this.advance(),{kind:Q.Identifier,name:"__error__",span:t.span}}parseArrayLiteral(){const t=this.currentSpan();this.expect(y.LeftBracket);const n=[];if(!this.check(y.RightBracket))for(n.push(this.parseExpression());this.check(y.Comma)&&(this.advance(),!this.check(y.RightBracket));)n.push(this.parseExpression());return this.expect(y.RightBracket),{kind:Q.ArrayLiteral,elements:n,span:this.makeSpan(t,this.previousSpan())}}parseFunctionCall(t,n){this.expect(y.LeftParen);const r=[];if(!this.check(y.RightParen))for(r.push(this.parseExpression());this.check(y.Comma);)this.advance(),r.push(this.parseExpression());return this.expect(y.RightParen),{kind:Q.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(y.LeftBrace))return;let t=0;for(;!this.isAtEnd();){if(this.check(y.LeftBrace)){t+=1,this.advance();continue}if(this.check(y.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(y.StringLiteral)||this.check(y.TripleQuoteString)?this.advance():this.expect(y.StringLiteral)}isAtEnd(){return this.current().type===y.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(y.DomainKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);let o,i,a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P;for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.OwnerKeyword))this.advance(),this.expect(y.Equals),i=this.expect(y.StringLiteral).value;else if(this.check(y.DescriptionKeyword))this.advance(),this.expect(y.Equals),S=this.expectStringLike().value;else if(this.check(y.TagsKeyword))this.advance(),this.expect(y.Equals),f=this.parseStringArrayValues();else if(this.check(y.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 A=this.advance();this.expect(y.Equals),A.value==="id"?o=this.expect(y.StringLiteral).value:A.value==="parent"?a=this.expect(y.StringLiteral).value:A.value==="businessOwner"?c=this.expect(y.StringLiteral).value:A.value==="boundedContext"?l=this.expectStringLike().value:A.value==="sourceSystems"?u=this.parseStringArrayValues():A.value==="primaryTerms"?h=this.parseStringArrayValues():A.value==="reviewCadence"?d=this.expect(y.StringLiteral).value:A.value==="businessOutcome"?m=this.expect(y.StringLiteral).value:A.value==="inScope"?v=this.parseStringArrayValues():A.value==="outOfScope"?b=this.parseStringArrayValues():A.value==="dbtGroups"?w=this.parseStringArrayValues():A.value==="dbtPaths"?j=this.parseStringArrayValues():A.value==="dbtTags"?C=this.parseStringArrayValues():A.value==="semanticDomains"?x=this.parseStringArrayValues():A.value==="semanticTags"?E=this.parseStringArrayValues():A.value==="exports"&&(P=this.parseStringArrayValues())}else{if(this.check(y.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(y.RightBrace),{kind:Q.DomainDecl,name:r.value,id:o,parent:a,owner:i,businessOwner:c,boundedContext:l,sourceSystems:u,primaryTerms:h,reviewCadence:d,tags:f,businessOutcome:m,description:S,inScope:v,outOfScope:b,dbtGroups:w,dbtPaths:j,dbtTags:C,semanticDomains:x,semanticTags:E,exports:P,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseTermDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.TermKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);let o,i,a,c,l,u,h,d,f,m,S,v,b,w,j;for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.DomainKeyword))this.advance(),this.expect(y.Equals),o=this.expect(y.StringLiteral).value;else if(this.check(y.TypeKeyword))this.advance(),this.expect(y.Equals),i=this.expect(y.StringLiteral).value;else if(this.check(y.DescriptionKeyword))this.advance(),this.expect(y.Equals),c=this.expectStringLike().value;else if(this.check(y.TagsKeyword))this.advance(),this.expect(y.Equals),l=this.parseStringArrayValues();else if(this.check(y.OwnerKeyword))this.advance(),this.expect(y.Equals),u=this.expect(y.StringLiteral).value;else if(this.check(y.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 C=this.advance();this.expect(y.Equals),C.value==="status"?a=this.expect(y.StringLiteral).value:C.value==="identifiers"?h=this.parseStringArrayValues():C.value==="synonyms"?d=this.parseStringArrayValues():C.value==="metricRefs"?f=this.parseStringArrayValues():C.value==="businessOutcome"?m=this.expect(y.StringLiteral).value:C.value==="businessOwner"?S=this.expect(y.StringLiteral).value:C.value==="decisionUse"?v=this.expect(y.StringLiteral).value:C.value==="reviewCadence"?b=this.expect(y.StringLiteral).value:C.value==="businessRules"?w=this.parseStringArrayValues():C.value==="caveats"&&(j=this.parseStringArrayValues())}else{if(this.check(y.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(y.RightBrace),{kind:Q.TermDecl,name:r.value,domain:o,termType:i,status:a,description:c,tags:l,owner:u,identifiers:h,synonyms:d,metricRefs:f,businessOutcome:m,businessOwner:S,decisionUse:v,reviewCadence:b,businessRules:w,caveats:j,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseBusinessViewDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.BusinessViewKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);let o,i,a,c,l,u,h,d,f,m,S,v,b=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.DomainKeyword))this.advance(),this.expect(y.Equals),o=this.expect(y.StringLiteral).value;else if(this.check(y.DescriptionKeyword))this.advance(),this.expect(y.Equals),a=this.expectStringLike().value;else if(this.check(y.TagsKeyword))this.advance(),this.expect(y.Equals),c=this.parseStringArrayValues();else if(this.check(y.OwnerKeyword))this.advance(),this.expect(y.Equals),l=this.expect(y.StringLiteral).value;else if(this.check(y.TermsKeyword))this.advance(),this.expect(y.Equals),u=this.parseStringArrayValues();else if(this.check(y.IncludesKeyword))b=this.parseBusinessViewIncludes();else if(this.check(y.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 w=this.advance();this.expect(y.Equals),w.value==="status"?i=this.expect(y.StringLiteral).value:w.value==="businessOutcome"?h=this.expect(y.StringLiteral).value:w.value==="businessOwner"?d=this.expect(y.StringLiteral).value:w.value==="decisionUse"?f=this.expect(y.StringLiteral).value:w.value==="reviewCadence"?m=this.expect(y.StringLiteral).value:w.value==="businessRules"?S=this.parseStringArrayValues():w.value==="caveats"&&(v=this.parseStringArrayValues())}else{if(this.check(y.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(y.RightBrace),{kind:Q.BusinessViewDecl,name:r.value,domain:o,status:i,description:a,tags:c,owner:l,termRefs:u,businessOutcome:h,businessOwner:d,decisionUse:f,reviewCadence:m,businessRules:S,caveats:v,includes:b,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseBusinessViewIncludes(){this.expect(y.IncludesKeyword),this.expect(y.LeftBrace);const t=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan();if(this.check(y.BlockKeyword)){this.advance();const r=this.expect(y.StringLiteral);t.push({kind:Q.BusinessViewInclude,refType:"block",name:r.value,span:this.makeSpan(n,this.previousSpan())})}else if(this.check(y.BusinessViewKeyword)){this.advance();const r=this.expect(y.StringLiteral);t.push({kind:Q.BusinessViewInclude,refType:"business_view",name:r.value,span:this.makeSpan(n,this.previousSpan())})}else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside includes. Expected 'block', 'business_view', or '}'.`),this.advance()}}return this.expect(y.RightBrace),t}parseStringArrayValues(){const t=this.parseArrayLiteral();return t.kind!==Q.ArrayLiteral?[]:t.elements.filter(n=>n.kind===Q.StringLiteral).map(n=>n.value)}parseBlockDecl(t){var nn;const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.BlockKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);let o,i,a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P,A,g,I,T,O,_,M,q,G,J,H,L,$,X,W,te,F,K,oe,ee,ce,ke,xe,De,We,Be,Ee,ge,Je,tt,Fe,Ke,bt,Mt,jt,Et,en,tn,Tn,An,U,se,je,ve,me;for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.DomainKeyword))this.advance(),this.expect(y.Equals),o=this.expect(y.StringLiteral).value;else if(this.check(y.TypeKeyword)){this.advance(),this.expect(y.Equals);const Y=this.expect(y.StringLiteral).value;Y==="semantic"||Y==="custom"?i=Y:(this.error(`Block type must be "semantic" or "custom", got "${Y}". Use type = "semantic" for dbt metric blocks or type = "custom" for SQL blocks.`),i="custom")}else if(this.check(y.MetricKeyword))this.advance(),this.expect(y.Equals),a=this.expect(y.StringLiteral).value;else if(this.check(y.MetricsKeyword)){this.advance(),this.expect(y.Equals);const ie=this.parseArrayLiteral();ie.kind===Q.ArrayLiteral&&(c=ie.elements.filter(Y=>Y.kind===Q.StringLiteral).map(Y=>Y.value))}else if(this.check(y.DimensionsKeyword)){this.advance(),this.expect(y.Equals);const ie=this.parseArrayLiteral();ie.kind===Q.ArrayLiteral&&(l=ie.elements.filter(Y=>Y.kind===Q.StringLiteral).map(Y=>Y.value))}else if(this.check(y.DescriptionKeyword))this.advance(),this.expect(y.Equals),u=this.expectStringLike().value;else if(this.check(y.TagsKeyword)){this.advance(),this.expect(y.Equals);const ie=this.parseArrayLiteral();ie.kind===Q.ArrayLiteral&&(h=ie.elements.filter(Y=>Y.kind===Q.StringLiteral).map(Y=>Y.value))}else if(this.check(y.OwnerKeyword))this.advance(),this.expect(y.Equals),d=this.expect(y.StringLiteral).value;else if(this.check(y.TermsKeyword))this.advance(),this.expect(y.Equals),f=this.parseStringArrayValues();else if(this.check(y.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 ie=this.advance();this.expect(y.Equals),ie.value==="pattern"?m=this.expect(y.StringLiteral).value:ie.value==="grain"?S=this.expect(y.StringLiteral).value:ie.value==="entities"?v=this.parseStringArrayValues():ie.value==="outputs"?b=this.parseStringArrayValues():ie.value==="allowedFilters"?w=this.parseStringArrayValues():ie.value==="sourceSystems"?x=this.parseStringArrayValues():ie.value==="replacementFor"&&(E=this.parseStringArrayValues())}else if(this.check(y.ParamsKeyword))P=this.parseBlockParams();else if(this.check(y.Identifier)&&this.current().value==="parameterPolicy")j=this.parseBlockParameterPolicy();else if(this.check(y.Identifier)&&this.current().value==="filterBindings")C=this.parseBlockFilterBindings();else if(this.check(y.QueryKeyword))if(this.advance(),this.check(y.LeftBrace))A=this.parseLegacyBlockQuerySection();else if(this.expect(y.Equals),this.check(y.TripleQuoteString)){const ie=this.advance(),Y=this.extractInterpolations(ie.value,ie.span);A={kind:Q.SQLQuery,rawSQL:ie.value,interpolations:Y,span:ie.span}}else A=this.parseSQLQuery();else if(this.check(y.VisualizationKeyword))g=this.parseBlockVisualization();else if(this.check(y.TestsKeyword))I=this.parseBlockTests();else{if(this.check(y.RightBrace))break;if(this.check(y.Identifier)&&this.current().value==="status")this.advance(),this.expect(y.Equals),$=this.expect(y.StringLiteral).value;else if(this.check(y.Identifier)&&this.current().value==="datalex_contract")this.advance(),this.expect(y.Equals),X=this.expect(y.StringLiteral).value;else if(this.check(y.Identifier)&&(this.current().value==="asked_times"||this.current().value==="limit"||this.current().value==="source_dql_limit")){const ie=this.advance();this.expect(y.Equals);const Y=this.expect(y.NumberLiteral);ie.value==="asked_times"?W=Number(Y.value):ie.value==="limit"?Tn=Number(Y.value):ve=Number(Y.value)}else if(this.check(y.Identifier)&&f0(this.current().value)){const ie=this.advance();this.expect(y.Equals);const Y=this.expect(y.StringLiteral);switch(ie.value){case"first_asked":te=Y.value;break;case"last_asked":F=Y.value;break;case"proposed_contract_id":K=Y.value;break;case"proposed_domain":oe=Y.value;break;case"proposed_entity":ee=Y.value;break;case"source_question":ce=Y.value;break;case"source_block":ke=Y.value;break;case"source_dql_kind":xe=Y.value;break;case"source_dql_name":De=Y.value;break;case"source_dql_path":We=Y.value;break;case"source_dql_hash":Be=Y.value;break;case"source_dql_time_dimension":Ee=Y.value;break;case"source_dql_granularity":ge=Y.value;break;case"followup_kind":Je=Y.value;break;case"context_pack_id":tt=Y.value;break;case"route_intent":Fe=Y.value;break;case"time_dimension":Ke=Y.value;break;case"granularity":bt=Y.value;break;case"draft_path":Mt=Y.value;break}}else if(this.check(y.Identifier)&&h0(this.current().value)){const ie=this.advance();this.expect(y.Equals);const Y=this.parseStringArrayValues();switch(ie.value){case"upstream_refs":jt=Y;break;case"requested_filters":Et=Y;break;case"requested_dimensions":en=Y;break;case"order_by":tn=Y;break;case"source_dql_metrics":An=Y;break;case"source_dql_dimensions":U=Y;break;case"source_dql_filters":se=Y;break;case"source_dql_order_by":je=Y;break;case"validation_warnings":me=Y;break}}else if(this.check(y.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 ie=this.advance();if(this.expect(y.Equals),ie.value==="llmContext")T=this.expect(y.StringLiteral).value;else if(ie.value==="invariants"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(O=Y.elements.filter($e=>$e.kind===Q.StringLiteral).map($e=>$e.value))}else if(ie.value==="examples"){this.expect(y.LeftBracket);const Y=[];for(;!this.check(y.RightBracket)&&!this.isAtEnd();){this.expect(y.LeftBrace);let $e,Yn;for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const Xn=this.current();if(Xn.type!==y.Identifier){this.error(`Expected 'question' or 'sql' in example entry, got '${Xn.value}'.`),this.advance();continue}this.advance(),this.expect(y.Equals);const Ro=this.expect(y.StringLiteral);Xn.value==="question"?$e=Ro.value:Xn.value==="sql"&&(Yn=Ro.value),this.check(y.Comma)&&this.advance()}this.expect(y.RightBrace),$e&&Y.push(Yn?{question:$e,sql:Yn}:{question:$e}),this.check(y.Comma)&&this.advance()}this.expect(y.RightBracket),Y.length>0&&(_=Y)}else if(ie.value==="businessOutcome")M=this.expect(y.StringLiteral).value;else if(ie.value==="businessOwner")q=this.expect(y.StringLiteral).value;else if(ie.value==="decisionUse")G=this.expect(y.StringLiteral).value;else if(ie.value==="reviewCadence")J=this.expect(y.StringLiteral).value;else if(ie.value==="businessRules"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(H=Y.elements.filter($e=>$e.kind===Q.StringLiteral).map($e=>$e.value))}else if(ie.value==="caveats"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(L=Y.elements.filter($e=>$e.kind===Q.StringLiteral).map($e=>$e.value))}}else{if(this.check(y.Identifier)&&((nn=this.tokens[this.pos+1])==null?void 0:nn.type)===y.LeftBrace){const ie=this.current().value;this.error(`Unexpected nested section '${ie}' 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(y.RightBrace),{kind:Q.BlockDecl,name:r.value,domain:o,blockType:i,metricRef:a,metricsRef:c,dimensionsRef:i==="semantic"?l:void 0,description:u,tags:h,owner:d,termRefs:f,pattern:m,grain:S,entities:v,outputs:b,dimensions:i==="semantic"?void 0:l,allowedFilters:w,parameterPolicy:j,filterBindings:C,sourceSystems:x,replacementFor:E,params:P,query:A,visualization:g,tests:I,decorators:t,llmContext:T,invariants:O,examples:_,businessOutcome:M,businessOwner:q,decisionUse:G,reviewCadence:J,businessRules:H,caveats:L,status:$,datalexContract:X,askedTimes:W,firstAsked:te,lastAsked:F,proposedContractId:K,proposedDomain:oe,proposedEntity:ee,sourceQuestion:ce,sourceBlock:ke,sourceDqlKind:xe,sourceDqlName:De,sourceDqlPath:We,sourceDqlHash:Be,sourceDqlTimeDimension:Ee,sourceDqlGranularity:ge,followupKind:Je,contextPackId:tt,routeIntent:Fe,timeDimension:Ke,granularity:bt,draftPath:Mt,upstreamRefs:jt,requestedFilters:Et,requestedDimensions:en,orderBy:tn,limit:Tn,sourceDqlMetrics:An,sourceDqlDimensions:U,sourceDqlFilters:se,sourceDqlOrderBy:je,sourceDqlLimit:ve,validationWarnings:me,span:this.makeSpan(n,this.previousSpan())}}parseLegacyBlockQuerySection(){const t=this.currentSpan();this.expect(y.LeftBrace);let n;for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.Identifier)&&this.current().value==="sql")if(this.advance(),this.expect(y.Equals),this.check(y.TripleQuoteString)){const r=this.advance(),o=this.extractInterpolations(r.value,r.span);n={kind:Q.SQLQuery,rawSQL:r.value,interpolations:o,span:r.span}}else n=this.parseSQLQuery();else this.check(y.Identifier)&&d0.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(y.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(y.ParamsKeyword),this.expect(y.LeftBrace);const n=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const o=this.currentSpan(),i=this.current();if(i.type===y.Identifier||this.isBlockFieldKeyword(i.type))this.advance();else{this.error(`Expected parameter name, got '${i.value}'.`),this.advance();continue}let a;if(this.check(y.ColonToken)){this.advance();let u=this.expect(y.Identifier).value;this.check(y.LeftBracket)&&((r=this.tokens[this.pos+1])==null?void 0:r.type)===y.RightBracket&&(this.advance(),this.advance(),u+="[]");const h=["string","number","boolean","date","string[]","number[]","date[]"];h.includes(u)?a=u:this.error(`Invalid block parameter type '${u}'. Valid types: ${h.join(", ")}`)}let c;this.check(y.Equals)&&(this.advance(),c=this.parseExpression()),n.push({name:i.value,paramType:a,initializer:c,span:this.makeSpan(o,this.previousSpan())})}return this.expect(y.RightBrace),{kind:Q.BlockParams,params:n,span:this.makeSpan(t,this.previousSpan())}}parseBlockParameterPolicy(){const t=[];for(this.expect(y.Identifier),this.expect(y.LeftBrace);!this.check(y.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan(),r=this.current();if(r.type===y.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected parameter name inside parameterPolicy, got '${r.value}'.`),this.advance();continue}this.expect(y.Equals);const o=this.expectStringLike();t.push({name:r.value,policy:o.value,span:this.makeSpan(n,this.previousSpan())})}return this.expect(y.RightBrace),t}parseBlockFilterBindings(){const t=[];for(this.expect(y.Identifier),this.expect(y.LeftBrace);!this.check(y.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan(),r=this.current();if(r.type===y.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected business filter name inside filterBindings, got '${r.value}'.`),this.advance();continue}this.expect(y.Equals);const o=this.expectStringLike();t.push({filter:r.value,binding:o.value,span:this.makeSpan(n,this.previousSpan())})}return this.expect(y.RightBrace),t}parseBlockVisualization(){const t=this.currentSpan();this.expect(y.VisualizationKeyword),this.expect(y.LeftBrace);const n=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const r=this.currentSpan(),o=this.current();if(o.type===y.Identifier||this.isBlockFieldKeyword(o.type))this.advance();else{this.error(`Expected property name, got '${o.value}'.`),this.advance();continue}this.expect(y.Equals);const i=this.parseExpression();n.push({kind:Q.NamedArg,name:o.value,value:i,span:this.makeSpan(r,this.previousSpan())})}return this.expect(y.RightBrace),{kind:Q.BlockVisualization,properties:n,span:this.makeSpan(t,this.previousSpan())}}parseBlockTests(){this.currentSpan(),this.expect(y.TestsKeyword),this.expect(y.LeftBrace);const t=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.AssertKeyword)){const n=this.currentSpan();this.advance();const r=this.current();if(r.type===y.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(y.GreaterThan))this.advance(),o=">";else if(this.check(y.LessThan))this.advance(),o="<";else if(this.check(y.GreaterThanOrEqual))this.advance(),o=">=";else if(this.check(y.LessThanOrEqual))this.advance(),o="<=";else if(this.check(y.DoubleEquals))this.advance(),o="==";else if(this.check(y.NotEquals))this.advance(),o="!=";else if(this.check(y.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:Q.BlockTest,field:r.value,operator:o,expected:i,span:this.makeSpan(n,this.previousSpan())})}else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside tests. Expected 'assert' or '}'.`),this.advance()}return this.expect(y.RightBrace),t}isBlockFieldKeyword(t){return t===y.DomainKeyword||t===y.TypeKeyword||t===y.MetricKeyword||t===y.DescriptionKeyword||t===y.TagsKeyword||t===y.OwnerKeyword||t===y.TermsKeyword||t===y.ChartKeyword||t===y.QueryKeyword||t===y.DefaultKeyword||t===y.FromKeyword}parseWorkbook(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.WorkbookKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);const o=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.PageKeyword))o.push(this.parsePage());else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside workbook. Expected 'page' or '}'.`),this.advance()}return this.expect(y.RightBrace),{kind:Q.Workbook,title:r.value,decorators:t,pages:o,span:this.makeSpan(n,this.previousSpan())}}parsePage(){const t=this.currentSpan();this.expect(y.PageKeyword);const n=this.expect(y.StringLiteral);this.expect(y.LeftBrace);const r=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const o=this.parseDecoratorList();if(this.check(y.LetKeyword))o.length>0&&this.error("Decorators cannot be applied to variable declarations."),r.push(this.parseVariableDecl());else if(this.check(y.ParamKeyword))o.length>0&&this.error("Decorators cannot be applied to param declarations."),r.push(this.parseParamDecl());else if(this.check(y.ChartKeyword))r.push(this.parseChartCall(o));else if(this.check(y.FilterKeyword))o.length>0&&this.error("Decorators cannot be applied to filter declarations."),r.push(this.parseFilterCall());else if(this.check(y.UseKeyword))o.length>0&&this.error("Decorators cannot be applied to use declarations."),r.push(this.parseUseDecl());else if(this.check(y.LayoutKeyword))o.length>0&&this.error("Decorators cannot be applied to layout blocks."),r.push(this.parseLayoutBlock());else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside page. Expected 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(y.RightBrace),{kind:Q.Page,title:n.value,body:r,span:this.makeSpan(t,this.previousSpan())}}parseParamDecl(){const t=this.currentSpan();this.expect(y.ParamKeyword);const n=this.expect(y.Identifier);let r="string";if(this.check(y.ColonToken)){this.advance();const i=this.expect(y.Identifier),a=["string","number","boolean","date"];a.includes(i.value)?r=i.value:this.reporter.error(`Invalid param type '${i.value}'. Valid types: ${a.join(", ")}`,i.span)}let o;return this.check(y.Equals)&&(this.advance(),o=this.parseExpression()),{kind:Q.ParamDecl,name:n.value,paramType:r,defaultValue:o,span:this.makeSpan(t,this.previousSpan())}}parseImportDecl(){const t=this.currentSpan();this.expect(y.ImportKeyword),this.expect(y.LeftBrace);const n=[];if(!this.check(y.RightBrace))for(n.push(this.expect(y.Identifier).value);this.check(y.Comma)&&(this.advance(),!this.check(y.RightBrace));)n.push(this.expect(y.Identifier).value);this.expect(y.RightBrace),this.expect(y.FromKeyword);const r=this.expect(y.StringLiteral);return{kind:Q.ImportDecl,names:n,path:r.value,span:this.makeSpan(t,this.previousSpan())}}parseUseDecl(){const t=this.currentSpan();this.expect(y.UseKeyword);let n;return this.check(y.Identifier)||this.check(y.StringLiteral)?n=this.advance():n=this.expect(y.Identifier),{kind:Q.UseDecl,name:n.value,span:this.makeSpan(t,this.previousSpan())}}parseLayoutBlock(){const t=this.currentSpan();this.expect(y.LayoutKeyword);let n=12;if(this.check(y.LeftParen)){this.advance();const o=[];if(!this.check(y.RightParen))for(o.push(this.parseNamedArg());this.check(y.Comma)&&(this.advance(),!this.check(y.RightParen));)o.push(this.parseNamedArg());this.expect(y.RightParen);const i=o.find(a=>a.name==="columns");i&&i.value.kind===Q.NumberLiteral&&(n=i.value.value)}this.expect(y.LeftBrace);const r=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.RowKeyword))r.push(this.parseLayoutRow());else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside layout. Expected 'row' or '}'.`),this.advance()}return this.expect(y.RightBrace),{kind:Q.LayoutBlock,columns:n,rows:r,span:this.makeSpan(t,this.previousSpan())}}parseLayoutRow(){const t=this.currentSpan();this.expect(y.RowKeyword),this.expect(y.LeftBrace);const n=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const r=this.parseDecoratorList();let o;if(this.check(y.ChartKeyword))o=this.parseChartCall(r);else if(this.check(y.FilterKeyword))r.length>0&&this.error("Decorators cannot be applied to filter declarations."),o=this.parseFilterCall();else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside row. Expected 'chart', 'filter', or '}'.`),this.advance();continue}let i;if(this.check(y.Identifier)&&this.current().value==="span"){this.advance();const a=this.expect(y.NumberLiteral);i=Number(a.value)}n.push({node:o,span:i})}return this.expect(y.RightBrace),{kind:Q.LayoutRow,items:n,span:this.makeSpan(t,this.previousSpan())}}synchronize(){for(;!this.isAtEnd();){const t=this.current();if(t.type===y.DashboardKeyword||t.type===y.WorkbookKeyword||t.type===y.ChartKeyword||t.type===y.FilterKeyword||t.type===y.ImportKeyword||t.type===y.BlockKeyword||t.type===y.TermKeyword||t.type===y.BusinessViewKeyword||t.type===y.AtSign||t.type===y.RightBrace)return;this.advance()}}}function g0(e,t){return new m0(e,t).parse()}function y0(e,t={}){const n=g0(e);return b0(n,t)}function b0(e,t={}){const n={indentUnit:t.indent??" "},r=e.statements.map(o=>x0(o,0,n)).join(`
411
+ `&&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(y.TripleQuoteString,n,t);n+=this.advance()}return this.makeToken(y.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 p0=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"]),f0=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 h0(e){return p0.has(e)}function m0(e){return f0.has(e)}class g0{constructor(t,n){Pe(this,"tokens");Pe(this,"pos",0);Pe(this,"source");Pe(this,"file");Pe(this,"reporter");this.source=t,this.file=n,this.reporter=new o0;const r=new hs(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 i0(`Parse errors in ${this.file??"<input>"}`,this.reporter.getErrors());return{kind:Q.Program,statements:n,span:this.makeSpan(t,this.currentSpan())}}parseStatement(){const t=this.parseDecoratorList();return this.check(y.WorkbookKeyword)?this.parseWorkbook(t):this.check(y.DashboardKeyword)?this.parseDashboard(t):this.check(y.DigestKeyword)?this.parseDigest(t):this.check(y.ChartKeyword)?this.parseChartCall(t):this.check(y.BlockKeyword)?this.parseBlockDecl(t):this.check(y.DomainKeyword)?this.parseDomainDecl(t):this.check(y.TermKeyword)?this.parseTermDecl(t):this.check(y.BusinessViewKeyword)?this.parseBusinessViewDecl(t):this.check(y.ImportKeyword)?(t.length>0&&this.error("Decorators cannot be applied to import statements."),this.parseImportDecl()):(this.check(y.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(y.FilterKeyword),this.expect(y.Dot);const n=this.expect(y.Identifier);Zs.has(n.value)||this.reporter.error(`Unknown filter type '${n.value}'. Valid types: ${[...Zs].join(", ")}`,n.span,`Did you mean one of: ${[...Zs].join(", ")}?`),this.expect(y.LeftParen);let r;const i=this.current().value.toUpperCase();(i==="SELECT"||i==="WITH")&&(r=this.parseSQLQuery());const a=[];for(;(this.check(y.Comma)||!r&&(this.check(y.Identifier)||this.isKeywordUsableAsArgName(this.current().type)))&&(this.check(y.Comma)&&this.advance(),!this.check(y.RightParen));)a.push(this.parseNamedArg());return this.expect(y.RightParen),{kind:Q.FilterCall,filterType:n.value,query:r,args:a,span:this.makeSpan(t,this.previousSpan())}}parseDashboard(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.DashboardKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);const o=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const i=this.parseDecoratorList();if(this.check(y.LetKeyword))i.length>0&&this.error("Decorators cannot be applied to variable declarations."),o.push(this.parseVariableDecl());else if(this.check(y.ParamKeyword))i.length>0&&this.error("Decorators cannot be applied to param declarations."),o.push(this.parseParamDecl());else if(this.check(y.ChartKeyword))o.push(this.parseChartCall(i));else if(this.check(y.FilterKeyword))i.length>0&&this.error("Decorators cannot be applied to filter declarations."),o.push(this.parseFilterCall());else if(this.check(y.UseKeyword))i.length>0&&this.error("Decorators cannot be applied to use declarations."),o.push(this.parseUseDecl());else if(this.check(y.LayoutKeyword))i.length>0&&this.error("Decorators cannot be applied to layout blocks."),o.push(this.parseLayoutBlock());else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside dashboard. Expected 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(y.RightBrace),{kind:Q.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(y.DigestKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);const o=[];let i;for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const a=this.parseDecoratorList();if(this.check(y.NarrativeKeyword))a.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(y.LetKeyword))a.length>0&&this.error("Decorators cannot be applied to variable declarations."),o.push(this.parseVariableDecl());else if(this.check(y.ParamKeyword))a.length>0&&this.error("Decorators cannot be applied to param declarations."),o.push(this.parseParamDecl());else if(this.check(y.ChartKeyword))o.push(this.parseChartCall(a));else if(this.check(y.FilterKeyword))a.length>0&&this.error("Decorators cannot be applied to filter declarations."),o.push(this.parseFilterCall());else if(this.check(y.UseKeyword))a.length>0&&this.error("Decorators cannot be applied to use declarations."),o.push(this.parseUseDecl());else if(this.check(y.LayoutKeyword))a.length>0&&this.error("Decorators cannot be applied to layout blocks."),o.push(this.parseLayoutBlock());else{if(this.check(y.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(y.RightBrace),{kind:Q.Digest,title:r.value,decorators:t,narrative:i,body:o,span:this.makeSpan(n,this.previousSpan())}}parseNarrative(){const t=this.currentSpan();this.expect(y.NarrativeKeyword),this.expect(y.LeftBrace);const n=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)n.push(this.parseNamedArg());return this.expect(y.RightBrace),{kind:Q.Narrative,properties:n,span:this.makeSpan(t,this.previousSpan())}}parseChartCall(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.ChartKeyword),this.expect(y.Dot);const r=this.currentSpan();let i=this.expect(y.Identifier).value;for(;this.check(y.Minus);)this.advance(),i+=`-${this.expect(y.Identifier).value}`;const a=this.makeSpan(r,this.previousSpan());Xs.has(i)||this.reporter.error(`Unknown chart type '${i}'. Valid types: ${[...Xs].join(", ")}`,a,`Did you mean one of: ${[...Xs].join(", ")}?`);const c=d0(i);this.expect(y.LeftParen);const l=this.parseSQLQuery(),u=[];for(;this.check(y.Comma)&&(this.advance(),!this.check(y.RightParen));)u.push(this.parseNamedArg());return this.expect(y.RightParen),{kind:Q.ChartCall,chartType:c,query:l,args:u,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseSQLQuery(){const t=this.currentSpan(),r=this.current().span.start.offset,{sql:o,endOffset:i}=hs.scanSQLBoundary(this.source,r,1),a=this.extractInterpolations(o,t);for(;!this.isAtEnd()&&this.current().span.start.offset<i;)this.advance();const c=this.makeSpan(t,this.currentSpan());return{kind:Q.SQLQuery,rawSQL:o,interpolations:a,span:c}}extractInterpolations(t,n){const r=[],o=/\$\{(\w+)\}|\{(\w+)\}/g;let i;for(;(i=o.exec(t))!==null;){const a=i[1]||i[2];a&&r.push({variableName:a,offsetInSQL:i.index,span:n})}return r}parseNamedArg(){const t=this.currentSpan(),n=this.current();n.type===y.Identifier||this.isKeywordUsableAsArgName(n.type)?this.advance():(this.error(`Expected argument name, got '${n.value}'.`),this.advance()),this.expect(y.Equals);const r=this.parseExpression();return{kind:Q.NamedArg,name:n.value,value:r,span:this.makeSpan(t,this.previousSpan())}}isKeywordUsableAsArgName(t){return t===y.ParamKeyword||t===y.FromKeyword||t===y.LayoutKeyword||t===y.RowKeyword||t===y.UseKeyword||t===y.ImportKeyword||t===y.MetricKeyword||t===y.MetricsKeyword||t===y.TermsKeyword||t===y.IncludesKeyword}parseVariableDecl(){const t=this.currentSpan();this.expect(y.LetKeyword);const n=this.expect(y.Identifier);this.expect(y.Equals);const r=this.parseExpression();return{kind:Q.VariableDecl,name:n.value,initializer:r,span:this.makeSpan(t,this.previousSpan())}}parseDecoratorList(){const t=[];for(;this.check(y.AtSign);)t.push(this.parseDecorator());return t}parseDecorator(){const t=this.currentSpan();this.expect(y.AtSign);const n=this.expect(y.Identifier),r=[];if(this.check(y.LeftParen)){if(this.advance(),!this.check(y.RightParen))for(r.push(this.parseExpression());this.check(y.Comma);)this.advance(),r.push(this.parseExpression());this.expect(y.RightParen)}return{kind:Q.Decorator,name:n.value,arguments:r,span:this.makeSpan(t,this.previousSpan())}}parseExpression(){let t=this.parsePrimary();for(;this.check(y.Plus)||this.check(y.Minus);){const n=this.advance(),r=this.parsePrimary();t={kind:Q.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(y.StringLiteral))return this.advance(),{kind:Q.StringLiteral,value:t.value,span:t.span};if(this.check(y.NumberLiteral))return this.advance(),{kind:Q.NumberLiteral,value:Number(t.value),span:t.span};if(this.check(y.BooleanLiteral))return this.advance(),{kind:Q.BooleanLiteral,value:t.value==="true",span:t.span};if(this.check(y.LeftBracket))return this.parseArrayLiteral();if(this.check(y.IntervalKeyword)){const n=this.currentSpan();this.advance();const r=this.expect(y.StringLiteral);return{kind:Q.IntervalExpr,value:r.value,span:this.makeSpan(n,this.previousSpan())}}if(this.check(y.Identifier)){this.advance();const n=t.value;return this.check(y.LeftParen)?this.parseFunctionCall(n,t.span):{kind:Q.Identifier,name:n,span:t.span}}if(this.check(y.Minus)){const n=this.currentSpan();this.advance();const r=this.expect(y.NumberLiteral);return{kind:Q.NumberLiteral,value:-Number(r.value),span:this.makeSpan(n,r.span)}}return this.error(`Unexpected token '${t.value}'. Expected an expression.`),this.advance(),{kind:Q.Identifier,name:"__error__",span:t.span}}parseArrayLiteral(){const t=this.currentSpan();this.expect(y.LeftBracket);const n=[];if(!this.check(y.RightBracket))for(n.push(this.parseExpression());this.check(y.Comma)&&(this.advance(),!this.check(y.RightBracket));)n.push(this.parseExpression());return this.expect(y.RightBracket),{kind:Q.ArrayLiteral,elements:n,span:this.makeSpan(t,this.previousSpan())}}parseFunctionCall(t,n){this.expect(y.LeftParen);const r=[];if(!this.check(y.RightParen))for(r.push(this.parseExpression());this.check(y.Comma);)this.advance(),r.push(this.parseExpression());return this.expect(y.RightParen),{kind:Q.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(y.LeftBrace))return;let t=0;for(;!this.isAtEnd();){if(this.check(y.LeftBrace)){t+=1,this.advance();continue}if(this.check(y.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(y.StringLiteral)||this.check(y.TripleQuoteString)?this.advance():this.expect(y.StringLiteral)}isAtEnd(){return this.current().type===y.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(y.DomainKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);let o,i,a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P;for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.OwnerKeyword))this.advance(),this.expect(y.Equals),i=this.expect(y.StringLiteral).value;else if(this.check(y.DescriptionKeyword))this.advance(),this.expect(y.Equals),S=this.expectStringLike().value;else if(this.check(y.TagsKeyword))this.advance(),this.expect(y.Equals),f=this.parseStringArrayValues();else if(this.check(y.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 A=this.advance();this.expect(y.Equals),A.value==="id"?o=this.expect(y.StringLiteral).value:A.value==="parent"?a=this.expect(y.StringLiteral).value:A.value==="businessOwner"?c=this.expect(y.StringLiteral).value:A.value==="boundedContext"?l=this.expectStringLike().value:A.value==="sourceSystems"?u=this.parseStringArrayValues():A.value==="primaryTerms"?h=this.parseStringArrayValues():A.value==="reviewCadence"?d=this.expect(y.StringLiteral).value:A.value==="businessOutcome"?m=this.expect(y.StringLiteral).value:A.value==="inScope"?v=this.parseStringArrayValues():A.value==="outOfScope"?b=this.parseStringArrayValues():A.value==="dbtGroups"?w=this.parseStringArrayValues():A.value==="dbtPaths"?j=this.parseStringArrayValues():A.value==="dbtTags"?C=this.parseStringArrayValues():A.value==="semanticDomains"?x=this.parseStringArrayValues():A.value==="semanticTags"?E=this.parseStringArrayValues():A.value==="exports"&&(P=this.parseStringArrayValues())}else{if(this.check(y.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(y.RightBrace),{kind:Q.DomainDecl,name:r.value,id:o,parent:a,owner:i,businessOwner:c,boundedContext:l,sourceSystems:u,primaryTerms:h,reviewCadence:d,tags:f,businessOutcome:m,description:S,inScope:v,outOfScope:b,dbtGroups:w,dbtPaths:j,dbtTags:C,semanticDomains:x,semanticTags:E,exports:P,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseTermDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.TermKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);let o,i,a,c,l,u,h,d,f,m,S,v,b,w,j;for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.DomainKeyword))this.advance(),this.expect(y.Equals),o=this.expect(y.StringLiteral).value;else if(this.check(y.TypeKeyword))this.advance(),this.expect(y.Equals),i=this.expect(y.StringLiteral).value;else if(this.check(y.DescriptionKeyword))this.advance(),this.expect(y.Equals),c=this.expectStringLike().value;else if(this.check(y.TagsKeyword))this.advance(),this.expect(y.Equals),l=this.parseStringArrayValues();else if(this.check(y.OwnerKeyword))this.advance(),this.expect(y.Equals),u=this.expect(y.StringLiteral).value;else if(this.check(y.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 C=this.advance();this.expect(y.Equals),C.value==="status"?a=this.expect(y.StringLiteral).value:C.value==="identifiers"?h=this.parseStringArrayValues():C.value==="synonyms"?d=this.parseStringArrayValues():C.value==="metricRefs"?f=this.parseStringArrayValues():C.value==="businessOutcome"?m=this.expect(y.StringLiteral).value:C.value==="businessOwner"?S=this.expect(y.StringLiteral).value:C.value==="decisionUse"?v=this.expect(y.StringLiteral).value:C.value==="reviewCadence"?b=this.expect(y.StringLiteral).value:C.value==="businessRules"?w=this.parseStringArrayValues():C.value==="caveats"&&(j=this.parseStringArrayValues())}else{if(this.check(y.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(y.RightBrace),{kind:Q.TermDecl,name:r.value,domain:o,termType:i,status:a,description:c,tags:l,owner:u,identifiers:h,synonyms:d,metricRefs:f,businessOutcome:m,businessOwner:S,decisionUse:v,reviewCadence:b,businessRules:w,caveats:j,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseBusinessViewDecl(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.BusinessViewKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);let o,i,a,c,l,u,h,d,f,m,S,v,b=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.DomainKeyword))this.advance(),this.expect(y.Equals),o=this.expect(y.StringLiteral).value;else if(this.check(y.DescriptionKeyword))this.advance(),this.expect(y.Equals),a=this.expectStringLike().value;else if(this.check(y.TagsKeyword))this.advance(),this.expect(y.Equals),c=this.parseStringArrayValues();else if(this.check(y.OwnerKeyword))this.advance(),this.expect(y.Equals),l=this.expect(y.StringLiteral).value;else if(this.check(y.TermsKeyword))this.advance(),this.expect(y.Equals),u=this.parseStringArrayValues();else if(this.check(y.IncludesKeyword))b=this.parseBusinessViewIncludes();else if(this.check(y.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 w=this.advance();this.expect(y.Equals),w.value==="status"?i=this.expect(y.StringLiteral).value:w.value==="businessOutcome"?h=this.expect(y.StringLiteral).value:w.value==="businessOwner"?d=this.expect(y.StringLiteral).value:w.value==="decisionUse"?f=this.expect(y.StringLiteral).value:w.value==="reviewCadence"?m=this.expect(y.StringLiteral).value:w.value==="businessRules"?S=this.parseStringArrayValues():w.value==="caveats"&&(v=this.parseStringArrayValues())}else{if(this.check(y.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(y.RightBrace),{kind:Q.BusinessViewDecl,name:r.value,domain:o,status:i,description:a,tags:c,owner:l,termRefs:u,businessOutcome:h,businessOwner:d,decisionUse:f,reviewCadence:m,businessRules:S,caveats:v,includes:b,decorators:t,span:this.makeSpan(n,this.previousSpan())}}parseBusinessViewIncludes(){this.expect(y.IncludesKeyword),this.expect(y.LeftBrace);const t=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan();if(this.check(y.BlockKeyword)){this.advance();const r=this.expect(y.StringLiteral);t.push({kind:Q.BusinessViewInclude,refType:"block",name:r.value,span:this.makeSpan(n,this.previousSpan())})}else if(this.check(y.BusinessViewKeyword)){this.advance();const r=this.expect(y.StringLiteral);t.push({kind:Q.BusinessViewInclude,refType:"business_view",name:r.value,span:this.makeSpan(n,this.previousSpan())})}else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside includes. Expected 'block', 'business_view', or '}'.`),this.advance()}}return this.expect(y.RightBrace),t}parseStringArrayValues(){const t=this.parseArrayLiteral();return t.kind!==Q.ArrayLiteral?[]:t.elements.filter(n=>n.kind===Q.StringLiteral).map(n=>n.value)}parseBlockDecl(t){var nn;const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.BlockKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);let o,i,a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P,A,g,I,T,O,_,M,q,G,J,H,L,$,X,W,te,F,K,oe,ee,ce,ke,xe,De,We,Be,Ee,ge,Je,tt,Fe,Ke,bt,Mt,jt,Et,en,tn,Tn,An,U,se,je,ve,me;for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.DomainKeyword))this.advance(),this.expect(y.Equals),o=this.expect(y.StringLiteral).value;else if(this.check(y.TypeKeyword)){this.advance(),this.expect(y.Equals);const Y=this.expect(y.StringLiteral).value;Y==="semantic"||Y==="custom"?i=Y:(this.error(`Block type must be "semantic" or "custom", got "${Y}". Use type = "semantic" for dbt metric blocks or type = "custom" for SQL blocks.`),i="custom")}else if(this.check(y.MetricKeyword))this.advance(),this.expect(y.Equals),a=this.expect(y.StringLiteral).value;else if(this.check(y.MetricsKeyword)){this.advance(),this.expect(y.Equals);const ie=this.parseArrayLiteral();ie.kind===Q.ArrayLiteral&&(c=ie.elements.filter(Y=>Y.kind===Q.StringLiteral).map(Y=>Y.value))}else if(this.check(y.DimensionsKeyword)){this.advance(),this.expect(y.Equals);const ie=this.parseArrayLiteral();ie.kind===Q.ArrayLiteral&&(l=ie.elements.filter(Y=>Y.kind===Q.StringLiteral).map(Y=>Y.value))}else if(this.check(y.DescriptionKeyword))this.advance(),this.expect(y.Equals),u=this.expectStringLike().value;else if(this.check(y.TagsKeyword)){this.advance(),this.expect(y.Equals);const ie=this.parseArrayLiteral();ie.kind===Q.ArrayLiteral&&(h=ie.elements.filter(Y=>Y.kind===Q.StringLiteral).map(Y=>Y.value))}else if(this.check(y.OwnerKeyword))this.advance(),this.expect(y.Equals),d=this.expect(y.StringLiteral).value;else if(this.check(y.TermsKeyword))this.advance(),this.expect(y.Equals),f=this.parseStringArrayValues();else if(this.check(y.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 ie=this.advance();this.expect(y.Equals),ie.value==="pattern"?m=this.expect(y.StringLiteral).value:ie.value==="grain"?S=this.expect(y.StringLiteral).value:ie.value==="entities"?v=this.parseStringArrayValues():ie.value==="outputs"?b=this.parseStringArrayValues():ie.value==="allowedFilters"?w=this.parseStringArrayValues():ie.value==="sourceSystems"?x=this.parseStringArrayValues():ie.value==="replacementFor"&&(E=this.parseStringArrayValues())}else if(this.check(y.ParamsKeyword))P=this.parseBlockParams();else if(this.check(y.Identifier)&&this.current().value==="parameterPolicy")j=this.parseBlockParameterPolicy();else if(this.check(y.Identifier)&&this.current().value==="filterBindings")C=this.parseBlockFilterBindings();else if(this.check(y.QueryKeyword))if(this.advance(),this.check(y.LeftBrace))A=this.parseLegacyBlockQuerySection();else if(this.expect(y.Equals),this.check(y.TripleQuoteString)){const ie=this.advance(),Y=this.extractInterpolations(ie.value,ie.span);A={kind:Q.SQLQuery,rawSQL:ie.value,interpolations:Y,span:ie.span}}else A=this.parseSQLQuery();else if(this.check(y.VisualizationKeyword))g=this.parseBlockVisualization();else if(this.check(y.TestsKeyword))I=this.parseBlockTests();else{if(this.check(y.RightBrace))break;if(this.check(y.Identifier)&&this.current().value==="status")this.advance(),this.expect(y.Equals),$=this.expect(y.StringLiteral).value;else if(this.check(y.Identifier)&&this.current().value==="datalex_contract")this.advance(),this.expect(y.Equals),X=this.expect(y.StringLiteral).value;else if(this.check(y.Identifier)&&(this.current().value==="asked_times"||this.current().value==="limit"||this.current().value==="source_dql_limit")){const ie=this.advance();this.expect(y.Equals);const Y=this.expect(y.NumberLiteral);ie.value==="asked_times"?W=Number(Y.value):ie.value==="limit"?Tn=Number(Y.value):ve=Number(Y.value)}else if(this.check(y.Identifier)&&h0(this.current().value)){const ie=this.advance();this.expect(y.Equals);const Y=this.expect(y.StringLiteral);switch(ie.value){case"first_asked":te=Y.value;break;case"last_asked":F=Y.value;break;case"proposed_contract_id":K=Y.value;break;case"proposed_domain":oe=Y.value;break;case"proposed_entity":ee=Y.value;break;case"source_question":ce=Y.value;break;case"source_block":ke=Y.value;break;case"source_dql_kind":xe=Y.value;break;case"source_dql_name":De=Y.value;break;case"source_dql_path":We=Y.value;break;case"source_dql_hash":Be=Y.value;break;case"source_dql_time_dimension":Ee=Y.value;break;case"source_dql_granularity":ge=Y.value;break;case"followup_kind":Je=Y.value;break;case"context_pack_id":tt=Y.value;break;case"route_intent":Fe=Y.value;break;case"time_dimension":Ke=Y.value;break;case"granularity":bt=Y.value;break;case"draft_path":Mt=Y.value;break}}else if(this.check(y.Identifier)&&m0(this.current().value)){const ie=this.advance();this.expect(y.Equals);const Y=this.parseStringArrayValues();switch(ie.value){case"upstream_refs":jt=Y;break;case"requested_filters":Et=Y;break;case"requested_dimensions":en=Y;break;case"order_by":tn=Y;break;case"source_dql_metrics":An=Y;break;case"source_dql_dimensions":U=Y;break;case"source_dql_filters":se=Y;break;case"source_dql_order_by":je=Y;break;case"validation_warnings":me=Y;break}}else if(this.check(y.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 ie=this.advance();if(this.expect(y.Equals),ie.value==="llmContext")T=this.expect(y.StringLiteral).value;else if(ie.value==="invariants"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(O=Y.elements.filter($e=>$e.kind===Q.StringLiteral).map($e=>$e.value))}else if(ie.value==="examples"){this.expect(y.LeftBracket);const Y=[];for(;!this.check(y.RightBracket)&&!this.isAtEnd();){this.expect(y.LeftBrace);let $e,Yn;for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const Xn=this.current();if(Xn.type!==y.Identifier){this.error(`Expected 'question' or 'sql' in example entry, got '${Xn.value}'.`),this.advance();continue}this.advance(),this.expect(y.Equals);const Ro=this.expect(y.StringLiteral);Xn.value==="question"?$e=Ro.value:Xn.value==="sql"&&(Yn=Ro.value),this.check(y.Comma)&&this.advance()}this.expect(y.RightBrace),$e&&Y.push(Yn?{question:$e,sql:Yn}:{question:$e}),this.check(y.Comma)&&this.advance()}this.expect(y.RightBracket),Y.length>0&&(_=Y)}else if(ie.value==="businessOutcome")M=this.expect(y.StringLiteral).value;else if(ie.value==="businessOwner")q=this.expect(y.StringLiteral).value;else if(ie.value==="decisionUse")G=this.expect(y.StringLiteral).value;else if(ie.value==="reviewCadence")J=this.expect(y.StringLiteral).value;else if(ie.value==="businessRules"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(H=Y.elements.filter($e=>$e.kind===Q.StringLiteral).map($e=>$e.value))}else if(ie.value==="caveats"){const Y=this.parseArrayLiteral();Y.kind===Q.ArrayLiteral&&(L=Y.elements.filter($e=>$e.kind===Q.StringLiteral).map($e=>$e.value))}}else{if(this.check(y.Identifier)&&((nn=this.tokens[this.pos+1])==null?void 0:nn.type)===y.LeftBrace){const ie=this.current().value;this.error(`Unexpected nested section '${ie}' 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(y.RightBrace),{kind:Q.BlockDecl,name:r.value,domain:o,blockType:i,metricRef:a,metricsRef:c,dimensionsRef:i==="semantic"?l:void 0,description:u,tags:h,owner:d,termRefs:f,pattern:m,grain:S,entities:v,outputs:b,dimensions:i==="semantic"?void 0:l,allowedFilters:w,parameterPolicy:j,filterBindings:C,sourceSystems:x,replacementFor:E,params:P,query:A,visualization:g,tests:I,decorators:t,llmContext:T,invariants:O,examples:_,businessOutcome:M,businessOwner:q,decisionUse:G,reviewCadence:J,businessRules:H,caveats:L,status:$,datalexContract:X,askedTimes:W,firstAsked:te,lastAsked:F,proposedContractId:K,proposedDomain:oe,proposedEntity:ee,sourceQuestion:ce,sourceBlock:ke,sourceDqlKind:xe,sourceDqlName:De,sourceDqlPath:We,sourceDqlHash:Be,sourceDqlTimeDimension:Ee,sourceDqlGranularity:ge,followupKind:Je,contextPackId:tt,routeIntent:Fe,timeDimension:Ke,granularity:bt,draftPath:Mt,upstreamRefs:jt,requestedFilters:Et,requestedDimensions:en,orderBy:tn,limit:Tn,sourceDqlMetrics:An,sourceDqlDimensions:U,sourceDqlFilters:se,sourceDqlOrderBy:je,sourceDqlLimit:ve,validationWarnings:me,span:this.makeSpan(n,this.previousSpan())}}parseLegacyBlockQuerySection(){const t=this.currentSpan();this.expect(y.LeftBrace);let n;for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.Identifier)&&this.current().value==="sql")if(this.advance(),this.expect(y.Equals),this.check(y.TripleQuoteString)){const r=this.advance(),o=this.extractInterpolations(r.value,r.span);n={kind:Q.SQLQuery,rawSQL:r.value,interpolations:o,span:r.span}}else n=this.parseSQLQuery();else this.check(y.Identifier)&&u0.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(y.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(y.ParamsKeyword),this.expect(y.LeftBrace);const n=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const o=this.currentSpan(),i=this.current();if(i.type===y.Identifier||this.isBlockFieldKeyword(i.type))this.advance();else{this.error(`Expected parameter name, got '${i.value}'.`),this.advance();continue}let a;if(this.check(y.ColonToken)){this.advance();let u=this.expect(y.Identifier).value;this.check(y.LeftBracket)&&((r=this.tokens[this.pos+1])==null?void 0:r.type)===y.RightBracket&&(this.advance(),this.advance(),u+="[]");const h=["string","number","boolean","date","string[]","number[]","date[]"];h.includes(u)?a=u:this.error(`Invalid block parameter type '${u}'. Valid types: ${h.join(", ")}`)}let c;this.check(y.Equals)&&(this.advance(),c=this.parseExpression()),n.push({name:i.value,paramType:a,initializer:c,span:this.makeSpan(o,this.previousSpan())})}return this.expect(y.RightBrace),{kind:Q.BlockParams,params:n,span:this.makeSpan(t,this.previousSpan())}}parseBlockParameterPolicy(){const t=[];for(this.expect(y.Identifier),this.expect(y.LeftBrace);!this.check(y.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan(),r=this.current();if(r.type===y.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected parameter name inside parameterPolicy, got '${r.value}'.`),this.advance();continue}this.expect(y.Equals);const o=this.expectStringLike();t.push({name:r.value,policy:o.value,span:this.makeSpan(n,this.previousSpan())})}return this.expect(y.RightBrace),t}parseBlockFilterBindings(){const t=[];for(this.expect(y.Identifier),this.expect(y.LeftBrace);!this.check(y.RightBrace)&&!this.isAtEnd();){const n=this.currentSpan(),r=this.current();if(r.type===y.Identifier||this.isBlockFieldKeyword(r.type))this.advance();else{this.error(`Expected business filter name inside filterBindings, got '${r.value}'.`),this.advance();continue}this.expect(y.Equals);const o=this.expectStringLike();t.push({filter:r.value,binding:o.value,span:this.makeSpan(n,this.previousSpan())})}return this.expect(y.RightBrace),t}parseBlockVisualization(){const t=this.currentSpan();this.expect(y.VisualizationKeyword),this.expect(y.LeftBrace);const n=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const r=this.currentSpan(),o=this.current();if(o.type===y.Identifier||this.isBlockFieldKeyword(o.type))this.advance();else{this.error(`Expected property name, got '${o.value}'.`),this.advance();continue}this.expect(y.Equals);const i=this.parseExpression();n.push({kind:Q.NamedArg,name:o.value,value:i,span:this.makeSpan(r,this.previousSpan())})}return this.expect(y.RightBrace),{kind:Q.BlockVisualization,properties:n,span:this.makeSpan(t,this.previousSpan())}}parseBlockTests(){this.currentSpan(),this.expect(y.TestsKeyword),this.expect(y.LeftBrace);const t=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.AssertKeyword)){const n=this.currentSpan();this.advance();const r=this.current();if(r.type===y.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(y.GreaterThan))this.advance(),o=">";else if(this.check(y.LessThan))this.advance(),o="<";else if(this.check(y.GreaterThanOrEqual))this.advance(),o=">=";else if(this.check(y.LessThanOrEqual))this.advance(),o="<=";else if(this.check(y.DoubleEquals))this.advance(),o="==";else if(this.check(y.NotEquals))this.advance(),o="!=";else if(this.check(y.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:Q.BlockTest,field:r.value,operator:o,expected:i,span:this.makeSpan(n,this.previousSpan())})}else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside tests. Expected 'assert' or '}'.`),this.advance()}return this.expect(y.RightBrace),t}isBlockFieldKeyword(t){return t===y.DomainKeyword||t===y.TypeKeyword||t===y.MetricKeyword||t===y.DescriptionKeyword||t===y.TagsKeyword||t===y.OwnerKeyword||t===y.TermsKeyword||t===y.ChartKeyword||t===y.QueryKeyword||t===y.DefaultKeyword||t===y.FromKeyword}parseWorkbook(t){const n=t.length>0?t[0].span:this.currentSpan();this.expect(y.WorkbookKeyword);const r=this.expect(y.StringLiteral);this.expect(y.LeftBrace);const o=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.PageKeyword))o.push(this.parsePage());else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside workbook. Expected 'page' or '}'.`),this.advance()}return this.expect(y.RightBrace),{kind:Q.Workbook,title:r.value,decorators:t,pages:o,span:this.makeSpan(n,this.previousSpan())}}parsePage(){const t=this.currentSpan();this.expect(y.PageKeyword);const n=this.expect(y.StringLiteral);this.expect(y.LeftBrace);const r=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const o=this.parseDecoratorList();if(this.check(y.LetKeyword))o.length>0&&this.error("Decorators cannot be applied to variable declarations."),r.push(this.parseVariableDecl());else if(this.check(y.ParamKeyword))o.length>0&&this.error("Decorators cannot be applied to param declarations."),r.push(this.parseParamDecl());else if(this.check(y.ChartKeyword))r.push(this.parseChartCall(o));else if(this.check(y.FilterKeyword))o.length>0&&this.error("Decorators cannot be applied to filter declarations."),r.push(this.parseFilterCall());else if(this.check(y.UseKeyword))o.length>0&&this.error("Decorators cannot be applied to use declarations."),r.push(this.parseUseDecl());else if(this.check(y.LayoutKeyword))o.length>0&&this.error("Decorators cannot be applied to layout blocks."),r.push(this.parseLayoutBlock());else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside page. Expected 'let', 'param', 'chart', 'filter', 'use', 'layout', or '}'.`),this.advance()}}return this.expect(y.RightBrace),{kind:Q.Page,title:n.value,body:r,span:this.makeSpan(t,this.previousSpan())}}parseParamDecl(){const t=this.currentSpan();this.expect(y.ParamKeyword);const n=this.expect(y.Identifier);let r="string";if(this.check(y.ColonToken)){this.advance();const i=this.expect(y.Identifier),a=["string","number","boolean","date"];a.includes(i.value)?r=i.value:this.reporter.error(`Invalid param type '${i.value}'. Valid types: ${a.join(", ")}`,i.span)}let o;return this.check(y.Equals)&&(this.advance(),o=this.parseExpression()),{kind:Q.ParamDecl,name:n.value,paramType:r,defaultValue:o,span:this.makeSpan(t,this.previousSpan())}}parseImportDecl(){const t=this.currentSpan();this.expect(y.ImportKeyword),this.expect(y.LeftBrace);const n=[];if(!this.check(y.RightBrace))for(n.push(this.expect(y.Identifier).value);this.check(y.Comma)&&(this.advance(),!this.check(y.RightBrace));)n.push(this.expect(y.Identifier).value);this.expect(y.RightBrace),this.expect(y.FromKeyword);const r=this.expect(y.StringLiteral);return{kind:Q.ImportDecl,names:n,path:r.value,span:this.makeSpan(t,this.previousSpan())}}parseUseDecl(){const t=this.currentSpan();this.expect(y.UseKeyword);let n;return this.check(y.Identifier)||this.check(y.StringLiteral)?n=this.advance():n=this.expect(y.Identifier),{kind:Q.UseDecl,name:n.value,span:this.makeSpan(t,this.previousSpan())}}parseLayoutBlock(){const t=this.currentSpan();this.expect(y.LayoutKeyword);let n=12;if(this.check(y.LeftParen)){this.advance();const o=[];if(!this.check(y.RightParen))for(o.push(this.parseNamedArg());this.check(y.Comma)&&(this.advance(),!this.check(y.RightParen));)o.push(this.parseNamedArg());this.expect(y.RightParen);const i=o.find(a=>a.name==="columns");i&&i.value.kind===Q.NumberLiteral&&(n=i.value.value)}this.expect(y.LeftBrace);const r=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();)if(this.check(y.RowKeyword))r.push(this.parseLayoutRow());else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside layout. Expected 'row' or '}'.`),this.advance()}return this.expect(y.RightBrace),{kind:Q.LayoutBlock,columns:n,rows:r,span:this.makeSpan(t,this.previousSpan())}}parseLayoutRow(){const t=this.currentSpan();this.expect(y.RowKeyword),this.expect(y.LeftBrace);const n=[];for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const r=this.parseDecoratorList();let o;if(this.check(y.ChartKeyword))o=this.parseChartCall(r);else if(this.check(y.FilterKeyword))r.length>0&&this.error("Decorators cannot be applied to filter declarations."),o=this.parseFilterCall();else{if(this.check(y.RightBrace))break;this.error(`Unexpected token '${this.current().value}' inside row. Expected 'chart', 'filter', or '}'.`),this.advance();continue}let i;if(this.check(y.Identifier)&&this.current().value==="span"){this.advance();const a=this.expect(y.NumberLiteral);i=Number(a.value)}n.push({node:o,span:i})}return this.expect(y.RightBrace),{kind:Q.LayoutRow,items:n,span:this.makeSpan(t,this.previousSpan())}}synchronize(){for(;!this.isAtEnd();){const t=this.current();if(t.type===y.DashboardKeyword||t.type===y.WorkbookKeyword||t.type===y.ChartKeyword||t.type===y.FilterKeyword||t.type===y.ImportKeyword||t.type===y.BlockKeyword||t.type===y.TermKeyword||t.type===y.BusinessViewKeyword||t.type===y.AtSign||t.type===y.RightBrace)return;this.advance()}}}function y0(e,t){return new g0(e,t).parse()}function b0(e,t={}){const n=y0(e);return x0(n,t)}function x0(e,t={}){const n={indentUnit:t.indent??" "},r=e.statements.map(o=>v0(o,0,n)).join(`
412
412
 
413
413
  `).trimEnd();return t.finalNewline===!1?r:`${r}
414
- `}function N(e,t){return t.indentUnit.repeat(e)}function x0(e,t,n){switch(e.kind){case Q.Dashboard:return v0(e,t,n);case Q.ChartCall:return $a(e,t,n);case Q.Workbook:return k0(e,t,n);case Q.ImportDecl:return j0(e,t,n);case Q.DomainDecl:return P0(e,t,n);case Q.BlockDecl:return _0(e,t,n);case Q.TermDecl:return I0(e,t,n);case Q.BusinessViewDecl:return D0(e,t,n);case Q.Digest:return S0(e,t,n);default:return""}}function v0(e,t,n){const r=[];r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}dashboard ${V(e.title)} {`);for(const o of e.body)r.push(Da(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
415
- `)}function S0(e,t,n){const r=[];r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}digest ${V(e.title)} {`),e.narrative&&r.push(w0(e.narrative,t+1,n));for(const o of e.body)r.push(Da(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
416
- `)}function w0(e,t,n){const r=[];r.push(`${N(t,n)}narrative {`);for(const o of e.properties)r.push(`${N(t+1,n)}${Ma(o)}`);return r.push(`${N(t,n)}}`),r.join(`
417
- `)}function k0(e,t,n){const r=[];r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}workbook ${V(e.title)} {`);for(const o of e.pages)r.push(C0(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
418
- `)}function C0(e,t,n){const r=[];r.push(`${N(t,n)}page ${V(e.title)} {`);for(const o of e.body)r.push(Da(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
419
- `)}function Da(e,t,n){switch(e.kind){case Q.VariableDecl:return T0(e,t,n);case Q.ParamDecl:return A0(e,t,n);case Q.ChartCall:return $a(e,t,n);case Q.FilterCall:return Mp(e,t,n);case Q.UseDecl:return E0(e,t,n);case Q.LayoutBlock:return R0(e,t,n);default:return""}}function j0(e,t,n){return`${N(t,n)}import { ${e.names.join(", ")} } from ${V(e.path)}`}function E0(e,t,n){const r=/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.name);return`${N(t,n)}use ${r?e.name:V(e.name)}`}function T0(e,t,n){return`${N(t,n)}let ${e.name} = ${_t(e.initializer)}`}function A0(e,t,n){const r=`: ${e.paramType}`,o=e.defaultValue?` = ${_t(e.defaultValue)}`:"";return`${N(t,n)}param ${e.name}${r}${o}`}function En(e,t,n){return e.map(r=>{if(r.arguments.length===0)return`${N(t,n)}@${r.name}`;const o=r.arguments.map(i=>_t(i)).join(", ");return`${N(t,n)}@${r.name}(${o})`})}function $a(e,t,n){return Lp(`chart.${e.chartType}`,e.decorators,e.query,e.args,t,n)}function Mp(e,t,n){return Lp(`filter.${e.filterType}`,[],e.query,e.args,t,n)}function Lp(e,t,n,r,o,i){const a=[];a.push(...En(t,o,i)),a.push(`${N(o,i)}${e}(`);const c=[];n&&c.push(Np(n,o+1,i));for(const l of r)c.push([`${N(o+1,i)}${Ma(l)}`]);for(let l=0;l<c.length;l++){const u=l===c.length-1,h=c[l];for(let d=0;d<h.length;d++){const f=d===h.length-1;a.push(f&&!u?`${h[d]},`:h[d])}}return a.push(`${N(o,i)})`),a.join(`
420
- `)}function R0(e,t,n){const r=[];r.push(`${N(t,n)}layout(columns = ${e.columns}) {`);for(const o of e.rows)r.push(O0(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
421
- `)}function O0(e,t,n){const r=[];r.push(`${N(t,n)}row {`);for(const o of e.items){const i=o.node.kind===Q.ChartCall?$a(o.node,t+1,n):Mp(o.node,t+1,n);if(o.span==null){r.push(i);continue}const a=i.split(`
414
+ `}function N(e,t){return t.indentUnit.repeat(e)}function v0(e,t,n){switch(e.kind){case Q.Dashboard:return S0(e,t,n);case Q.ChartCall:return $a(e,t,n);case Q.Workbook:return C0(e,t,n);case Q.ImportDecl:return E0(e,t,n);case Q.DomainDecl:return I0(e,t,n);case Q.BlockDecl:return P0(e,t,n);case Q.TermDecl:return D0(e,t,n);case Q.BusinessViewDecl:return $0(e,t,n);case Q.Digest:return w0(e,t,n);default:return""}}function S0(e,t,n){const r=[];r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}dashboard ${V(e.title)} {`);for(const o of e.body)r.push(Da(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
415
+ `)}function w0(e,t,n){const r=[];r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}digest ${V(e.title)} {`),e.narrative&&r.push(k0(e.narrative,t+1,n));for(const o of e.body)r.push(Da(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
416
+ `)}function k0(e,t,n){const r=[];r.push(`${N(t,n)}narrative {`);for(const o of e.properties)r.push(`${N(t+1,n)}${Ma(o)}`);return r.push(`${N(t,n)}}`),r.join(`
417
+ `)}function C0(e,t,n){const r=[];r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}workbook ${V(e.title)} {`);for(const o of e.pages)r.push(j0(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
418
+ `)}function j0(e,t,n){const r=[];r.push(`${N(t,n)}page ${V(e.title)} {`);for(const o of e.body)r.push(Da(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
419
+ `)}function Da(e,t,n){switch(e.kind){case Q.VariableDecl:return A0(e,t,n);case Q.ParamDecl:return R0(e,t,n);case Q.ChartCall:return $a(e,t,n);case Q.FilterCall:return Lp(e,t,n);case Q.UseDecl:return T0(e,t,n);case Q.LayoutBlock:return O0(e,t,n);default:return""}}function E0(e,t,n){return`${N(t,n)}import { ${e.names.join(", ")} } from ${V(e.path)}`}function T0(e,t,n){const r=/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.name);return`${N(t,n)}use ${r?e.name:V(e.name)}`}function A0(e,t,n){return`${N(t,n)}let ${e.name} = ${_t(e.initializer)}`}function R0(e,t,n){const r=`: ${e.paramType}`,o=e.defaultValue?` = ${_t(e.defaultValue)}`:"";return`${N(t,n)}param ${e.name}${r}${o}`}function En(e,t,n){return e.map(r=>{if(r.arguments.length===0)return`${N(t,n)}@${r.name}`;const o=r.arguments.map(i=>_t(i)).join(", ");return`${N(t,n)}@${r.name}(${o})`})}function $a(e,t,n){return Np(`chart.${e.chartType}`,e.decorators,e.query,e.args,t,n)}function Lp(e,t,n){return Np(`filter.${e.filterType}`,[],e.query,e.args,t,n)}function Np(e,t,n,r,o,i){const a=[];a.push(...En(t,o,i)),a.push(`${N(o,i)}${e}(`);const c=[];n&&c.push(Bp(n,o+1,i));for(const l of r)c.push([`${N(o+1,i)}${Ma(l)}`]);for(let l=0;l<c.length;l++){const u=l===c.length-1,h=c[l];for(let d=0;d<h.length;d++){const f=d===h.length-1;a.push(f&&!u?`${h[d]},`:h[d])}}return a.push(`${N(o,i)})`),a.join(`
420
+ `)}function O0(e,t,n){const r=[];r.push(`${N(t,n)}layout(columns = ${e.columns}) {`);for(const o of e.rows)r.push(_0(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
421
+ `)}function _0(e,t,n){const r=[];r.push(`${N(t,n)}row {`);for(const o of e.items){const i=o.node.kind===Q.ChartCall?$a(o.node,t+1,n):Lp(o.node,t+1,n);if(o.span==null){r.push(i);continue}const a=i.split(`
422
422
  `);a[a.length-1]=`${a[a.length-1]} span ${o.span}`,r.push(a.join(`
423
423
  `))}return r.push(`${N(t,n)}}`),r.join(`
424
- `)}function _0(e,t,n){const r=[];if(r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}block ${V(e.name)} {`),e.domain&&r.push(`${N(t+1,n)}domain = ${V(e.domain)}`),e.blockType&&r.push(`${N(t+1,n)}type = ${V(e.blockType)}`),e.status&&r.push(`${N(t+1,n)}status = ${V(e.status)}`),e.description&&r.push(`${N(t+1,n)}description = ${V(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${N(t+1,n)}tags = [${e.tags.map(V).join(", ")}]`),e.owner&&r.push(`${N(t+1,n)}owner = ${V(e.owner)}`),e.termRefs&&e.termRefs.length>0&&r.push(`${N(t+1,n)}terms = [${e.termRefs.map(V).join(", ")}]`),e.pattern&&r.push(`${N(t+1,n)}pattern = ${V(e.pattern)}`),e.grain&&r.push(`${N(t+1,n)}grain = ${V(e.grain)}`),e.entities&&e.entities.length>0&&r.push(`${N(t+1,n)}entities = [${e.entities.map(V).join(", ")}]`),e.outputs&&e.outputs.length>0&&r.push(`${N(t+1,n)}outputs = [${e.outputs.map(V).join(", ")}]`),e.blockType!=="semantic"&&e.dimensions&&e.dimensions.length>0&&r.push(`${N(t+1,n)}dimensions = [${e.dimensions.map(V).join(", ")}]`),e.allowedFilters&&e.allowedFilters.length>0&&r.push(`${N(t+1,n)}allowedFilters = [${e.allowedFilters.map(V).join(", ")}]`),e.parameterPolicy&&e.parameterPolicy.length>0){r.push(`${N(t+1,n)}parameterPolicy {`);for(const o of e.parameterPolicy)r.push(`${N(t+2,n)}${o.name} = ${V(o.policy)}`);r.push(`${N(t+1,n)}}`)}if(e.filterBindings&&e.filterBindings.length>0){r.push(`${N(t+1,n)}filterBindings {`);for(const o of e.filterBindings)r.push(`${N(t+2,n)}${o.filter} = ${V(o.binding)}`);r.push(`${N(t+1,n)}}`)}if(e.sourceSystems&&e.sourceSystems.length>0&&r.push(`${N(t+1,n)}sourceSystems = [${e.sourceSystems.map(V).join(", ")}]`),e.replacementFor&&e.replacementFor.length>0&&r.push(`${N(t+1,n)}replacementFor = [${e.replacementFor.map(V).join(", ")}]`),e.llmContext&&r.push(`${N(t+1,n)}llmContext = ${V(e.llmContext)}`),e.businessOutcome&&r.push(`${N(t+1,n)}businessOutcome = ${V(e.businessOutcome)}`),e.businessOwner&&r.push(`${N(t+1,n)}businessOwner = ${V(e.businessOwner)}`),e.decisionUse&&r.push(`${N(t+1,n)}decisionUse = ${V(e.decisionUse)}`),e.reviewCadence&&r.push(`${N(t+1,n)}reviewCadence = ${V(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${N(t+1,n)}businessRules = [${e.businessRules.map(V).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${N(t+1,n)}caveats = [${e.caveats.map(V).join(", ")}]`),e.examples&&e.examples.length>0&&r.push(`${N(t+1,n)}examples = [${$0(e.examples)}]`),e.invariants&&e.invariants.length>0&&r.push(`${N(t+1,n)}invariants = [${e.invariants.map(V).join(", ")}]`),e.blockType==="semantic"){const o=e.metricsRef??(e.metricRef!==void 0?[e.metricRef]:[]);r.push(`${N(t+1,n)}metrics = [${o.map(V).join(", ")}]`),r.push(`${N(t+1,n)}dimensions = [${(e.dimensionsRef??[]).map(V).join(", ")}]`),e.timeDimension&&r.push(`${N(t+1,n)}time_dimension = ${V(e.timeDimension)}`),e.granularity&&r.push(`${N(t+1,n)}granularity = ${V(e.granularity)}`),e.requestedFilters&&e.requestedFilters.length>0&&r.push(`${N(t+1,n)}requested_filters = [${e.requestedFilters.map(V).join(", ")}]`),e.orderBy&&e.orderBy.length>0&&r.push(`${N(t+1,n)}order_by = [${e.orderBy.map(V).join(", ")}]`),e.limit!==void 0&&r.push(`${N(t+1,n)}limit = ${e.limit}`)}if(e.params){r.push(`${N(t+1,n)}params {`);for(const o of e.params.params){const i=o.paramType?`: ${o.paramType}`:"",a=o.initializer?` = ${_t(o.initializer)}`:"";r.push(`${N(t+2,n)}${o.name}${i}${a}`)}r.push(`${N(t+1,n)}}`)}if(e.query&&(r.push(`${N(t+1,n)}query = """`),r.push(...Np(e.query,t+2,n)),r.push(`${N(t+1,n)}"""`)),e.visualization){r.push(`${N(t+1,n)}visualization {`);for(const o of e.visualization.properties)r.push(`${N(t+2,n)}${Ma(o)}`);r.push(`${N(t+1,n)}}`)}if(e.tests&&e.tests.length>0){r.push(`${N(t+1,n)}tests {`);for(const o of e.tests)r.push(`${N(t+2,n)}assert ${o.field} ${o.operator} ${_t(o.expected)}`);r.push(`${N(t+1,n)}}`)}return r.push(`${N(t,n)}}`),r.join(`
425
- `)}function P0(e,t,n){var o,i,a,c,l,u,h,d;const r=[];return r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}domain ${V(e.name)} {`),e.id&&r.push(`${N(t+1,n)}id = ${V(e.id)}`),e.parent&&r.push(`${N(t+1,n)}parent = ${V(e.parent)}`),e.owner&&r.push(`${N(t+1,n)}owner = ${V(e.owner)}`),e.businessOwner&&r.push(`${N(t+1,n)}businessOwner = ${V(e.businessOwner)}`),e.boundedContext&&r.push(`${N(t+1,n)}boundedContext = ${V(e.boundedContext)}`),e.sourceSystems&&e.sourceSystems.length>0&&r.push(`${N(t+1,n)}sourceSystems = [${e.sourceSystems.map(V).join(", ")}]`),e.primaryTerms&&e.primaryTerms.length>0&&r.push(`${N(t+1,n)}primaryTerms = [${e.primaryTerms.map(V).join(", ")}]`),e.reviewCadence&&r.push(`${N(t+1,n)}reviewCadence = ${V(e.reviewCadence)}`),e.tags&&e.tags.length>0&&r.push(`${N(t+1,n)}tags = [${e.tags.map(V).join(", ")}]`),e.businessOutcome&&r.push(`${N(t+1,n)}businessOutcome = ${V(e.businessOutcome)}`),e.description&&r.push(`${N(t+1,n)}description = ${V(e.description)}`),(o=e.inScope)!=null&&o.length&&r.push(`${N(t+1,n)}inScope = [${e.inScope.map(V).join(", ")}]`),(i=e.outOfScope)!=null&&i.length&&r.push(`${N(t+1,n)}outOfScope = [${e.outOfScope.map(V).join(", ")}]`),(a=e.dbtGroups)!=null&&a.length&&r.push(`${N(t+1,n)}dbtGroups = [${e.dbtGroups.map(V).join(", ")}]`),(c=e.dbtPaths)!=null&&c.length&&r.push(`${N(t+1,n)}dbtPaths = [${e.dbtPaths.map(V).join(", ")}]`),(l=e.dbtTags)!=null&&l.length&&r.push(`${N(t+1,n)}dbtTags = [${e.dbtTags.map(V).join(", ")}]`),(u=e.semanticDomains)!=null&&u.length&&r.push(`${N(t+1,n)}semanticDomains = [${e.semanticDomains.map(V).join(", ")}]`),(h=e.semanticTags)!=null&&h.length&&r.push(`${N(t+1,n)}semanticTags = [${e.semanticTags.map(V).join(", ")}]`),(d=e.exports)!=null&&d.length&&r.push(`${N(t+1,n)}exports = [${e.exports.map(V).join(", ")}]`),r.push(`${N(t,n)}}`),r.join(`
426
- `)}function I0(e,t,n){const r=[];return r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}term ${V(e.name)} {`),e.domain&&r.push(`${N(t+1,n)}domain = ${V(e.domain)}`),e.termType&&r.push(`${N(t+1,n)}type = ${V(e.termType)}`),e.status&&r.push(`${N(t+1,n)}status = ${V(e.status)}`),e.description&&r.push(`${N(t+1,n)}description = ${V(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${N(t+1,n)}tags = [${e.tags.map(V).join(", ")}]`),e.owner&&r.push(`${N(t+1,n)}owner = ${V(e.owner)}`),e.identifiers&&e.identifiers.length>0&&r.push(`${N(t+1,n)}identifiers = [${e.identifiers.map(V).join(", ")}]`),e.synonyms&&e.synonyms.length>0&&r.push(`${N(t+1,n)}synonyms = [${e.synonyms.map(V).join(", ")}]`),e.businessOutcome&&r.push(`${N(t+1,n)}businessOutcome = ${V(e.businessOutcome)}`),e.businessOwner&&r.push(`${N(t+1,n)}businessOwner = ${V(e.businessOwner)}`),e.decisionUse&&r.push(`${N(t+1,n)}decisionUse = ${V(e.decisionUse)}`),e.reviewCadence&&r.push(`${N(t+1,n)}reviewCadence = ${V(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${N(t+1,n)}businessRules = [${e.businessRules.map(V).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${N(t+1,n)}caveats = [${e.caveats.map(V).join(", ")}]`),r.push(`${N(t,n)}}`),r.join(`
427
- `)}function D0(e,t,n){const r=[];r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}business_view ${V(e.name)} {`),e.domain&&r.push(`${N(t+1,n)}domain = ${V(e.domain)}`),e.status&&r.push(`${N(t+1,n)}status = ${V(e.status)}`),e.description&&r.push(`${N(t+1,n)}description = ${V(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${N(t+1,n)}tags = [${e.tags.map(V).join(", ")}]`),e.owner&&r.push(`${N(t+1,n)}owner = ${V(e.owner)}`),e.termRefs&&e.termRefs.length>0&&r.push(`${N(t+1,n)}terms = [${e.termRefs.map(V).join(", ")}]`),e.businessOutcome&&r.push(`${N(t+1,n)}businessOutcome = ${V(e.businessOutcome)}`),e.businessOwner&&r.push(`${N(t+1,n)}businessOwner = ${V(e.businessOwner)}`),e.decisionUse&&r.push(`${N(t+1,n)}decisionUse = ${V(e.decisionUse)}`),e.reviewCadence&&r.push(`${N(t+1,n)}reviewCadence = ${V(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${N(t+1,n)}businessRules = [${e.businessRules.map(V).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${N(t+1,n)}caveats = [${e.caveats.map(V).join(", ")}]`),r.push(`${N(t+1,n)}includes {`);for(const o of e.includes)r.push(`${N(t+2,n)}${o.refType} ${V(o.name)}`);return r.push(`${N(t+1,n)}}`),r.push(`${N(t,n)}}`),r.join(`
428
- `)}function Np(e,t,n){const r=e.rawSQL.replace(/^\n+|\s+$/g,"");if(!r.trim())return[`${N(t,n)}SELECT 1`];const o=r.split(`
429
- `).map(l=>l.trimEnd()),i=o.slice(1).filter(l=>l.length>0),a=i.length?i:o.filter(l=>l.length>0),c=a.length?Math.min(...a.map(l=>l.match(/^[ \t]*/)[0].length)):0;return o.map(l=>{if(l.length===0)return"";const u=l.startsWith(" ".repeat(c))||l.startsWith(" ".repeat(c))?l.slice(c):l.trimStart();return`${N(t,n)}${u}`})}function Ma(e){return`${e.name} = ${_t(e.value)}`}function $0(e){return e.map(t=>{const n=[`question = ${V(t.question)}`];return t.sql&&n.push(`sql = ${V(t.sql)}`),`{ ${n.join(", ")} }`}).join(", ")}function _t(e){switch(e.kind){case Q.StringLiteral:return V(e.value);case Q.NumberLiteral:return String(e.value);case Q.BooleanLiteral:return e.value?"true":"false";case Q.Identifier:return e.name;case Q.ArrayLiteral:return`[${e.elements.map(t=>_t(t)).join(", ")}]`;case Q.BinaryExpr:return`${_t(e.left)} ${e.operator} ${_t(e.right)}`;case Q.IntervalExpr:return`INTERVAL ${V(e.value)}`;case Q.FunctionCall:return`${e.callee}(${e.arguments.map(t=>_t(t)).join(", ")})`;case Q.TemplateString:return V(e.parts.map(t=>typeof t=="string"?t:`{${_t(t)}}`).join(""));default:return""}}function V(e){return JSON.stringify(e)}function M0(e){var u,h,d,f,m,S,v,b;const t=zr(e.metrics),n=zr(e.dimensions??[]),r=zr(e.requestedFilters??[]),o=zr((e.orderBy??[]).map(w=>typeof w=="string"?w:`${w.name} ${w.direction}`)),i=N0(e.parameters??[]),a=[`block ${ze(e.name)} {`,' type = "semantic"',` status = ${ze(((u=e.status)==null?void 0:u.trim())||"draft")}`],c=L0(e.domain);c&&a.push(` domain = ${ze(c)}`),(h=e.description)!=null&&h.trim()&&a.push(` description = ${ze(e.description.trim())}`);const l=zr(e.tags??[]);if(l.length>0&&a.push(` tags = [${l.map(ze).join(", ")}]`),(d=e.owner)!=null&&d.trim()&&a.push(` owner = ${ze(e.owner.trim())}`),a.push(` metrics = [${t.map(ze).join(", ")}]`),a.push(` dimensions = [${n.map(ze).join(", ")}]`),(f=e.timeDimension)!=null&&f.name.trim()&&(a.push(` time_dimension = ${ze(e.timeDimension.name.trim())}`),e.timeDimension.granularity.trim()&&a.push(` granularity = ${ze(e.timeDimension.granularity.trim())}`)),r.length>0&&a.push(` requested_filters = [${r.map(ze).join(", ")}]`),o.length>0&&a.push(` order_by = [${o.map(ze).join(", ")}]`),B0(e.limit)&&a.push(` limit = ${Math.floor(e.limit)}`),i.length>0){a.push(" params {");for(const C of i){const x=(m=C.type)!=null&&m.trim()?`: ${C.type.trim()}`:"",E=C.default!==void 0?` = ${Bp(C.default)}`:"";a.push(` ${C.name}${x}${E}`)}a.push(" }");const w=i.filter(C=>{var x;return(x=C.policy)==null?void 0:x.trim()});if(w.length>0){a.push(" parameterPolicy {");for(const C of w)a.push(` ${C.name} = ${ze(C.policy.trim())}`);a.push(" }")}const j=i.filter(C=>{var x;return(x=C.binding)==null?void 0:x.trim()});if(j.length>0){a.push(" filterBindings {");for(const C of j)a.push(` ${C.name} = ${ze(C.binding.trim())}`);a.push(" }")}}return(S=e.visualization)!=null&&S.chart.trim()&&(a.push(" visualization {"),a.push(` chart = ${ze(e.visualization.chart.trim())}`),(v=e.visualization.x)!=null&&v.trim()&&a.push(` x = ${il(e.visualization.x.trim())}`),(b=e.visualization.y)!=null&&b.trim()&&a.push(` y = ${il(e.visualization.y.trim())}`),a.push(" }")),a.push("}"),y0(`${a.join(`
424
+ `)}function P0(e,t,n){const r=[];if(r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}block ${V(e.name)} {`),e.domain&&r.push(`${N(t+1,n)}domain = ${V(e.domain)}`),e.blockType&&r.push(`${N(t+1,n)}type = ${V(e.blockType)}`),e.status&&r.push(`${N(t+1,n)}status = ${V(e.status)}`),e.description&&r.push(`${N(t+1,n)}description = ${V(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${N(t+1,n)}tags = [${e.tags.map(V).join(", ")}]`),e.owner&&r.push(`${N(t+1,n)}owner = ${V(e.owner)}`),e.termRefs&&e.termRefs.length>0&&r.push(`${N(t+1,n)}terms = [${e.termRefs.map(V).join(", ")}]`),e.pattern&&r.push(`${N(t+1,n)}pattern = ${V(e.pattern)}`),e.grain&&r.push(`${N(t+1,n)}grain = ${V(e.grain)}`),e.entities&&e.entities.length>0&&r.push(`${N(t+1,n)}entities = [${e.entities.map(V).join(", ")}]`),e.outputs&&e.outputs.length>0&&r.push(`${N(t+1,n)}outputs = [${e.outputs.map(V).join(", ")}]`),e.blockType!=="semantic"&&e.dimensions&&e.dimensions.length>0&&r.push(`${N(t+1,n)}dimensions = [${e.dimensions.map(V).join(", ")}]`),e.allowedFilters&&e.allowedFilters.length>0&&r.push(`${N(t+1,n)}allowedFilters = [${e.allowedFilters.map(V).join(", ")}]`),e.parameterPolicy&&e.parameterPolicy.length>0){r.push(`${N(t+1,n)}parameterPolicy {`);for(const o of e.parameterPolicy)r.push(`${N(t+2,n)}${o.name} = ${V(o.policy)}`);r.push(`${N(t+1,n)}}`)}if(e.filterBindings&&e.filterBindings.length>0){r.push(`${N(t+1,n)}filterBindings {`);for(const o of e.filterBindings)r.push(`${N(t+2,n)}${o.filter} = ${V(o.binding)}`);r.push(`${N(t+1,n)}}`)}if(e.sourceSystems&&e.sourceSystems.length>0&&r.push(`${N(t+1,n)}sourceSystems = [${e.sourceSystems.map(V).join(", ")}]`),e.replacementFor&&e.replacementFor.length>0&&r.push(`${N(t+1,n)}replacementFor = [${e.replacementFor.map(V).join(", ")}]`),e.llmContext&&r.push(`${N(t+1,n)}llmContext = ${V(e.llmContext)}`),e.businessOutcome&&r.push(`${N(t+1,n)}businessOutcome = ${V(e.businessOutcome)}`),e.businessOwner&&r.push(`${N(t+1,n)}businessOwner = ${V(e.businessOwner)}`),e.decisionUse&&r.push(`${N(t+1,n)}decisionUse = ${V(e.decisionUse)}`),e.reviewCadence&&r.push(`${N(t+1,n)}reviewCadence = ${V(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${N(t+1,n)}businessRules = [${e.businessRules.map(V).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${N(t+1,n)}caveats = [${e.caveats.map(V).join(", ")}]`),e.examples&&e.examples.length>0&&r.push(`${N(t+1,n)}examples = [${M0(e.examples)}]`),e.invariants&&e.invariants.length>0&&r.push(`${N(t+1,n)}invariants = [${e.invariants.map(V).join(", ")}]`),e.blockType==="semantic"){const o=e.metricsRef??(e.metricRef!==void 0?[e.metricRef]:[]);r.push(`${N(t+1,n)}metrics = [${o.map(V).join(", ")}]`),r.push(`${N(t+1,n)}dimensions = [${(e.dimensionsRef??[]).map(V).join(", ")}]`),e.timeDimension&&r.push(`${N(t+1,n)}time_dimension = ${V(e.timeDimension)}`),e.granularity&&r.push(`${N(t+1,n)}granularity = ${V(e.granularity)}`),e.requestedFilters&&e.requestedFilters.length>0&&r.push(`${N(t+1,n)}requested_filters = [${e.requestedFilters.map(V).join(", ")}]`),e.orderBy&&e.orderBy.length>0&&r.push(`${N(t+1,n)}order_by = [${e.orderBy.map(V).join(", ")}]`),e.limit!==void 0&&r.push(`${N(t+1,n)}limit = ${e.limit}`)}if(e.params){r.push(`${N(t+1,n)}params {`);for(const o of e.params.params){const i=o.paramType?`: ${o.paramType}`:"",a=o.initializer?` = ${_t(o.initializer)}`:"";r.push(`${N(t+2,n)}${o.name}${i}${a}`)}r.push(`${N(t+1,n)}}`)}if(e.query&&(r.push(`${N(t+1,n)}query = """`),r.push(...Bp(e.query,t+2,n)),r.push(`${N(t+1,n)}"""`)),e.visualization){r.push(`${N(t+1,n)}visualization {`);for(const o of e.visualization.properties)r.push(`${N(t+2,n)}${Ma(o)}`);r.push(`${N(t+1,n)}}`)}if(e.tests&&e.tests.length>0){r.push(`${N(t+1,n)}tests {`);for(const o of e.tests)r.push(`${N(t+2,n)}assert ${o.field} ${o.operator} ${_t(o.expected)}`);r.push(`${N(t+1,n)}}`)}return r.push(`${N(t,n)}}`),r.join(`
425
+ `)}function I0(e,t,n){var o,i,a,c,l,u,h,d;const r=[];return r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}domain ${V(e.name)} {`),e.id&&r.push(`${N(t+1,n)}id = ${V(e.id)}`),e.parent&&r.push(`${N(t+1,n)}parent = ${V(e.parent)}`),e.owner&&r.push(`${N(t+1,n)}owner = ${V(e.owner)}`),e.businessOwner&&r.push(`${N(t+1,n)}businessOwner = ${V(e.businessOwner)}`),e.boundedContext&&r.push(`${N(t+1,n)}boundedContext = ${V(e.boundedContext)}`),e.sourceSystems&&e.sourceSystems.length>0&&r.push(`${N(t+1,n)}sourceSystems = [${e.sourceSystems.map(V).join(", ")}]`),e.primaryTerms&&e.primaryTerms.length>0&&r.push(`${N(t+1,n)}primaryTerms = [${e.primaryTerms.map(V).join(", ")}]`),e.reviewCadence&&r.push(`${N(t+1,n)}reviewCadence = ${V(e.reviewCadence)}`),e.tags&&e.tags.length>0&&r.push(`${N(t+1,n)}tags = [${e.tags.map(V).join(", ")}]`),e.businessOutcome&&r.push(`${N(t+1,n)}businessOutcome = ${V(e.businessOutcome)}`),e.description&&r.push(`${N(t+1,n)}description = ${V(e.description)}`),(o=e.inScope)!=null&&o.length&&r.push(`${N(t+1,n)}inScope = [${e.inScope.map(V).join(", ")}]`),(i=e.outOfScope)!=null&&i.length&&r.push(`${N(t+1,n)}outOfScope = [${e.outOfScope.map(V).join(", ")}]`),(a=e.dbtGroups)!=null&&a.length&&r.push(`${N(t+1,n)}dbtGroups = [${e.dbtGroups.map(V).join(", ")}]`),(c=e.dbtPaths)!=null&&c.length&&r.push(`${N(t+1,n)}dbtPaths = [${e.dbtPaths.map(V).join(", ")}]`),(l=e.dbtTags)!=null&&l.length&&r.push(`${N(t+1,n)}dbtTags = [${e.dbtTags.map(V).join(", ")}]`),(u=e.semanticDomains)!=null&&u.length&&r.push(`${N(t+1,n)}semanticDomains = [${e.semanticDomains.map(V).join(", ")}]`),(h=e.semanticTags)!=null&&h.length&&r.push(`${N(t+1,n)}semanticTags = [${e.semanticTags.map(V).join(", ")}]`),(d=e.exports)!=null&&d.length&&r.push(`${N(t+1,n)}exports = [${e.exports.map(V).join(", ")}]`),r.push(`${N(t,n)}}`),r.join(`
426
+ `)}function D0(e,t,n){const r=[];return r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}term ${V(e.name)} {`),e.domain&&r.push(`${N(t+1,n)}domain = ${V(e.domain)}`),e.termType&&r.push(`${N(t+1,n)}type = ${V(e.termType)}`),e.status&&r.push(`${N(t+1,n)}status = ${V(e.status)}`),e.description&&r.push(`${N(t+1,n)}description = ${V(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${N(t+1,n)}tags = [${e.tags.map(V).join(", ")}]`),e.owner&&r.push(`${N(t+1,n)}owner = ${V(e.owner)}`),e.identifiers&&e.identifiers.length>0&&r.push(`${N(t+1,n)}identifiers = [${e.identifiers.map(V).join(", ")}]`),e.synonyms&&e.synonyms.length>0&&r.push(`${N(t+1,n)}synonyms = [${e.synonyms.map(V).join(", ")}]`),e.businessOutcome&&r.push(`${N(t+1,n)}businessOutcome = ${V(e.businessOutcome)}`),e.businessOwner&&r.push(`${N(t+1,n)}businessOwner = ${V(e.businessOwner)}`),e.decisionUse&&r.push(`${N(t+1,n)}decisionUse = ${V(e.decisionUse)}`),e.reviewCadence&&r.push(`${N(t+1,n)}reviewCadence = ${V(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${N(t+1,n)}businessRules = [${e.businessRules.map(V).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${N(t+1,n)}caveats = [${e.caveats.map(V).join(", ")}]`),r.push(`${N(t,n)}}`),r.join(`
427
+ `)}function $0(e,t,n){const r=[];r.push(...En(e.decorators,t,n)),r.push(`${N(t,n)}business_view ${V(e.name)} {`),e.domain&&r.push(`${N(t+1,n)}domain = ${V(e.domain)}`),e.status&&r.push(`${N(t+1,n)}status = ${V(e.status)}`),e.description&&r.push(`${N(t+1,n)}description = ${V(e.description)}`),e.tags&&e.tags.length>0&&r.push(`${N(t+1,n)}tags = [${e.tags.map(V).join(", ")}]`),e.owner&&r.push(`${N(t+1,n)}owner = ${V(e.owner)}`),e.termRefs&&e.termRefs.length>0&&r.push(`${N(t+1,n)}terms = [${e.termRefs.map(V).join(", ")}]`),e.businessOutcome&&r.push(`${N(t+1,n)}businessOutcome = ${V(e.businessOutcome)}`),e.businessOwner&&r.push(`${N(t+1,n)}businessOwner = ${V(e.businessOwner)}`),e.decisionUse&&r.push(`${N(t+1,n)}decisionUse = ${V(e.decisionUse)}`),e.reviewCadence&&r.push(`${N(t+1,n)}reviewCadence = ${V(e.reviewCadence)}`),e.businessRules&&e.businessRules.length>0&&r.push(`${N(t+1,n)}businessRules = [${e.businessRules.map(V).join(", ")}]`),e.caveats&&e.caveats.length>0&&r.push(`${N(t+1,n)}caveats = [${e.caveats.map(V).join(", ")}]`),r.push(`${N(t+1,n)}includes {`);for(const o of e.includes)r.push(`${N(t+2,n)}${o.refType} ${V(o.name)}`);return r.push(`${N(t+1,n)}}`),r.push(`${N(t,n)}}`),r.join(`
428
+ `)}function Bp(e,t,n){const r=e.rawSQL.replace(/^\n+|\s+$/g,"");if(!r.trim())return[`${N(t,n)}SELECT 1`];const o=r.split(`
429
+ `).map(l=>l.trimEnd()),i=o.slice(1).filter(l=>l.length>0),a=i.length?i:o.filter(l=>l.length>0),c=a.length?Math.min(...a.map(l=>l.match(/^[ \t]*/)[0].length)):0;return o.map(l=>{if(l.length===0)return"";const u=l.startsWith(" ".repeat(c))||l.startsWith(" ".repeat(c))?l.slice(c):l.trimStart();return`${N(t,n)}${u}`})}function Ma(e){return`${e.name} = ${_t(e.value)}`}function M0(e){return e.map(t=>{const n=[`question = ${V(t.question)}`];return t.sql&&n.push(`sql = ${V(t.sql)}`),`{ ${n.join(", ")} }`}).join(", ")}function _t(e){switch(e.kind){case Q.StringLiteral:return V(e.value);case Q.NumberLiteral:return String(e.value);case Q.BooleanLiteral:return e.value?"true":"false";case Q.Identifier:return e.name;case Q.ArrayLiteral:return`[${e.elements.map(t=>_t(t)).join(", ")}]`;case Q.BinaryExpr:return`${_t(e.left)} ${e.operator} ${_t(e.right)}`;case Q.IntervalExpr:return`INTERVAL ${V(e.value)}`;case Q.FunctionCall:return`${e.callee}(${e.arguments.map(t=>_t(t)).join(", ")})`;case Q.TemplateString:return V(e.parts.map(t=>typeof t=="string"?t:`{${_t(t)}}`).join(""));default:return""}}function V(e){return JSON.stringify(e)}function L0(e){var u,h,d,f,m,S,v,b;const t=zr(e.metrics),n=zr(e.dimensions??[]),r=zr(e.requestedFilters??[]),o=zr((e.orderBy??[]).map(w=>typeof w=="string"?w:`${w.name} ${w.direction}`)),i=B0(e.parameters??[]),a=[`block ${ze(e.name)} {`,' type = "semantic"',` status = ${ze(((u=e.status)==null?void 0:u.trim())||"draft")}`],c=N0(e.domain);c&&a.push(` domain = ${ze(c)}`),(h=e.description)!=null&&h.trim()&&a.push(` description = ${ze(e.description.trim())}`);const l=zr(e.tags??[]);if(l.length>0&&a.push(` tags = [${l.map(ze).join(", ")}]`),(d=e.owner)!=null&&d.trim()&&a.push(` owner = ${ze(e.owner.trim())}`),a.push(` metrics = [${t.map(ze).join(", ")}]`),a.push(` dimensions = [${n.map(ze).join(", ")}]`),(f=e.timeDimension)!=null&&f.name.trim()&&(a.push(` time_dimension = ${ze(e.timeDimension.name.trim())}`),e.timeDimension.granularity.trim()&&a.push(` granularity = ${ze(e.timeDimension.granularity.trim())}`)),r.length>0&&a.push(` requested_filters = [${r.map(ze).join(", ")}]`),o.length>0&&a.push(` order_by = [${o.map(ze).join(", ")}]`),F0(e.limit)&&a.push(` limit = ${Math.floor(e.limit)}`),i.length>0){a.push(" params {");for(const C of i){const x=(m=C.type)!=null&&m.trim()?`: ${C.type.trim()}`:"",E=C.default!==void 0?` = ${Fp(C.default)}`:"";a.push(` ${C.name}${x}${E}`)}a.push(" }");const w=i.filter(C=>{var x;return(x=C.policy)==null?void 0:x.trim()});if(w.length>0){a.push(" parameterPolicy {");for(const C of w)a.push(` ${C.name} = ${ze(C.policy.trim())}`);a.push(" }")}const j=i.filter(C=>{var x;return(x=C.binding)==null?void 0:x.trim()});if(j.length>0){a.push(" filterBindings {");for(const C of j)a.push(` ${C.name} = ${ze(C.binding.trim())}`);a.push(" }")}}return(S=e.visualization)!=null&&S.chart.trim()&&(a.push(" visualization {"),a.push(` chart = ${ze(e.visualization.chart.trim())}`),(v=e.visualization.x)!=null&&v.trim()&&a.push(` x = ${al(e.visualization.x.trim())}`),(b=e.visualization.y)!=null&&b.trim()&&a.push(` y = ${al(e.visualization.y.trim())}`),a.push(" }")),a.push("}"),b0(`${a.join(`
430
430
  `)}
431
- `)}function L0(e){const t=e==null?void 0:e.trim();if(!(!t||t==="uncategorized"||t==="_uncategorized"))return t}function zr(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function N0(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 B0(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Bp(e){return Array.isArray(e)?`[${e.map(Bp).join(", ")}]`:typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":ze(String(e??""))}function ze(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function il(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:ze(e)}function F0(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 M0({name:i,status:"draft",metrics:n,dimensions:r}).trimEnd()}function z0(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 q0(e,t){var o;const n={path:"",folders:new Map,blocks:[]};for(const i of e){const a=((o=i.domain)==null?void 0:o.trim())||"uncategorized",l=z0(i.path,t||a).split("/").filter(Boolean),u=t?l.slice(0,-1):[a,...l.slice(0,-1)];let h=n;for(const d of u){const f=[h.path,d].filter(Boolean).join("/");let m=h.folders.get(d);m||(m={name:d,path:f,folders:new Map,blocks:[]},h.folders.set(d,m)),h=m}h.blocks.push(i)}const r=i=>[...Array.from(i.folders.values()).sort((a,c)=>a.name.localeCompare(c.name)).map(a=>({kind:"folder",name:a.name,path:a.path,children:r(a)})),...i.blocks.sort((a,c)=>a.name.localeCompare(c.name)).map(a=>({kind:"block",block:a}))];return r(n)}function U0(e,t){const n={path:"",folders:new Map,files:[]};for(const o of e){const i=W0(o,t);let a=n;for(const c of i){const l=[a.path,c].filter(Boolean).join("/");let u=a.folders.get(c);u||(u={name:c,path:l,folders:new Map,files:[]},a.folders.set(c,u)),a=u}a.files.push(o)}const r=o=>[...Array.from(o.folders.values()).sort((i,a)=>i.name.localeCompare(a.name)).map(i=>({kind:"folder",name:i.name,path:i.path,children:r(i)})),...o.files.sort((i,a)=>i.name.localeCompare(a.name)).map(i=>({kind:"file",file:i}))];return r(n)}function W0(e,t){const n=e.path.replace(/\\/g,"/").split("/").filter(Boolean);if(n[0]==="domains"){const i=["notebooks","workbooks"],a=n.findIndex((c,l)=>l>0&&i.includes(c));if(a>0)return["Domains",...n.slice(1,a),...n.slice(a+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(a=>a.trim()).filter(Boolean),...o]:["Project",...o]}function Fp({id:e,ariaLabel:t,value:n,options:r,onChange:o,summary:i,t:a}){return s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${a.headerBorder}`,display:"grid",gap:5},children:[s.jsx("label",{htmlFor:e,style:{color:a.textMuted,fontSize:9,fontWeight:750,letterSpacing:".06em",textTransform:"uppercase"},children:"Domain"}),s.jsxs("select",{id:e,"aria-label":t,value:n,onChange:c=>o(c.target.value),style:{width:"100%",background:a.inputBg,border:`1px solid ${a.inputBorder}`,borderRadius:6,color:a.textPrimary,fontFamily:a.font,fontSize:12,padding:"7px 8px"},children:[s.jsx("option",{value:"",children:"All domains"}),r.map(c=>{const l=typeof c=="string"?{value:c,label:c}:c;return s.jsx("option",{value:l.value,children:l.label??l.value},l.value)})]}),i!==void 0?s.jsx("span",{style:{color:a.textMuted,fontSize:10},children:i}):null]})}function K0(e,t){const n=Ao(t),r=e.some(o=>o.type!=="notebook"?!1:![o.ownerDomain,...o.usesDomains??[]].map(a=>a==null?void 0:a.trim()).filter(a=>!!a).some(a=>n.has(a)));return[...Jn(t).map(o=>o.value),...r?["uncategorized"]:[]]}function al(e,t,n="",r=[]){const o=t.trim().toLowerCase(),i=Ao(r);return Array.from(new Map(e.filter(a=>a.type==="notebook").map(a=>[a.path,a])).values()).filter(a=>{var u,h;const c=[a.ownerDomain,...a.usesDomains??[]].map(d=>d==null?void 0:d.trim()).filter(d=>!!d);return(!n||(n==="uncategorized"?!c.some(d=>i.has(d)):i.has(n)&&c.includes(n)))&&(!o||a.name.toLowerCase().includes(o)||a.path.toLowerCase().includes(o)||((u=a.ownerDomain)==null?void 0:u.toLowerCase().includes(o))||((h=a.usesDomains)==null?void 0:h.some(d=>d.toLowerCase().includes(o))))}).sort((a,c)=>a.name.localeCompare(c.name))}const ei=25;function cl(e){var t;return!!((t=e.relation)!=null&&t.trim())}function ll(e){return{name:e.relation,path:e.relation,columns:[],source:"database",objectType:e.resourceType==="source"?"dbt_source":"dbt_model",dbtUniqueId:e.uniqueId,dbtResourceType:e.resourceType,dbtSourcePath:e.sourcePath,governance:e.binding?{domain:e.binding.domain,owner:e.binding.owner,status:J0(e.binding.status)}:void 0}}function V0(e,t){const n=new Map(e.map(r=>[r.dbtUniqueId,r]));for(const r of t){const o=n.get(r.dbtUniqueId);n.set(r.dbtUniqueId,o?{...o,...r,columns:r.columns.length>0?r.columns:o.columns,expanded:o.expanded}:r)}return Array.from(n.values())}function H0(e,t){const n=new Map(t.map(i=>[i.name.toLowerCase(),i])),r=e.columns.map(i=>{var a;return{name:i.name,type:i.type??((a=n.get(i.name.toLowerCase()))==null?void 0:a.type)??""}}),o=new Set(r.map(i=>i.name.toLowerCase()));for(const i of t)o.has(i.name.toLowerCase())||r.push(i);return r}function G0(e){return e.split(".").filter(Boolean).at(-1)??e}function Q0(e){const t=e.split(".").filter(Boolean);return t.length>1?t.slice(0,-1).join("."):""}function J0(e){if(e==="draft"||e==="review"||e==="certified"||e==="deprecated"||e==="pending_recertification")return e}function Y0({t:e,search:t,onInsert:n}){const{dispatch:r}=et(),[o,i]=p.useState([]),[a,c]=p.useState(0),[l,u]=p.useState(null),[h,d]=p.useState(!0),[f,m]=p.useState(!1),[S,v]=p.useState(null),[b,w]=p.useState(new Set),[j,C]=p.useState(new Set),[x,E]=p.useState(new Set),[P,A]=p.useState({}),g=p.useRef(0),I=t.trim();p.useEffect(()=>{const _=++g.current,M=window.setTimeout(()=>{d(!0),v(null),B.getDbtModelInventory({q:I,limit:ei,physicalOnly:!0}).then(q=>{if(_!==g.current)return;const G=q.items.filter(cl).map(ll);i(G),c(q.total),u(q.nextCursor),w(new Set),C(new Set),A({}),r({type:"MERGE_SCHEMA_TABLES",tables:G})}).catch(q=>{_===g.current&&(i([]),c(0),u(null),v(q instanceof Error?q:new Error(String(q))))}).finally(()=>{_===g.current&&d(!1)})},180);return()=>window.clearTimeout(M)},[r,I]);const T=async()=>{if(l===null||f)return;const _=g.current;m(!0);try{const M=await B.getDbtModelInventory({q:I,cursor:l,limit:ei,physicalOnly:!0});if(_!==g.current)return;const q=M.items.filter(cl).map(ll);i(G=>V0(G,q)),c(M.total),u(M.nextCursor),r({type:"MERGE_SCHEMA_TABLES",tables:q})}catch(M){_===g.current&&v(M instanceof Error?M:new Error(String(M)))}finally{_===g.current&&m(!1)}},O=async _=>{const M=!b.has(_.dbtUniqueId);if(w(q=>{const G=new Set(q);return M?G.add(_.dbtUniqueId):G.delete(_.dbtUniqueId),G}),!(!M||j.has(_.dbtUniqueId)||x.has(_.dbtUniqueId))){E(q=>new Set(q).add(_.dbtUniqueId)),A(q=>{const G={...q};return delete G[_.dbtUniqueId],G});try{const q=await B.getDbtModelingNode(_.dbtUniqueId),J=q.columns.length===0||q.columns.some($=>!$.type)?await B.describeTable(_.path):[],H=H0(q,J),L={..._,columns:H};i($=>$.map(X=>X.dbtUniqueId===_.dbtUniqueId?L:X)),C($=>new Set($).add(_.dbtUniqueId)),r({type:"MERGE_SCHEMA_TABLES",tables:[L]})}catch(q){A(G=>({...G,[_.dbtUniqueId]:q instanceof Error?q.message:String(q)}))}finally{E(q=>{const G=new Set(q);return G.delete(_.dbtUniqueId),G})}}};return h?s.jsxs(cr,{t:e,children:[s.jsx(Un,{size:13,className:"dql-spin"})," Loading dbt database objects…"]}):S?s.jsx(X0,{error:S,t:e}):o.length===0?s.jsx(cr,{t:e,children:I?`No dbt models or sources match “${I}”.`:"No dbt database objects found. Compile the connected dbt project, then refresh this workspace."}):s.jsxs("div",{children:[s.jsxs("div",{style:{padding:"7px 10px",borderBottom:`1px solid ${e.cellBorder}`,color:e.textMuted,fontSize:10.5},children:["dbt scope · showing ",o.length.toLocaleString()," of ",a.toLocaleString()," object",a===1?"":"s"]}),o.map(_=>{const M=b.has(_.dbtUniqueId),q=x.has(_.dbtUniqueId),G=P[_.dbtUniqueId],J=G0(_.path),H=Q0(_.path);return s.jsxs("div",{children:[s.jsxs("div",{style:{...dl(e),alignItems:"flex-start"},children:[s.jsx("button",{type:"button",onClick:()=>void O(_),"aria-label":`${M?"Collapse":"Expand"} ${J}`,title:M?"Collapse columns":"Load columns",style:Z0(e),children:M?s.jsx(_a,{size:13}):s.jsx(Is,{size:13})}),s.jsxs("button",{type:"button",onClick:()=>n(`SELECT * FROM ${_.path} LIMIT 100`),title:`Insert a bounded SELECT from ${_.path}`,style:{flex:1,minWidth:0,border:"none",background:"transparent",cursor:"pointer",color:e.textPrimary,textAlign:"left",display:"grid",gap:2,padding:0,fontFamily:e.font},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0},children:[s.jsx(To,{size:12.5,color:e.accent,style:{flexShrink:0}}),s.jsx("strong",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontFamily:e.fontMono},children:J}),s.jsx("span",{style:{fontSize:8.5,color:e.textMuted,textTransform:"uppercase",letterSpacing:".04em",flexShrink:0},children:_.dbtResourceType}),j.has(_.dbtUniqueId)?s.jsx("span",{style:{fontSize:10,color:e.textMuted,flexShrink:0},children:_.columns.length}):null]}),H?s.jsx("span",{style:{paddingLeft:19,color:e.textMuted,fontSize:9.5,fontFamily:e.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:H}):null]})]}),M?s.jsxs("div",{children:[q?s.jsxs(cr,{t:e,compact:!0,children:[s.jsx(Un,{size:11,className:"dql-spin"})," Loading columns…"]}):null,!q&&G?s.jsx(cr,{t:e,compact:!0,children:"Columns unavailable. The relation can still be inserted and queried."}):null,!q&&!G&&j.has(_.dbtUniqueId)&&_.columns.length===0?s.jsx(cr,{t:e,compact:!0,children:"No columns are documented in dbt or visible from the selected connection."}):null,!q&&_.columns.map(L=>s.jsxs("button",{type:"button",onClick:()=>n(L.name),title:`Insert column ${L.name}`,style:{...dl(e),paddingLeft:34,gap:7},children:[s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11,fontFamily:e.fontMono,color:e.textSecondary},children:L.name}),s.jsx("span",{style:{fontSize:9.5,color:e.textMuted,flexShrink:0,fontFamily:e.fontMono},children:L.type||"unknown"})]},L.name))]}):null]},_.dbtUniqueId)}),l!==null?s.jsx("button",{type:"button",onClick:()=>void T(),disabled:f,style:{width:"calc(100% - 20px)",margin:"9px 10px 11px",padding:"7px 9px",borderRadius:6,border:`1px solid ${e.btnBorder}`,background:e.btnBg,color:e.textSecondary,cursor:f?"wait":"pointer",fontSize:10.5,fontFamily:e.font},children:f?"Loading…":`Load ${Math.min(ei,a-o.length).toLocaleString()} more`}):null,s.jsx("style",{children:".dql-spin { animation: dql-catalog-spin .8s linear infinite; } @keyframes dql-catalog-spin { to { transform: rotate(360deg); } }"})]})}function X0({error:e,t}){const n=e instanceof St?e:null,r=(n==null?void 0:n.code)==="DBT_FIRST_NOT_ENABLED"?"Connect and apply a dbt project in Settings to browse its database objects.":(n==null?void 0:n.code)==="DBT_MANIFEST_NOT_FOUND"?"The connected dbt manifest is missing. Run dbt parse or dbt build, then refresh.":"The dbt database catalog could not be loaded. Refresh after checking the dbt project setup.";return s.jsx(cr,{t,children:r})}function cr({t:e,compact:t=!1,children:n}){return s.jsx("div",{style:{padding:t?"6px 12px 6px 34px":"16px 12px",fontSize:t?10:11.5,color:e.textMuted,textAlign:t?"left":"center",display:"flex",alignItems:"center",justifyContent:t?"flex-start":"center",gap:6},children:n})}const dl=e=>({display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,boxSizing:"border-box",padding:"7px 10px",border:"none",borderBottom:`1px solid ${e.cellBorder}`,background:"transparent",cursor:"pointer",textAlign:"left",fontFamily:e.font,color:e.textPrimary}),Z0=e=>({border:"none",background:"transparent",cursor:"pointer",color:e.textMuted,display:"flex",padding:"1px 0 0",flexShrink:0}),ek=[{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 st(e){return String(e??"").trim()||"uncategorized"}function Rt(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 tk(e,t){return String((t==="dimension"||t==="time_dimension")&&e.reference||e.name)}function nk(e,t,n){const r=tk(e,t),o=st(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)}:{},...Rt(e).length>0?{semanticModelIds:Rt(e).join(",")}:{},...e.owner?{owner:String(e.owner)}:{},...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags.join(",")}:{}}}}function Ht(e,t,n,r,o){if(r.length===0)return null;const i=r.map(a=>nk(a,n,o)).sort((a,c)=>a.label.localeCompare(c.label)||a.id.localeCompare(c.id));return{id:e,label:t,kind:"group",count:i.length,meta:{provider:o,objectKind:n},children:i}}function ur(e){var t;return(t=e.children)!=null&&t.length?e.children.reduce((n,r)=>n+ur(r),0):1}function rk(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(u=>[u.name,u])),o=new Set(e.semanticModels.map(u=>u.name));for(const u of n)for(const h of Rt(u))o.add(h);const i=u=>{const h=r.get(u);if(h)return st(h.domain);const d=n.find(f=>Rt(f).includes(u));return st(d==null?void 0:d.domain)},a=new Set([...e.domains.map(st),...e.semanticModels.map(u=>st(u.domain)),...n.map(u=>st(u.domain))]),c=Array.from(a).sort((u,h)=>u.localeCompare(h)).flatMap(u=>{const d=Array.from(o).filter(x=>i(x)===u).sort((x,E)=>x.localeCompare(E)).flatMap(x=>{const E=r.get(x),P=ek.flatMap(({collection:g,kind:I,label:T})=>{const O=e[g].filter(M=>{const q=Rt(M);return q.length===1&&q[0]===x&&(g!=="dimensions"||!M.isTimeDimension)}),_=Ht(`group:${u}:${x}:${I}`,T,I,O,t);return _?[_]:[]});return P.length===0&&!E?[]:[{id:`semantic_model:${x}`,label:(E==null?void 0:E.label)||x,kind:"semantic_model",count:P.reduce((g,I)=>g+ur(I),0),meta:{provider:t,domain:u,cube:x,...E!=null&&E.table?{table:E.table}:{},...E!=null&&E.owner?{owner:E.owner}:{}},children:P}]}),f=e.metrics.filter(x=>st(x.domain)===u&&Rt(x).length>1),m=e.metrics.filter(x=>st(x.domain)===u&&Rt(x).length===0),S=[Ht(`group:${u}:unassigned-dimensions`,"Dimensions","dimension",e.dimensions.filter(x=>st(x.domain)===u&&Rt(x).length===0&&!x.isTimeDimension),t),Ht(`group:${u}:unassigned-time-dimensions`,"Time Dimensions","time_dimension",e.timeDimensions.filter(x=>st(x.domain)===u&&Rt(x).length===0),t),Ht(`group:${u}:unassigned-measures`,"Underlying measures","measure",e.measures.filter(x=>st(x.domain)===u&&Rt(x).length===0),t),Ht(`group:${u}:unassigned-entities`,"Entities","entity",e.entities.filter(x=>st(x.domain)===u&&Rt(x).length===0),t)].filter(x=>!!x),v=[...d],b=Ht(`group:${u}:cross-model-metrics`,"Cross-model metrics","metric",f,t);b&&v.push(b);const w=Ht(`group:${u}:unassigned-metrics`,"Unassigned metrics","metric",m,t);w&&v.push(w),S.length>0&&v.push({id:`group:${u}:unassigned-objects`,label:"Unassigned objects",kind:"group",count:S.reduce((x,E)=>x+ur(E),0),meta:{provider:t,domain:u},children:S});const j=Ht(`group:${u}:hierarchies`,"Hierarchies","hierarchy",e.hierarchies.filter(x=>st(x.domain)===u),t);j&&v.push(j);const C=Ht(`group:${u}:saved-queries`,"Saved Queries","saved_query",e.savedQueries.filter(x=>st(x.domain)===u),t);return C&&v.push(C),v.length===0?[]:[{id:`domain:${t}:${u}`,label:u,kind:"domain",count:v.reduce((x,E)=>x+ur(E),0),meta:{provider:t,domain:u},children:v}]});if(c.length===0)return null;const l=c.flatMap(u=>u.label==="uncategorized"?u.children??[]:[u]);return{id:"root:semantic",label:"Semantic Layer",kind:"group",children:[{id:`provider:${t}`,label:t.toUpperCase(),kind:"provider",count:l.reduce((u,h)=>u+ur(h),0),meta:{provider:t},children:l}]}}function ok(e,t,n,r){const o=i=>{var c,l;if(!((c=i.children)!=null&&c.length)){if(i.kind==="metric")return{...i};if(i.kind==="dimension"||i.kind==="time_dimension"){if(t===0||r!=="ready"||!n)return null;const u=String(((l=i.meta)==null?void 0:l.reference)||i.id.slice(i.id.indexOf(":")+1));return n.has(u)?{...i}:null}return null}const a=i.children.map(o).filter(u=>!!u);return a.length===0?null:{...i,count:a.reduce((u,h)=>u+ur(h),0),children:a}};return o(e)??{...e,children:[]}}const ul=[{id:"notebooks",label:"Notebooks",icon:Pa},{id:"semantic",label:"Semantic",icon:bp},{id:"database",label:"Database",icon:To},{id:"blocks",label:"Blocks",icon:Oa}],sk={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 ik({defaultTab:e,onOpenFile:t,tabs:n,onInsertText:r,onSemanticCompose:o,blockDomain:i="",onBlockDomainChange:a,onNewBlock:c,onOpenBlock:l,onDeleteBlock:u,blockLibraryRefreshKey:h=0,footer:d,footerStatus:f="ready",onCollapse:m}){var I;const{state:S,dispatch:v}=et(),b=Qe[S.themeMode],w=n?n.map(T=>ul.find(O=>O.id===T)).filter(T=>!!T):ul,[j,C]=p.useState(e??((I=w[0])==null?void 0:I.id)??"notebooks"),[x,E]=p.useState(""),[P,A]=p.useState("");p.useEffect(()=>{e&&C(e)},[e]);const g=r??(T=>{Hw(T)||v({type:"ADD_CELL",cell:Ra("sql",T)})});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",minHeight:0,background:b.cellBg,fontFamily:b.font},children:[s.jsxs("div",{style:{display:"flex",gap:2,padding:"6px 6px 0",borderBottom:`1px solid ${b.headerBorder}`},children:[w.map(({id:T,label:O,icon:_})=>{const M=j===T;return s.jsxs("button",{type:"button",onClick:()=>C(T),title:O,style:{flex:w.length>3?"1 1 auto":1,minWidth:0,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,border:"none",borderBottom:`2px solid ${M?b.accent:"transparent"}`,background:"transparent",color:M?b.accent:b.textMuted,cursor:"pointer",fontSize:11,fontWeight:700,padding:"6px 3px 7px"},children:[s.jsx(_,{size:13,style:{flexShrink:0}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:O})]},T)}),m?s.jsx("button",{type:"button",onClick:m,title:"Collapse explorer",style:{border:"none",background:"transparent",color:b.textMuted,cursor:"pointer",fontSize:13,padding:"0 6px",flexShrink:0},children:"‹"}):null]}),j==="notebooks"?s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${b.headerBorder}`,display:"flex",gap:6},children:[s.jsxs("div",{style:{position:"relative",flex:1},children:[s.jsx(Hc,{size:12,style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:b.textMuted}}),s.jsx("input",{value:x,onChange:T=>E(T.target.value),placeholder:"Search notebooks…","aria-label":"Search notebooks",style:{width:"100%",boxSizing:"border-box",background:b.inputBg,border:`1px solid ${b.inputBorder}`,borderRadius:6,color:b.textPrimary,fontSize:12,fontFamily:b.font,padding:"6px 8px 6px 26px",outline:"none"}})]}),s.jsx("button",{type:"button",onClick:()=>v({type:"OPEN_NEW_NOTEBOOK_MODAL"}),title:"Create notebook","aria-label":"Create notebook",style:{width:28,height:28,flexShrink:0,borderRadius:7,border:`1px solid ${b.accent}55`,background:"var(--accent-dim)",color:b.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:s.jsx(vS,{size:14,strokeWidth:2,"aria-hidden":"true"})})]}):s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${b.headerBorder}`,display:"flex",gap:6},children:[s.jsxs("div",{style:{position:"relative",flex:1},children:[s.jsx(Hc,{size:12,style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:b.textMuted}}),s.jsx("input",{value:x,onChange:T=>E(T.target.value),placeholder:`Search ${j}…`,style:{width:"100%",boxSizing:"border-box",background:b.inputBg,border:`1px solid ${b.inputBorder}`,borderRadius:6,color:b.textPrimary,fontSize:12,fontFamily:b.font,padding:"6px 8px 6px 26px",outline:"none"}})]}),c?s.jsx("button",{type:"button",onClick:c,title:"New block",style:{width:28,height:28,flexShrink:0,borderRadius:6,border:`1px solid ${b.btnBorder}`,background:b.btnBg,color:b.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:s.jsx(OS,{size:14,strokeWidth:2})}):null]}),s.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:[j==="notebooks"&&t&&s.jsx(ak,{t:b,onOpenFile:t,search:x,domain:P,onDomainChange:A}),j==="semantic"&&s.jsx(uk,{t:b,search:x,onInsert:g,notebookMode:!r||!!o,onSemanticCompose:o}),j==="database"&&s.jsx(Y0,{t:b,search:x,onInsert:g}),j==="blocks"&&s.jsx(pk,{t:b,search:x,domain:i,onDomainChange:a,onOpenBlock:l,onDeleteBlock:u,refreshKey:h})]}),d?s.jsxs("div",{style:{padding:"9px 12px",borderTop:`1px solid ${b.headerBorder}`,fontSize:10.5,color:b.textMuted,display:"flex",alignItems:"center",gap:6,fontFamily:b.font},children:[s.jsx("span",{style:{width:6,height:6,borderRadius:999,background:f==="ready"?"var(--status-success)":"var(--status-warning)",flexShrink:0}}),s.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d})]}):null]})}const zp=(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 hr({text:e,t}){return s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:t.textMuted,textAlign:"center"},children:e})}function ak({t:e,onOpenFile:t,search:n,domain:r,onDomainChange:o}){var P;const{state:i,dispatch:a}=et(),[c,l]=p.useState(null),[u,h]=p.useState(!1),[d,f]=p.useState(null),m=K0(i.files,i.authoredDomains),S=m.includes(r)?r:"",b=[...Jn(i.authoredDomains).filter(A=>m.includes(A.value)),...m.includes("uncategorized")?[{value:"uncategorized",label:"Unassigned"}]:[]],w=al(i.files,"",S,i.authoredDomains),j=al(i.files,n,S,i.authoredDomains),C=U0(j,"notebooks"),x=S==="uncategorized"?"unassigned":S||"all domains",E=async()=>{if(c){h(!0),f(null);try{const A=await B.deleteNotebook(c.path);if(!A.ok){f(A.error??"Could not delete this notebook.");return}a({type:"FILE_REMOVED",path:c.path}),l(null)}catch(A){f(A instanceof Error?A.message:String(A))}finally{h(!1)}}};return s.jsxs("div",{children:[s.jsx(Fp,{id:"notebook-domain-filter",ariaLabel:"Notebook domain",value:S,options:b,onChange:o,summary:s.jsxs(s.Fragment,{children:[j.length," notebook",j.length===1?"":"s"," · ",x]}),t:e}),j.length===0?s.jsx(hr,{text:w.length===0?S?`No notebooks are related to ${x} yet.`:"No notebooks yet. Use the notebook icon above to create one.":`No ${x} notebooks match “${n.trim()}”.`,t:e}):s.jsx(qp,{nodes:C,activePath:(P=i.activeFile)==null?void 0:P.path,onOpenFile:t,onDelete:A=>{f(null),l(A)},t:e}),s.jsx("style",{children:`
431
+ `)}function N0(e){const t=e==null?void 0:e.trim();if(!(!t||t==="uncategorized"||t==="_uncategorized"))return t}function zr(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function B0(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 F0(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Fp(e){return Array.isArray(e)?`[${e.map(Fp).join(", ")}]`:typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":ze(String(e??""))}function ze(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function al(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:ze(e)}function z0(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 L0({name:i,status:"draft",metrics:n,dimensions:r}).trimEnd()}function q0(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 U0(e,t){var o;const n={path:"",folders:new Map,blocks:[]};for(const i of e){const a=((o=i.domain)==null?void 0:o.trim())||"uncategorized",l=q0(i.path,t||a).split("/").filter(Boolean),u=t?l.slice(0,-1):[a,...l.slice(0,-1)];let h=n;for(const d of u){const f=[h.path,d].filter(Boolean).join("/");let m=h.folders.get(d);m||(m={name:d,path:f,folders:new Map,blocks:[]},h.folders.set(d,m)),h=m}h.blocks.push(i)}const r=i=>[...Array.from(i.folders.values()).sort((a,c)=>a.name.localeCompare(c.name)).map(a=>({kind:"folder",name:a.name,path:a.path,children:r(a)})),...i.blocks.sort((a,c)=>a.name.localeCompare(c.name)).map(a=>({kind:"block",block:a}))];return r(n)}function W0(e,t){const n={path:"",folders:new Map,files:[]};for(const o of e){const i=K0(o,t);let a=n;for(const c of i){const l=[a.path,c].filter(Boolean).join("/");let u=a.folders.get(c);u||(u={name:c,path:l,folders:new Map,files:[]},a.folders.set(c,u)),a=u}a.files.push(o)}const r=o=>[...Array.from(o.folders.values()).sort((i,a)=>i.name.localeCompare(a.name)).map(i=>({kind:"folder",name:i.name,path:i.path,children:r(i)})),...o.files.sort((i,a)=>i.name.localeCompare(a.name)).map(i=>({kind:"file",file:i}))];return r(n)}function K0(e,t){const n=e.path.replace(/\\/g,"/").split("/").filter(Boolean);if(n[0]==="domains"){const i=["notebooks","workbooks"],a=n.findIndex((c,l)=>l>0&&i.includes(c));if(a>0)return["Domains",...n.slice(1,a),...n.slice(a+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(a=>a.trim()).filter(Boolean),...o]:["Project",...o]}function zp({id:e,ariaLabel:t,value:n,options:r,onChange:o,summary:i,t:a}){return s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${a.headerBorder}`,display:"grid",gap:5},children:[s.jsx("label",{htmlFor:e,style:{color:a.textMuted,fontSize:9,fontWeight:750,letterSpacing:".06em",textTransform:"uppercase"},children:"Domain"}),s.jsxs("select",{id:e,"aria-label":t,value:n,onChange:c=>o(c.target.value),style:{width:"100%",background:a.inputBg,border:`1px solid ${a.inputBorder}`,borderRadius:6,color:a.textPrimary,fontFamily:a.font,fontSize:12,padding:"7px 8px"},children:[s.jsx("option",{value:"",children:"All domains"}),r.map(c=>{const l=typeof c=="string"?{value:c,label:c}:c;return s.jsx("option",{value:l.value,children:l.label??l.value},l.value)})]}),i!==void 0?s.jsx("span",{style:{color:a.textMuted,fontSize:10},children:i}):null]})}function V0(e,t){const n=Ao(t),r=e.some(o=>o.type!=="notebook"?!1:![o.ownerDomain,...o.usesDomains??[]].map(a=>a==null?void 0:a.trim()).filter(a=>!!a).some(a=>n.has(a)));return[...Jn(t).map(o=>o.value),...r?["uncategorized"]:[]]}function cl(e,t,n="",r=[]){const o=t.trim().toLowerCase(),i=Ao(r);return Array.from(new Map(e.filter(a=>a.type==="notebook").map(a=>[a.path,a])).values()).filter(a=>{var u,h;const c=[a.ownerDomain,...a.usesDomains??[]].map(d=>d==null?void 0:d.trim()).filter(d=>!!d);return(!n||(n==="uncategorized"?!c.some(d=>i.has(d)):i.has(n)&&c.includes(n)))&&(!o||a.name.toLowerCase().includes(o)||a.path.toLowerCase().includes(o)||((u=a.ownerDomain)==null?void 0:u.toLowerCase().includes(o))||((h=a.usesDomains)==null?void 0:h.some(d=>d.toLowerCase().includes(o))))}).sort((a,c)=>a.name.localeCompare(c.name))}const ei=25;function ll(e){var t;return!!((t=e.relation)!=null&&t.trim())}function dl(e){return{name:e.relation,path:e.relation,columns:[],source:"database",objectType:e.resourceType==="source"?"dbt_source":"dbt_model",dbtUniqueId:e.uniqueId,dbtResourceType:e.resourceType,dbtSourcePath:e.sourcePath,governance:e.binding?{domain:e.binding.domain,owner:e.binding.owner,status:Y0(e.binding.status)}:void 0}}function H0(e,t){const n=new Map(e.map(r=>[r.dbtUniqueId,r]));for(const r of t){const o=n.get(r.dbtUniqueId);n.set(r.dbtUniqueId,o?{...o,...r,columns:r.columns.length>0?r.columns:o.columns,expanded:o.expanded}:r)}return Array.from(n.values())}function G0(e,t){const n=new Map(t.map(i=>[i.name.toLowerCase(),i])),r=e.columns.map(i=>{var a;return{name:i.name,type:i.type??((a=n.get(i.name.toLowerCase()))==null?void 0:a.type)??""}}),o=new Set(r.map(i=>i.name.toLowerCase()));for(const i of t)o.has(i.name.toLowerCase())||r.push(i);return r}function Q0(e){return e.split(".").filter(Boolean).at(-1)??e}function J0(e){const t=e.split(".").filter(Boolean);return t.length>1?t.slice(0,-1).join("."):""}function Y0(e){if(e==="draft"||e==="review"||e==="certified"||e==="deprecated"||e==="pending_recertification")return e}function X0({t:e,search:t,onInsert:n}){const{dispatch:r}=et(),[o,i]=p.useState([]),[a,c]=p.useState(0),[l,u]=p.useState(null),[h,d]=p.useState(!0),[f,m]=p.useState(!1),[S,v]=p.useState(null),[b,w]=p.useState(new Set),[j,C]=p.useState(new Set),[x,E]=p.useState(new Set),[P,A]=p.useState({}),g=p.useRef(0),I=t.trim();p.useEffect(()=>{const _=++g.current,M=window.setTimeout(()=>{d(!0),v(null),B.getDbtModelInventory({q:I,limit:ei,physicalOnly:!0}).then(q=>{if(_!==g.current)return;const G=q.items.filter(ll).map(dl);i(G),c(q.total),u(q.nextCursor),w(new Set),C(new Set),A({}),r({type:"MERGE_SCHEMA_TABLES",tables:G})}).catch(q=>{_===g.current&&(i([]),c(0),u(null),v(q instanceof Error?q:new Error(String(q))))}).finally(()=>{_===g.current&&d(!1)})},180);return()=>window.clearTimeout(M)},[r,I]);const T=async()=>{if(l===null||f)return;const _=g.current;m(!0);try{const M=await B.getDbtModelInventory({q:I,cursor:l,limit:ei,physicalOnly:!0});if(_!==g.current)return;const q=M.items.filter(ll).map(dl);i(G=>H0(G,q)),c(M.total),u(M.nextCursor),r({type:"MERGE_SCHEMA_TABLES",tables:q})}catch(M){_===g.current&&v(M instanceof Error?M:new Error(String(M)))}finally{_===g.current&&m(!1)}},O=async _=>{const M=!b.has(_.dbtUniqueId);if(w(q=>{const G=new Set(q);return M?G.add(_.dbtUniqueId):G.delete(_.dbtUniqueId),G}),!(!M||j.has(_.dbtUniqueId)||x.has(_.dbtUniqueId))){E(q=>new Set(q).add(_.dbtUniqueId)),A(q=>{const G={...q};return delete G[_.dbtUniqueId],G});try{const q=await B.getDbtModelingNode(_.dbtUniqueId),J=q.columns.length===0||q.columns.some($=>!$.type)?await B.describeTable(_.path):[],H=G0(q,J),L={..._,columns:H};i($=>$.map(X=>X.dbtUniqueId===_.dbtUniqueId?L:X)),C($=>new Set($).add(_.dbtUniqueId)),r({type:"MERGE_SCHEMA_TABLES",tables:[L]})}catch(q){A(G=>({...G,[_.dbtUniqueId]:q instanceof Error?q.message:String(q)}))}finally{E(q=>{const G=new Set(q);return G.delete(_.dbtUniqueId),G})}}};return h?s.jsxs(cr,{t:e,children:[s.jsx(Un,{size:13,className:"dql-spin"})," Loading dbt database objects…"]}):S?s.jsx(Z0,{error:S,t:e}):o.length===0?s.jsx(cr,{t:e,children:I?`No dbt models or sources match “${I}”.`:"No dbt database objects found. Compile the connected dbt project, then refresh this workspace."}):s.jsxs("div",{children:[s.jsxs("div",{style:{padding:"7px 10px",borderBottom:`1px solid ${e.cellBorder}`,color:e.textMuted,fontSize:10.5},children:["dbt scope · showing ",o.length.toLocaleString()," of ",a.toLocaleString()," object",a===1?"":"s"]}),o.map(_=>{const M=b.has(_.dbtUniqueId),q=x.has(_.dbtUniqueId),G=P[_.dbtUniqueId],J=Q0(_.path),H=J0(_.path);return s.jsxs("div",{children:[s.jsxs("div",{style:{...ul(e),alignItems:"flex-start"},children:[s.jsx("button",{type:"button",onClick:()=>void O(_),"aria-label":`${M?"Collapse":"Expand"} ${J}`,title:M?"Collapse columns":"Load columns",style:ek(e),children:M?s.jsx(_a,{size:13}):s.jsx(Is,{size:13})}),s.jsxs("button",{type:"button",onClick:()=>n(`SELECT * FROM ${_.path} LIMIT 100`),title:`Insert a bounded SELECT from ${_.path}`,style:{flex:1,minWidth:0,border:"none",background:"transparent",cursor:"pointer",color:e.textPrimary,textAlign:"left",display:"grid",gap:2,padding:0,fontFamily:e.font},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0},children:[s.jsx(To,{size:12.5,color:e.accent,style:{flexShrink:0}}),s.jsx("strong",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5,fontFamily:e.fontMono},children:J}),s.jsx("span",{style:{fontSize:8.5,color:e.textMuted,textTransform:"uppercase",letterSpacing:".04em",flexShrink:0},children:_.dbtResourceType}),j.has(_.dbtUniqueId)?s.jsx("span",{style:{fontSize:10,color:e.textMuted,flexShrink:0},children:_.columns.length}):null]}),H?s.jsx("span",{style:{paddingLeft:19,color:e.textMuted,fontSize:9.5,fontFamily:e.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:H}):null]})]}),M?s.jsxs("div",{children:[q?s.jsxs(cr,{t:e,compact:!0,children:[s.jsx(Un,{size:11,className:"dql-spin"})," Loading columns…"]}):null,!q&&G?s.jsx(cr,{t:e,compact:!0,children:"Columns unavailable. The relation can still be inserted and queried."}):null,!q&&!G&&j.has(_.dbtUniqueId)&&_.columns.length===0?s.jsx(cr,{t:e,compact:!0,children:"No columns are documented in dbt or visible from the selected connection."}):null,!q&&_.columns.map(L=>s.jsxs("button",{type:"button",onClick:()=>n(L.name),title:`Insert column ${L.name}`,style:{...ul(e),paddingLeft:34,gap:7},children:[s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11,fontFamily:e.fontMono,color:e.textSecondary},children:L.name}),s.jsx("span",{style:{fontSize:9.5,color:e.textMuted,flexShrink:0,fontFamily:e.fontMono},children:L.type||"unknown"})]},L.name))]}):null]},_.dbtUniqueId)}),l!==null?s.jsx("button",{type:"button",onClick:()=>void T(),disabled:f,style:{width:"calc(100% - 20px)",margin:"9px 10px 11px",padding:"7px 9px",borderRadius:6,border:`1px solid ${e.btnBorder}`,background:e.btnBg,color:e.textSecondary,cursor:f?"wait":"pointer",fontSize:10.5,fontFamily:e.font},children:f?"Loading…":`Load ${Math.min(ei,a-o.length).toLocaleString()} more`}):null,s.jsx("style",{children:".dql-spin { animation: dql-catalog-spin .8s linear infinite; } @keyframes dql-catalog-spin { to { transform: rotate(360deg); } }"})]})}function Z0({error:e,t}){const n=e instanceof St?e:null,r=(n==null?void 0:n.code)==="DBT_FIRST_NOT_ENABLED"?"Connect and apply a dbt project in Settings to browse its database objects.":(n==null?void 0:n.code)==="DBT_MANIFEST_NOT_FOUND"?"The connected dbt manifest is missing. Run dbt parse or dbt build, then refresh.":"The dbt database catalog could not be loaded. Refresh after checking the dbt project setup.";return s.jsx(cr,{t,children:r})}function cr({t:e,compact:t=!1,children:n}){return s.jsx("div",{style:{padding:t?"6px 12px 6px 34px":"16px 12px",fontSize:t?10:11.5,color:e.textMuted,textAlign:t?"left":"center",display:"flex",alignItems:"center",justifyContent:t?"flex-start":"center",gap:6},children:n})}const ul=e=>({display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,boxSizing:"border-box",padding:"7px 10px",border:"none",borderBottom:`1px solid ${e.cellBorder}`,background:"transparent",cursor:"pointer",textAlign:"left",fontFamily:e.font,color:e.textPrimary}),ek=e=>({border:"none",background:"transparent",cursor:"pointer",color:e.textMuted,display:"flex",padding:"1px 0 0",flexShrink:0}),tk=[{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 st(e){return String(e??"").trim()||"uncategorized"}function Rt(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 nk(e,t){return String((t==="dimension"||t==="time_dimension")&&e.reference||e.name)}function rk(e,t,n){const r=nk(e,t),o=st(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)}:{},...Rt(e).length>0?{semanticModelIds:Rt(e).join(",")}:{},...e.owner?{owner:String(e.owner)}:{},...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags.join(",")}:{}}}}function Ht(e,t,n,r,o){if(r.length===0)return null;const i=r.map(a=>rk(a,n,o)).sort((a,c)=>a.label.localeCompare(c.label)||a.id.localeCompare(c.id));return{id:e,label:t,kind:"group",count:i.length,meta:{provider:o,objectKind:n},children:i}}function ur(e){var t;return(t=e.children)!=null&&t.length?e.children.reduce((n,r)=>n+ur(r),0):1}function ok(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(u=>[u.name,u])),o=new Set(e.semanticModels.map(u=>u.name));for(const u of n)for(const h of Rt(u))o.add(h);const i=u=>{const h=r.get(u);if(h)return st(h.domain);const d=n.find(f=>Rt(f).includes(u));return st(d==null?void 0:d.domain)},a=new Set([...e.domains.map(st),...e.semanticModels.map(u=>st(u.domain)),...n.map(u=>st(u.domain))]),c=Array.from(a).sort((u,h)=>u.localeCompare(h)).flatMap(u=>{const d=Array.from(o).filter(x=>i(x)===u).sort((x,E)=>x.localeCompare(E)).flatMap(x=>{const E=r.get(x),P=tk.flatMap(({collection:g,kind:I,label:T})=>{const O=e[g].filter(M=>{const q=Rt(M);return q.length===1&&q[0]===x&&(g!=="dimensions"||!M.isTimeDimension)}),_=Ht(`group:${u}:${x}:${I}`,T,I,O,t);return _?[_]:[]});return P.length===0&&!E?[]:[{id:`semantic_model:${x}`,label:(E==null?void 0:E.label)||x,kind:"semantic_model",count:P.reduce((g,I)=>g+ur(I),0),meta:{provider:t,domain:u,cube:x,...E!=null&&E.table?{table:E.table}:{},...E!=null&&E.owner?{owner:E.owner}:{}},children:P}]}),f=e.metrics.filter(x=>st(x.domain)===u&&Rt(x).length>1),m=e.metrics.filter(x=>st(x.domain)===u&&Rt(x).length===0),S=[Ht(`group:${u}:unassigned-dimensions`,"Dimensions","dimension",e.dimensions.filter(x=>st(x.domain)===u&&Rt(x).length===0&&!x.isTimeDimension),t),Ht(`group:${u}:unassigned-time-dimensions`,"Time Dimensions","time_dimension",e.timeDimensions.filter(x=>st(x.domain)===u&&Rt(x).length===0),t),Ht(`group:${u}:unassigned-measures`,"Underlying measures","measure",e.measures.filter(x=>st(x.domain)===u&&Rt(x).length===0),t),Ht(`group:${u}:unassigned-entities`,"Entities","entity",e.entities.filter(x=>st(x.domain)===u&&Rt(x).length===0),t)].filter(x=>!!x),v=[...d],b=Ht(`group:${u}:cross-model-metrics`,"Cross-model metrics","metric",f,t);b&&v.push(b);const w=Ht(`group:${u}:unassigned-metrics`,"Unassigned metrics","metric",m,t);w&&v.push(w),S.length>0&&v.push({id:`group:${u}:unassigned-objects`,label:"Unassigned objects",kind:"group",count:S.reduce((x,E)=>x+ur(E),0),meta:{provider:t,domain:u},children:S});const j=Ht(`group:${u}:hierarchies`,"Hierarchies","hierarchy",e.hierarchies.filter(x=>st(x.domain)===u),t);j&&v.push(j);const C=Ht(`group:${u}:saved-queries`,"Saved Queries","saved_query",e.savedQueries.filter(x=>st(x.domain)===u),t);return C&&v.push(C),v.length===0?[]:[{id:`domain:${t}:${u}`,label:u,kind:"domain",count:v.reduce((x,E)=>x+ur(E),0),meta:{provider:t,domain:u},children:v}]});if(c.length===0)return null;const l=c.flatMap(u=>u.label==="uncategorized"?u.children??[]:[u]);return{id:"root:semantic",label:"Semantic Layer",kind:"group",children:[{id:`provider:${t}`,label:t.toUpperCase(),kind:"provider",count:l.reduce((u,h)=>u+ur(h),0),meta:{provider:t},children:l}]}}function sk(e,t,n,r){const o=i=>{var c,l;if(!((c=i.children)!=null&&c.length)){if(i.kind==="metric")return{...i};if(i.kind==="dimension"||i.kind==="time_dimension"){if(t===0||r!=="ready"||!n)return null;const u=String(((l=i.meta)==null?void 0:l.reference)||i.id.slice(i.id.indexOf(":")+1));return n.has(u)?{...i}:null}return null}const a=i.children.map(o).filter(u=>!!u);return a.length===0?null:{...i,count:a.reduce((u,h)=>u+ur(h),0),children:a}};return o(e)??{...e,children:[]}}const pl=[{id:"notebooks",label:"Notebooks",icon:Pa},{id:"semantic",label:"Semantic",icon:xp},{id:"database",label:"Database",icon:To},{id:"blocks",label:"Blocks",icon:Oa}],ik={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 ak({defaultTab:e,onOpenFile:t,tabs:n,onInsertText:r,onSemanticCompose:o,blockDomain:i="",onBlockDomainChange:a,onNewBlock:c,onOpenBlock:l,onDeleteBlock:u,blockLibraryRefreshKey:h=0,footer:d,footerStatus:f="ready",onCollapse:m}){var I;const{state:S,dispatch:v}=et(),b=Qe[S.themeMode],w=n?n.map(T=>pl.find(O=>O.id===T)).filter(T=>!!T):pl,[j,C]=p.useState(e??((I=w[0])==null?void 0:I.id)??"notebooks"),[x,E]=p.useState(""),[P,A]=p.useState("");p.useEffect(()=>{e&&C(e)},[e]);const g=r??(T=>{Gw(T)||v({type:"ADD_CELL",cell:Ra("sql",T)})});return s.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",minHeight:0,background:b.cellBg,fontFamily:b.font},children:[s.jsxs("div",{style:{display:"flex",gap:2,padding:"6px 6px 0",borderBottom:`1px solid ${b.headerBorder}`},children:[w.map(({id:T,label:O,icon:_})=>{const M=j===T;return s.jsxs("button",{type:"button",onClick:()=>C(T),title:O,style:{flex:w.length>3?"1 1 auto":1,minWidth:0,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,border:"none",borderBottom:`2px solid ${M?b.accent:"transparent"}`,background:"transparent",color:M?b.accent:b.textMuted,cursor:"pointer",fontSize:11,fontWeight:700,padding:"6px 3px 7px"},children:[s.jsx(_,{size:13,style:{flexShrink:0}}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:O})]},T)}),m?s.jsx("button",{type:"button",onClick:m,title:"Collapse explorer",style:{border:"none",background:"transparent",color:b.textMuted,cursor:"pointer",fontSize:13,padding:"0 6px",flexShrink:0},children:"‹"}):null]}),j==="notebooks"?s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${b.headerBorder}`,display:"flex",gap:6},children:[s.jsxs("div",{style:{position:"relative",flex:1},children:[s.jsx(Hc,{size:12,style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:b.textMuted}}),s.jsx("input",{value:x,onChange:T=>E(T.target.value),placeholder:"Search notebooks…","aria-label":"Search notebooks",style:{width:"100%",boxSizing:"border-box",background:b.inputBg,border:`1px solid ${b.inputBorder}`,borderRadius:6,color:b.textPrimary,fontSize:12,fontFamily:b.font,padding:"6px 8px 6px 26px",outline:"none"}})]}),s.jsx("button",{type:"button",onClick:()=>v({type:"OPEN_NEW_NOTEBOOK_MODAL"}),title:"Create notebook","aria-label":"Create notebook",style:{width:28,height:28,flexShrink:0,borderRadius:7,border:`1px solid ${b.accent}55`,background:"var(--accent-dim)",color:b.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:s.jsx(SS,{size:14,strokeWidth:2,"aria-hidden":"true"})})]}):s.jsxs("div",{style:{padding:8,borderBottom:`1px solid ${b.headerBorder}`,display:"flex",gap:6},children:[s.jsxs("div",{style:{position:"relative",flex:1},children:[s.jsx(Hc,{size:12,style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:b.textMuted}}),s.jsx("input",{value:x,onChange:T=>E(T.target.value),placeholder:`Search ${j}…`,style:{width:"100%",boxSizing:"border-box",background:b.inputBg,border:`1px solid ${b.inputBorder}`,borderRadius:6,color:b.textPrimary,fontSize:12,fontFamily:b.font,padding:"6px 8px 6px 26px",outline:"none"}})]}),c?s.jsx("button",{type:"button",onClick:c,title:"New block",style:{width:28,height:28,flexShrink:0,borderRadius:6,border:`1px solid ${b.btnBorder}`,background:b.btnBg,color:b.accent,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},children:s.jsx(_S,{size:14,strokeWidth:2})}):null]}),s.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:[j==="notebooks"&&t&&s.jsx(ck,{t:b,onOpenFile:t,search:x,domain:P,onDomainChange:A}),j==="semantic"&&s.jsx(pk,{t:b,search:x,onInsert:g,notebookMode:!r||!!o,onSemanticCompose:o}),j==="database"&&s.jsx(X0,{t:b,search:x,onInsert:g}),j==="blocks"&&s.jsx(fk,{t:b,search:x,domain:i,onDomainChange:a,onOpenBlock:l,onDeleteBlock:u,refreshKey:h})]}),d?s.jsxs("div",{style:{padding:"9px 12px",borderTop:`1px solid ${b.headerBorder}`,fontSize:10.5,color:b.textMuted,display:"flex",alignItems:"center",gap:6,fontFamily:b.font},children:[s.jsx("span",{style:{width:6,height:6,borderRadius:999,background:f==="ready"?"var(--status-success)":"var(--status-warning)",flexShrink:0}}),s.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d})]}):null]})}const qp=(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 hr({text:e,t}){return s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:t.textMuted,textAlign:"center"},children:e})}function ck({t:e,onOpenFile:t,search:n,domain:r,onDomainChange:o}){var P;const{state:i,dispatch:a}=et(),[c,l]=p.useState(null),[u,h]=p.useState(!1),[d,f]=p.useState(null),m=V0(i.files,i.authoredDomains),S=m.includes(r)?r:"",b=[...Jn(i.authoredDomains).filter(A=>m.includes(A.value)),...m.includes("uncategorized")?[{value:"uncategorized",label:"Unassigned"}]:[]],w=cl(i.files,"",S,i.authoredDomains),j=cl(i.files,n,S,i.authoredDomains),C=W0(j,"notebooks"),x=S==="uncategorized"?"unassigned":S||"all domains",E=async()=>{if(c){h(!0),f(null);try{const A=await B.deleteNotebook(c.path);if(!A.ok){f(A.error??"Could not delete this notebook.");return}a({type:"FILE_REMOVED",path:c.path}),l(null)}catch(A){f(A instanceof Error?A.message:String(A))}finally{h(!1)}}};return s.jsxs("div",{children:[s.jsx(zp,{id:"notebook-domain-filter",ariaLabel:"Notebook domain",value:S,options:b,onChange:o,summary:s.jsxs(s.Fragment,{children:[j.length," notebook",j.length===1?"":"s"," · ",x]}),t:e}),j.length===0?s.jsx(hr,{text:w.length===0?S?`No notebooks are related to ${x} yet.`:"No notebooks yet. Use the notebook icon above to create one.":`No ${x} notebooks match “${n.trim()}”.`,t:e}):s.jsx(Up,{nodes:C,activePath:(P=i.activeFile)==null?void 0:P.path,onOpenFile:t,onDelete:A=>{f(null),l(A)},t:e}),s.jsx("style",{children:`
432
432
  .dql-nb-delete { opacity: 0; transition: opacity .12s, color .12s, background .12s, border-color .12s; }
433
433
  .dql-nb-row:hover .dql-nb-delete { opacity: 1; }
434
434
  .dql-nb-delete:hover { color: ${e.error} !important; background: ${e.error}12 !important; border-color: ${e.error}44 !important; }
435
435
  .dql-nb-delete:focus-visible { opacity: 1; }
436
- `}),c?s.jsx(dk,{file:c,t:e,busy:u,error:d,onCancel:()=>{l(null),f(null)},onConfirm:()=>void E()}):null]})}function qp({nodes:e,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i=0}){return s.jsx(s.Fragment,{children:e.map(a=>a.kind==="folder"?s.jsx(ck,{node:a,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i},`notebook-folder:${a.path}`):s.jsx(lk,{file:a.file,active:t===a.file.path,onOpenFile:n,onDelete:r,t:o,depth:i},a.file.path))})}function ck({node:e,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i}){const[a,c]=p.useState(!0);return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>c(l=>!l),"aria-expanded":a,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(Is,{size:11,style:{transform:a?"rotate(90deg)":void 0,flexShrink:0}}),a?s.jsx(yp,{size:13}):s.jsx(ro,{size:13}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]}),a?s.jsx(qp,{nodes:e.children,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i+1}):null]})}function lk({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:{...zp(o,t),paddingLeft:10+i*14,paddingRight:30},title:`${e.path}${e.ownerDomain?` · Owner domain: ${e.ownerDomain}`:""}`,children:[s.jsx(Pa,{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:a=>{a.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(vp,{size:12})})]})}function dk({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:a=>a.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:Re(t,{variant:"secondary",size:"md",disabled:n}),children:"Cancel"}),s.jsx("button",{type:"button",onClick:i,disabled:n,style:Re(t,{variant:"danger",size:"md",disabled:n}),children:n?"Deleting…":"Delete notebook"})]})]})})}function uk({t:e,search:t,onInsert:n,notebookMode:r,onSemanticCompose:o}){var X;const{state:i,dispatch:a}=et(),c=p.useMemo(()=>rk(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]),l=i.semanticLayer.loading,[u,h]=p.useState(new Set),[d,f]=p.useState(new Set),[m,S]=p.useState(null),[v,b]=p.useState("idle"),[w,j]=p.useState(null),[C,x]=p.useState(!1),[E,P]=p.useState(null),[A,g]=p.useState(null),[I,T]=p.useState(),O=new Map(i.semanticLayer.metrics.map(W=>[W.name,W])),_=()=>{a({type:"SET_SETTINGS_TAB",tab:"project"}),a({type:"SET_MAIN_VIEW",view:"settings"})};p.useEffect(()=>{let W=!0;return B.getConnections().then(te=>{W&&T(te.default?{target:"connection",connectionName:te.default}:void 0)}).catch(()=>{W&&T(void 0)}),()=>{W=!1}},[]),p.useEffect(()=>{let W=!0;if(P(null),g(null),u.size===0){S(null),b("idle"),j(null),f(new Set);return}return S(null),b("loading"),j(null),B.getCompatibility(Array.from(u)).then(te=>{if(!W)return;const F=new Set(te.dimensions.map(K=>K.reference??K.name));S(F),b("ready"),j(te.engine),f(K=>new Set(Array.from(K).filter(oe=>F.has(oe))))}).catch(te=>{W&&(S(new Set),b("error"),j(null),f(new Set),g(te instanceof St?`${te.code?`${te.code}: `:""}${te.message}`:te instanceof Error?te.message:"Semantic compatibility could not be verified."))}),()=>{W=!1}},[Array.from(u).sort().join("|")]);const M=p.useMemo(()=>!c||!r?c:ok(c,u.size,m,v),[c,r,u.size,m,v]),q=(W,te)=>{P(null),g(null),(W==="metric"?h:f)(K=>{const oe=new Set(K);return oe.has(te)?oe.delete(te):oe.add(te),oe})},G=(W,te)=>{var F;if(W==="metric"){const K=(F=O.get(te))==null?void 0:F.execution;return K&&K.status!=="ready"?{allowed:!1,reason:K.reason||"This metric requires semantic runtime setup."}:{allowed:!0}}return u.size===0?{allowed:!1,reason:"Select a metric first."}:m?m.has(te)?{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(u).map(W=>`metric:${W}`),...Array.from(d).map(W=>`dimension:${W}`)]),H=u.size>0&&v==="ready"&&!C,L=async()=>{if(u.size!==0){x(!0),g(null);try{const W=await B.previewSemanticBuilder({metrics:Array.from(u),dimensions:Array.from(d),executionTarget:I,limit:50});if("error"in W){P(null),g(W.error);return}P({sql:W.sql,rows:W.result.rowCount??W.result.rows.length,executionTarget:I,engine:W.engine})}catch(W){P(null),g(W instanceof St?`${W.code?`${W.code}: `:""}${W.message}`:W instanceof Error?W.message:"The governed semantic preview could not run.")}finally{x(!1)}}},$=()=>{if(!H)return;const W=Array.from(u),te=Array.from(d);if(o){o(W,te),h(new Set),f(new Set),P(null),g(null);return}const F=F0(W,te),K=Ra("dql",F);K.executionTarget=(E==null?void 0:E.executionTarget)??I,K.dqlArtifact={source:F,kind:"semantic_block",metrics:W,dimensions:te,persistence:"transient",trustState:"governed",reviewState:"draft",routeEvidence:[{route:"semantic",authoringState:E?"previewed":"selected",compatibilityState:v,...w?{compatibilityEngine:w}:{},...E?{engine:E.engine,executionTarget:E.executionTarget,previewRows:E.rows}:{}}],...E?{sql:E.sql,compiledSql:E.sql}:{}},a({type:"ADD_CELL",cell:K}),h(new Set),f(new Set),P(null),g(null)};return l&&!c?s.jsx(hr,{text:"Loading semantic layer…",t:e}):!c||!M||(((X=c.children)==null?void 0:X.length)??0)===0?s.jsx(hr,{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:u.size===0?"Choose a business metric. Related dimensions appear next.":v==="loading"?"Checking governed dimensions…":v==="ready"?`${u.size>1?"Common governed dimensions":"Governed dimensions"} · ${(m==null?void 0:m.size)??0} available${w?` · ${w}`:""}`:`${u.size} metric${u.size===1?"":"s"} selected`}),s.jsx("button",{type:"button",onClick:()=>void L(),disabled:C||u.size===0,style:{border:`1px solid ${e.btnBorder}`,background:e.btnBg,color:e.textSecondary,borderRadius:5,padding:"4px 7px",fontSize:10,cursor:u.size?"pointer":"not-allowed",opacity:u.size?1:.5},children:C?"Running…":"Preview & run"}),s.jsx("button",{type:"button",onClick:$,disabled:!H,title:H?o?"Apply this governed selection to the Block Studio visual builder":E?"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:H?"pointer":"not-allowed",opacity:H?1:.5},children:o?"Apply to block":"Add to cell"})]}),E&&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 · ",E.rows," row",E.rows===1?"":"s"]}),s.jsx("code",{style:{display:"block",maxHeight:48,overflow:"hidden",whiteSpace:"pre-wrap",fontSize:9,color:e.textMuted},children:E.sql})]}),A&&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:A}),/semantic runtime|MetricFlow/i.test(A)?s.jsx("button",{type:"button",onClick:_,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(W=>W.execution&&W.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:_,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(e0,{tree:M,themeMode:i.themeMode,search:t,onInsert:n,selectionMode:r,selected:J,onToggleSelection:q,canSelect:G})]})}function pk({t:e,search:t,domain:n,onDomainChange:r,onOpenBlock:o,onDeleteBlock:i,refreshKey:a}){const{state:c,dispatch:l}=et(),[u,h]=p.useState([]),[d,f]=p.useState(!0),[m,S]=p.useState(new Set),v=c.files.filter(g=>g.type==="block").map(g=>g.path).sort().join("|");p.useEffect(()=>{let g=!0;return f(!0),B.getBlockLibrary().then(I=>{g&&h(I.blocks)}).finally(()=>{g&&f(!1)}),()=>{g=!1}},[v,a]);const b=t0(u,c.authoredDomains),w=b.includes(n)?n:"",C=[...Jn(c.authoredDomains).filter(g=>b.includes(g.value)),...b.includes("uncategorized")?[{value:"uncategorized",label:"Unassigned"}]:[]],x=n0(u,w,t,c.authoredDomains),E=p.useMemo(()=>q0(x,w),[x,w]),P=w==="uncategorized"?"unassigned":w||"all domains",A=g=>{if(o){o(g);return}const I={name:g.path.split("/").pop()??g.name,path:g.path,type:"block",folder:"blocks"};c.files.some(T=>T.path===g.path)||l({type:"FILE_ADDED",file:I}),B.openBlockStudio(g.path).then(T=>l({type:"OPEN_BLOCK_STUDIO",file:I,payload:T}))};return d?s.jsx(hr,{text:"Loading blocks…",t:e}):u.length===0?s.jsx(hr,{text:"No blocks yet.",t:e}):s.jsxs("div",{children:[s.jsx(Fp,{id:"block-domain-filter",ariaLabel:"Block domain",value:w,options:C,onChange:g=>r==null?void 0:r(g),summary:s.jsxs(s.Fragment,{children:[x.length," block",x.length===1?"":"s"," · ",P]}),t:e}),x.length===0?s.jsx(hr,{text:t?`No ${P} blocks match this search.`:w?`No blocks in ${w} yet.`:"No blocks yet.",t:e}):s.jsx(Up,{nodes:E,depth:0,expandAll:!!t.trim(),expandedFolders:m,onToggleFolder:g=>S(I=>{const T=new Set(I);return T.has(g)?T.delete(g):T.add(g),T}),onOpen:A,onDelete:i,t:e})]})}function Up({nodes:e,depth:t,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:a,t:c}){return s.jsx(s.Fragment,{children:e.map(l=>{if(l.kind==="block")return s.jsx(fk,{block:l.block,depth:t,t:c,onOpen:()=>i(l.block),onDelete:a?()=>a(l.block):void 0},l.block.path);const u=n||r.has(l.path);return s.jsxs(qe.Fragment,{children:[s.jsxs("button",{type:"button",onClick:()=>o(l.path),title:l.path,style:{...zp(c),paddingLeft:10+t*16,borderBottom:"none",fontWeight:650},children:[u?s.jsx(_a,{size:13,color:c.textMuted}):s.jsx(Is,{size:13,color:c.textMuted}),u?s.jsx(yp,{size:14,color:c.accent}):s.jsx(ro,{size:14,color:c.textMuted}),s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},children:l.name}),s.jsx("span",{style:{fontSize:10,color:c.textMuted},children:Wp(l.children)})]}),u?s.jsx(Up,{nodes:l.children,depth:t+1,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:a,t:c}):null]},`folder:${l.path}`)})})}function Wp(e){return e.reduce((t,n)=>t+(n.kind==="block"?1:Wp(n.children)),0)}function fk({block:e,depth:t=0,t:n,onOpen:r,onDelete:o}){const i=String(e.status??"draft"),a=sk[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(Oa,{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:a}}),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(vp,{size:13})}):null]})}const Ho=(e,t)=>`https://cdn.simpleicons.org/${e}/${t}`,hk={duckdb:[Ho("duckdb","FFF000")],file:[Ho("duckdb","FFF000")],snowflake:[Ho("snowflake","29B5E8")],databricks:[Ho("databricks","FF3621")]},mk={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"};function gk({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 Yr({driver:e,size:t=16,fallbackColor:n}){const r=hk[e]??[],o=n??mk[e]??"#888",[i,a]=p.useState(0);return r.length===0||i>=r.length?s.jsx(gk,{size:t,color:o}):s.jsx("img",{src:r[i],alt:`${e} logo`,width:t,height:t,loading:"lazy",onError:()=>a(i+1),style:{flexShrink:0,display:"block",objectFit:"contain"}})}function yk(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 Go="http://127.0.0.1:11434";function bk({t:e,onStatus:t}){const[n,r]=p.useState("hashed"),[o,i]=p.useState(Go),[a,c]=p.useState(""),[l,u]=p.useState(""),[h,d]=p.useState(!1),[f,m]=p.useState({ollama:[],openai:[]}),[S,v]=p.useState([]),[b,w]=p.useState(!1),[j,C]=p.useState({id:"",semantic:!1,reindexRequired:!1}),[x,E]=p.useState(null),[P,A]=p.useState(null),[g,I]=p.useState(null),T=p.useCallback($=>{r($.settings.provider),i($.settings.endpoint||Go),c($.settings.model),d($.settings.apiKeySet),C({id:$.activeProviderId,semantic:$.semantic,reindexRequired:$.reindexRequired})},[]),O=p.useCallback(async $=>{try{const X=await B.listEmbeddingModels($);m(X.catalog),v(X.installed),w(X.ollamaReachable)}catch{}},[]);p.useEffect(()=>{(async()=>{try{const $=await B.getEmbeddingSettings();T($),await O($.settings.endpoint||Go)}catch($){A($ instanceof Error?$.message:String($))}})()},[T,O]);const _=async($,X)=>{E($),A(null),I(null);try{await X()}catch(W){A(W instanceof Error?W.message:String(W))}finally{E(null)}},M=($,X)=>_("save",async()=>{const W=await B.saveEmbeddingSettings({provider:$,...$==="ollama"?{endpoint:o}:{},...X?{model:X}:{},...$==="openai"&&l?{apiKey:l}:{}});r($),c(X),l&&(d(!0),u("")),C({id:W.activeProviderId,semantic:W.semantic,reindexRequired:W.reindexRequired}),t==null||t(W.semantic?"Semantic embeddings enabled. Re-index to apply them to your catalog.":"Using the offline hashed embedder — retrieval stays lexical.")}),q=n==="openai"?f.openai:f.ollama,G={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"},H={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%"},L=$=>({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:G,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:j.semantic?"var(--status-success-bg)":"var(--status-warning-bg)",color:j.semantic?"var(--status-success)":"var(--status-warning)",border:`1px solid ${j.semantic?"var(--status-success-border)":"var(--status-warning-border)"}`},children:[j.semantic?s.jsx(FS,{size:11}):s.jsx(NS,{size:11}),j.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"&&M("hashed","")},style:{...L(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 O(o),style:H,placeholder:Go}),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 ",h?"(stored — leave blank to keep)":""]}),s.jsx("input",{type:"password",value:l,onChange:$=>u($.target.value),style:{...H,marginTop:4},placeholder:h?"••••••••":"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:q.map($=>{const X=n==="openai"||S.includes($.model),W=a===$.model;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"9px 11px",borderRadius:8,border:`1px solid ${W?e.accent:e.btnBorder}`,background:W?`${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})]}),X?s.jsx("button",{type:"button",onClick:()=>void M(n,$.model),disabled:x!==null,style:L(W),children:W?s.jsxs(s.Fragment,{children:[s.jsx(bv,{size:12})," In use"]}):"Use this"}):s.jsx("button",{type:"button",disabled:x!==null||!b,onClick:()=>void _(`install:${$.model}`,async()=>{await B.installEmbeddingModel($.model,o),await O(o),await B.saveEmbeddingSettings({provider:"ollama",endpoint:o,model:$.model}),c($.model);const te=await B.getEmbeddingSettings();T(te),t==null||t(`${$.model} installed and selected. Re-index to apply it.`)}),style:L(!0),children:x===`install:${$.model}`?s.jsxs(s.Fragment,{children:[s.jsx(Un,{size:12,className:"dql-spin"})," Installing…"]}):s.jsxs(s.Fragment,{children:[s.jsx(mp,{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:x!==null,onClick:()=>void _("test",async()=>{const $=await B.testEmbeddingProvider();t==null||t(`${$.providerId} responded in ${$.elapsedMs} ms (${$.dimensions} dims).`)}),style:L(),children:[x==="test"?s.jsx(Un,{size:12,className:"dql-spin"}):null," Test"]}),s.jsxs("button",{type:"button",disabled:x!==null,onClick:()=>void _("reindex",async()=>{const $=await B.reindexEmbeddings(),X=await B.getEmbeddingSettings();T(X);const W=yk($,X);I(W),t==null||t(W.message)}),style:L(j.reindexRequired),children:[x==="reindex"?s.jsx(Un,{size:12,className:"dql-spin"}):s.jsx(ps,{size:12}),x==="reindex"?"Re-indexing…":"Re-index catalog"]}),s.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.fontMono},children:["active: ",j.id||"—"]})]}),j.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."}),x==="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."}),g&&s.jsx("div",{role:g.ok?"status":"alert",style:{fontSize:11.5,color:g.ok?"var(--status-success)":"var(--status-error)",marginTop:8,lineHeight:1.5},children:g.message}),P&&s.jsx("div",{style:{fontSize:11.5,color:e.error,marginTop:8,lineHeight:1.5},children:P})]})}function xk({values:e,onChange:t,placeholder:n,style:r,ariaLabel:o,title:i,disabled:a}){const c=e.join(", "),[l,u]=p.useState(c),h=p.useRef(!1);return p.useEffect(()=>{h.current||u(c)},[c]),s.jsx("input",{type:"text",value:l,disabled:a,"aria-label":o,title:i,placeholder:n,style:r,onFocus:()=>{h.current=!0},onBlur:()=>{h.current=!1,u(pl(l).join(", "))},onChange:d=>{u(d.target.value),t(pl(d.target.value))}})}function pl(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function vk(e){var t;return((t=e.evaluation)==null?void 0:t.status)==="failed"?"Rerun checks & approve":"Run checks & approve"}function Sk(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 wk(e,t,n){const r=n.trim();return{...e,[t]:r||void 0}}async function kk(e,t){try{return await e()}finally{await t()}}const Ck=["claude-code","codex","anthropic","openai","gemini","ollama","custom-openai"],jk=["claude-code","codex"],Ek=["anthropic","openai","gemini","ollama","custom-openai"];function Kp(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 ti({includeMemory:e=!0,embedded:t=!1,section:n,editorMode:r="settings",onProviderConfigured:o}){const i=Qe[Ge(A=>A.themeMode)],[a,c]=p.useState([]),[l,u]=p.useState([]),[h,d]=p.useState({}),[f,m]=p.useState({path:"",entries:[],warnings:[]}),[S,v]=p.useState([]),[b,w]=p.useState(!0),[j,C]=p.useState(null),x=async()=>{w(!0);try{const A=!n||n==="providers",g=e&&(!n||n==="memory"),I=!n||n==="advanced",[T,O,_,M]=await Promise.all([I?B.getSettingsEnvStatus():Promise.resolve({groups:[]}),A?B.getProviderSettings():Promise.resolve({providers:[]}),I?B.getRemoteMcpSettings():Promise.resolve({settings:{path:"",entries:[],warnings:[]}}),g?B.listAgentMemory():Promise.resolve({memories:[]})]);c(T.groups),u(O.providers),m(_.settings),v(M.memories)}finally{w(!1)}};p.useEffect(()=>{x()},[]),p.useEffect(()=>{if(b||n&&n!=="providers")return;let A=!1;return B.getProviderCliStatus().then(g=>{A||d(g.status??{})}),()=>{A=!0}},[b]);const E=p.useMemo(()=>l.filter(A=>A.enabled&&A.configured).length,[l]),P=l.find(A=>A.active&&A.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:i.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(Pk,{configured:E,total:l.length||Ck.length,activeLabel:P==null?void 0:P.label,t:i})]}),j&&s.jsx("div",{style:{marginTop:14,border:`1px solid ${i.headerBorder}`,borderRadius:8,padding:"10px 12px",fontSize:12,color:i.textSecondary,background:i.cellBg},children:j}),b?s.jsx("div",{style:{marginTop:24,color:i.textSecondary},children:"Loading settings..."}):s.jsxs(s.Fragment,{children:[n==="providers"&&s.jsxs(s.Fragment,{children:[s.jsx(Rk,{providers:l,cliStatus:h,t:i,onSaved:A=>u(A),onStatus:C,editorMode:r,onProviderConfigured:o}),s.jsx(bk,{t:i,onStatus:C})]}),!n&&s.jsxs("section",{style:{marginTop:22},children:[s.jsx(or,{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:i}),s.jsx(hl,{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:i}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:jk.map(A=>{const g=l.find(I=>I.id===A);return g?s.jsx(yl,{provider:g,cliStatus:h[A],t:i,onSaved:I=>u(I),onStatus:C},A):null})}),s.jsx(hl,{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:i}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:Ek.map(A=>{const g=l.find(I=>I.id===A);return g?s.jsx(yl,{provider:g,t:i,onSaved:I=>u(I),onStatus:C},A):null})})]}),(!n||n==="memory")&&e&&s.jsxs("section",{style:{marginTop:n?0:22},children:[s.jsx(or,{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:i}),s.jsx(_k,{memories:S,t:i,onChange:v,onStatus:C}),s.jsx(Ok,{t:i,onStatus:C})]}),n==="advanced"&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsx(or,{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:i}),s.jsx(fl,{settings:f,t:i,onChange:m,onStatus:C})]}),s.jsxs("section",{style:{marginTop:22},children:[s.jsx(or,{title:"Runtime status",detail:"Environment variables remain supported for Docker, CI, and shell-based setup.",t:i}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:a.map(A=>s.jsx(xl,{group:A,t:i},A.id))})]})]}),!n&&s.jsxs("details",{style:{marginTop:22,border:`1px solid ${i.headerBorder}`,borderRadius:10,background:i.cellBg,overflow:"hidden"},children:[s.jsxs("summary",{style:{cursor:"pointer",padding:"13px 16px",fontSize:13,fontWeight:650,listStyle:"none",color:i.textPrimary},children:["Advanced — MCP connections & runtime status",s.jsx("span",{style:{color:i.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(or,{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:i}),s.jsx(fl,{settings:f,t:i,onChange:m,onStatus:C})]}),s.jsxs("section",{style:{marginTop:22},children:[s.jsx(or,{title:"Runtime status",detail:"Environment variables remain supported for Docker, CI, and shell-based setup.",t:i}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:a.map(A=>s.jsx(xl,{group:A,t:i},A.id))})]})]})]})]})]})}function fl({settings:e,t,onChange:n,onStatus:r}){const[o,i]=p.useState(e.entries),[a,c]=p.useState("form"),[l,u]=p.useState(()=>Ur(e.entries)),[h,d]=p.useState(null),[f,m]=p.useState(!1);p.useEffect(()=>{i(e.entries),u(Ur(e.entries)),d(null)},[e]);const S=O=>{i(O),u(Ur(O)),d(null)},v=(O,_)=>{S(o.map((M,q)=>q===O?Hn({...M,..._}):M))},b=O=>{S(o.filter((_,M)=>M!==O))},w=()=>{S([...o,{kind:"server",name:"",url:"",enabled:!0,trusted:!1,providers:["openai","anthropic"]}])},j=()=>{S([...o,{kind:"connector",name:"",connectorId:"connector_googledrive",enabled:!0,trusted:!1,providers:["openai"]}])},C=O=>{O==="json"&&u(Ur(o)),d(null),c(O)},x=()=>{const O=$k(l);return i(O),u(Ur(O)),d(null),O},E=()=>{try{x()}catch(O){d(O instanceof Error?O.message:String(O))}},P=()=>{try{x(),c("form"),r("MCP JSON applied.")}catch(O){d(O instanceof Error?O.message:String(O))}},A=async()=>{m(!0);try{const O=a==="json"?x():o,_=await B.saveRemoteMcpSettings(O.map(q=>Hn(q)));n(_.settings);const M=_.settings.warnings.length?` ${_.settings.warnings.join(" ")}`:"";r(`MCP connections saved.${M}`)}catch(O){const _=O instanceof Error?O.message:String(O);a==="json"&&d(_),r(_)}finally{m(!1)}},g=o.filter(O=>O.enabled&&O.trusted).length,I=o.filter(O=>O.kind==="server").length,T=o.filter(O=>O.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:[g," trusted connection",g===1?"":"s"," available to SDK providers"]}),s.jsxs("div",{style:{fontSize:11,color:t.textMuted,marginTop:3},children:[I," remote server",I===1?"":"s"," / ",T," OpenAI connector",T===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:()=>C("form"),style:vl(t,a==="form"),children:"Form"}),s.jsx("button",{type:"button",onClick:()=>C("json"),style:vl(t,a==="json"),children:"JSON import"})]}),s.jsx("button",{type:"button",onClick:w,style:Ft(t,!1),children:"Add MCP server"}),s.jsx("button",{type:"button",onClick:j,style:Ft(t,!1),children:"Add OpenAI connector"}),s.jsx("button",{type:"button",onClick:A,disabled:f,style:Ft(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(ni,{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(ni,{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(ni,{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(" ")}),a==="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:l,onChange:O=>{u(O.target.value),d(null)},spellCheck:!1,rows:18,style:{...Ne(t),width:"100%",minHeight:360,resize:"vertical",fontFamily:t.fontMono,fontSize:12,lineHeight:1.45}}),h&&s.jsx("div",{style:{color:"#b42318",fontSize:12,marginTop:8},children:h}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:10},children:[s.jsx("button",{type:"button",onClick:E,style:Ft(t,!1),children:"Format JSON"}),s.jsx("button",{type:"button",onClick:P,style:Ft(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((O,_)=>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:O.kind,onChange:M=>v(_,{kind:M.target.value==="connector"?"connector":"server",providers:M.target.value==="connector"?["openai"]:O.providers}),style:{...Ne(t),width:116},children:[s.jsx("option",{value:"server",children:"Server"}),s.jsx("option",{value:"connector",children:"Connector"})]}),s.jsx("input",{value:O.name,onChange:M=>v(_,{name:M.target.value}),placeholder:"Name",style:{...Ne(t),flex:1}}),s.jsx("button",{type:"button",onClick:()=>b(_),style:Ft(t,!1),children:"Remove"})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:10},children:[O.kind==="connector"?s.jsx("input",{value:O.connectorId??"",onChange:M=>v(_,{connectorId:M.target.value}),placeholder:"connector_googledrive",style:Ne(t)}):s.jsx("input",{value:O.url??"",onChange:M=>v(_,{url:M.target.value}),placeholder:"https://example.com/mcp or /sse",style:Ne(t)}),s.jsx("input",{value:O.description??"",onChange:M=>v(_,{description:M.target.value}),placeholder:"Description shown to the model",style:Ne(t)}),s.jsx("input",{value:O.authorizationTokenEnv??"",onChange:M=>v(_,{authorizationTokenEnv:M.target.value}),placeholder:"Authorization token env var",style:Ne(t)}),s.jsx("input",{value:O.authorizationToken??"",onChange:M=>v(_,{authorizationToken:M.target.value}),type:"password",placeholder:O.hasAuthorizationToken?`Leave blank to keep ${O.authorizationTokenPreview??"stored token"}`:"Optional OAuth token",style:Ne(t)}),s.jsx(xk,{values:O.allowedTools??[],onChange:M=>v(_,{allowedTools:M}),placeholder:"Allowed tools, comma separated",style:Ne(t)})]}),s.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",marginTop:10},children:[s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:O.enabled,onChange:M=>v(_,{enabled:M.target.checked})})," Enabled"]}),s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:O.trusted,onChange:M=>v(_,{trusted:M.target.checked})})," Trusted"]}),s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:!!O.deferLoading,onChange:M=>v(_,{deferLoading:M.target.checked})})," Defer tools"]}),s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:(O.providers??[]).includes("openai"),onChange:M=>v(_,{providers:wl(O.providers,"openai",M.target.checked)})})," OpenAI"]}),s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:(O.providers??[]).includes("anthropic"),disabled:O.kind==="connector",onChange:M=>v(_,{providers:wl(O.providers,"anthropic",M.target.checked)})})," Anthropic"]})]})]},`${O.kind}-${O.name||_}`))})]})}function ni({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 Tk({status:e,command:t,loginCmd:n,t:r}){let o=r.textMuted,i=r.textMuted,a="Checking for the CLI…";if(e)if(!e.installed)o=r.warning,i=r.warning,a=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,a=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 c=[e.email,e.subscriptionType?`${e.subscriptionType} plan`:e.authMethod].filter(Boolean).join(" · ");a=s.jsxs(s.Fragment,{children:["Signed in",c?s.jsxs(s.Fragment,{children:[" — ",c]}):"",". 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:a})]})}function hl({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 Vp(e){return e==="codex"?"codex":"claude"}function Hp({oauthProvider:e,label:t,model:n,setModel:r,cliStatus:o,command:i,loginCmd:a,t:c,onStatus:l,onConnected:u}){const[h,d]=p.useState(null),[f,m]=p.useState(!1),S=p.useRef(null),v=p.useRef(!0),b=e==="codex"?"ChatGPT":"Claude",w=p.useCallback(()=>{S.current!==null&&(window.clearInterval(S.current),S.current=null)},[]);p.useEffect(()=>(v.current=!0,B.getOAuthStatus(e).then(x=>{v.current&&d(x)}).catch(()=>{}),()=>{v.current=!1,w()}),[e,w]);const j=async()=>{m(!0);try{const x=await B.startOAuth(e);d(x),window.open(x.url,"_blank","noopener,noreferrer"),l(`Opened your browser to sign in to ${b}. Complete it there — this updates automatically.`);const E=Date.now();w(),S.current=window.setInterval(async()=>{const P=await B.getOAuthStatus(e).catch(()=>null);if(!v.current){w();return}P&&d(P),P!=null&&P.connected?(w(),m(!1),u(P.defaultModel)):Date.now()-E>300*1e3&&(w(),m(!1),l(`${b} sign-in timed out. Try again.`))},2500)}catch(x){m(!1),l(x instanceof Error?x.message:String(x))}},C=async()=>{m(!0),w();try{d(await B.signOutOAuth(e)),l(`Signed out of ${b}.`)}catch(x){l(x instanceof Error?x.message:String(x))}finally{m(!1)}};if(h!=null&&h.connected){const x=h.models.length>0?h.models:[h.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]}),h.email?s.jsxs("span",{style:{color:c.textSecondary},children:["as ",h.email]}):null]}),s.jsx("label",{style:{fontSize:11,color:c.textSecondary,fontWeight:600},children:"Model"}),s.jsx("select",{value:n||h.defaultModel,onChange:E=>r(E.target.value),style:Ne(c),children:x.map(E=>s.jsx("option",{value:E,children:E},E))}),s.jsx("div",{children:s.jsx("button",{type:"button",onClick:C,disabled:f,style:Ft(c,!1),children:"Sign out"})})]})}return s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsx("button",{type:"button",onClick:j,disabled:f,style:Ft(c,!0),children:f||h!=null&&h.pending?`Waiting for ${b}…`:`Sign in with ${b}`}),s.jsxs("div",{style:{fontSize:12,color:c.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:c.textSecondary,cursor:"pointer"},children:"Prefer the CLI?"}),s.jsxs("div",{style:{marginTop:6,display:"grid",gap:6},children:[s.jsx(Tk,{status:o,command:i,loginCmd:a,t:c}),s.jsxs("div",{style:{fontSize:11.5,color:c.textSecondary,lineHeight:1.5},children:["Or install the ",s.jsx("code",{children:i})," CLI and run ",s.jsxs("code",{children:[i," ",a]}),", then Enable + Save."]})]})]})]})}const ts=[{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"}}],ml={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 Ak(e){if(!e)return"claude";const t=ts.find(n=>Object.values(n.modes).includes(e));return(t==null?void 0:t.key)??"claude"}function Rk({providers:e,cliStatus:t,t:n,onSaved:r,onStatus:o,editorMode:i,onProviderConfigured:a}){var F;const c=e.find(K=>K.active&&K.configured),[l,u]=p.useState(()=>Ak(c==null?void 0:c.id)),h=ts.find(K=>K.key===l)??ts[0],d=Object.keys(h.modes),[f,m]=p.useState(()=>d.find(oe=>h.modes[oe]===(c==null?void 0:c.id))??d[0]),S=d.includes(f)?f:d[0],v=h.modes[S],b=e.find(K=>K.id===v),[w,j]=p.useState(""),[C,x]=p.useState((b==null?void 0:b.baseUrl)??""),[E,P]=p.useState((b==null?void 0:b.model)??""),[A,g]=p.useState((b==null?void 0:b.reasoningEffort)??"auto"),[I,T]=p.useState(!1),[O,_]=p.useState({state:"idle"}),[M,q]=p.useState({state:"idle"});p.useEffect(()=>{j(""),x((b==null?void 0:b.baseUrl)??""),P((b==null?void 0:b.model)??""),g((b==null?void 0:b.reasoningEffort)??"auto"),q({state:"idle"})},[v,b==null?void 0:b.baseUrl,b==null?void 0:b.model,b==null?void 0:b.reasoningEffort]);const G=async()=>{if(!c)return;_({state:"testing"});const K=Date.now(),oe=await B.testProviderSettings(c.id,{}),ee=oe.ok!==!1;_({state:"done",ok:ee,message:oe.message,seconds:((Date.now()-K)/1e3).toFixed(1)})},J=()=>{var K;return v==="custom-openai"&&!C.trim()?"Custom OpenAI-compatible providers require a Base URL.":v==="custom-openai"&&!E.trim()?"Custom OpenAI-compatible providers require a model.":S==="api"&&v!=="custom-openai"&&!w.trim()&&!(b!=null&&b.hasApiKey)?`Add an API key${(K=b==null?void 0:b.envVars)!=null&&K[0]?` or set ${b.envVars[0]}`:""}.`:S==="local"&&!C.trim()&&!E.trim()&&!(b!=null&&b.configured)?"Set an Ollama endpoint or model before testing.":null},H=async()=>{const K=J();if(K)return q({state:"done",ok:!1,message:K}),!1;q({state:"testing"});const oe=await B.testProviderSettings(v,{apiKey:w||void 0,baseUrl:C||void 0,model:E||void 0});return q({state:"done",ok:oe.ok,message:oe.message}),oe.ok},L=async()=>{T(!0);try{if(!await H()){o("Test failed. Your existing provider configuration was not changed.");return}const oe=await B.saveProviderSettings({id:v,enabled:!0,apiKey:w||void 0,baseUrl:C,model:E,reasoningEffort:A});r(oe.providers);const ee=oe.providers.find(ce=>ce.id===v);ee&&(a==null||a(ee)),o(`${h.label} passed its test and is now the active provider.`)}catch(K){o(K instanceof Error?K.message:String(K))}finally{T(!1)}},$=async K=>{const oe=E||K;P(oe);try{const ee=await B.saveProviderSettings({id:v,enabled:!0,model:oe});r(ee.providers);const ce=ee.providers.find(ke=>ke.id===v);ce&&(a==null||a(ce)),o(`${h.label} subscription configured and activated. Run Test to verify the next governed request.`)}catch(ee){o(ee instanceof Error?ee.message:String(ee))}},X={fontSize:11,fontWeight:650,color:n.textSecondary},W={...Ne(n),borderRadius:8},te=S==="subscription"?"Uses your existing plan through the provider’s sign-in — nothing billed per token.":S==="local"?"Everything runs on this machine — no data leaves your network.":"Keys stay in .dql/ and are never returned raw.";return s.jsxs("div",{style:{width:"min(680px, 100%)",display:"flex",flexDirection:"column",gap:16},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:17,fontWeight:700,color:n.textPrimary},children:"AI provider"}),s.jsxs("div",{style:{fontSize:12.5,color:n.textMuted,marginTop:3,lineHeight:1.5},children:["AI is optional. Without it, deterministic queries, dbt metadata, connections, and governed non-AI paths remain available. Keys stay in ",s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:11.5},children:".dql/"})," and are never returned raw."]})]}),c?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(xp,{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 · ",c.label,c.model?` — ${c.model}`:""]}),s.jsx("div",{style:{fontSize:11.5,color:O.state==="done"&&O.ok===!1?"var(--status-error)":"var(--status-success)",marginTop:2},children:O.state==="testing"?"Testing…":O.state==="done"?O.ok?`Test passed · ${O.seconds}s`:O.message||"Test failed":c.source==="env"?"Configured from environment — run Test to verify":"Configured — run Test to verify reachability"})]}),s.jsx("button",{type:"button",onClick:()=>void G(),disabled:O.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:O.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:X,children:"Provider"}),s.jsx("select",{value:h.key,onChange:K=>{u(K.target.value),m("subscription")},style:W,children:ts.map(K=>s.jsx("option",{value:K.key,children:K.label},K.key))})]})}),s.jsxs("div",{children:[s.jsx("span",{style:{...X,display:"block",marginBottom:6},children:"How do you want to connect?"}),s.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:d.map(K=>{const oe=K===S;return s.jsxs("button",{type:"button",onClick:()=>m(K),style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 13px",borderRadius:9,border:`1.5px solid ${oe?n.accent:n.headerBorder}`,background:oe?"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 ${oe?n.accent:"var(--border-strong)"}`,background:oe?n.accent:n.cellBg,boxShadow:oe?`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:ml[K].label}),s.jsx("span",{style:{fontSize:10,color:n.textMuted},children:ml[K].hint})]})]},K)})})]}),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(Hp,{oauthProvider:Vp(v),label:b.label,model:E,setModel:P,cliStatus:t[v],command:b.command,loginCmd:v==="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:X,children:"API key"}),s.jsx("input",{type:"password",value:w,onChange:K=>j(K.target.value),placeholder:b!=null&&b.hasApiKey?"Leave blank to keep existing key":"API key",style:{...W,fontFamily:n.fontMono}})]}),(F=b==null?void 0:b.envVars)!=null&&F[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:X,children:"Host"}),s.jsx("input",{value:C,onChange:K=>x(K.target.value),placeholder:"http://localhost:11434",style:{...W,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(gl,{providerId:v,provider:b,mode:S,baseUrl:C,setBaseUrl:x,model:E,setModel:P,reasoningEffort:A,setReasoningEffort:g,t:n,input:W,fieldLabel:X})})]}):s.jsx("div",{style:{display:"grid",gap:10},children:s.jsx(gl,{providerId:v,provider:b,mode:S,baseUrl:C,setBaseUrl:x,model:E,setModel:P,reasoningEffort:A,setReasoningEffort:g,t:n,input:W,fieldLabel:X})}),M.state!=="idle"?s.jsx("div",{role:M.ok===!1?"alert":"status",style:{fontSize:11.5,lineHeight:1.5,color:M.state==="testing"?n.textMuted:M.ok?"var(--status-success)":"var(--status-error)"},children:M.state==="testing"?"Testing these unsaved values through the governed runtime…":M.message}):null,s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,paddingTop:4,borderTop:"1px solid var(--border-subtle)"},children:[s.jsx("span",{style:{fontSize:10.5,color:n.textMuted,flex:1},children:te}),s.jsx("button",{type:"button",onClick:()=>void H(),disabled:I||M.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:M.state==="testing"?"Testing…":"Test unsaved values"}),s.jsx("button",{type:"button",onClick:()=>void L(),disabled:I,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:I?.7:1},children:I?"Testing…":"Test, save & activate"})]})]})]})}function gl({providerId:e,provider:t,mode:n,baseUrl:r,setBaseUrl:o,model:i,setModel:a,reasoningEffort:c,setReasoningEffort:l,t:u,input:h,fieldLabel:d}){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:d,children:e==="custom-openai"?"Base URL (required)":"Base URL (optional)"}),s.jsx("input",{value:r,onChange:f=>o(f.target.value),placeholder:Kp(e),style:{...h,fontFamily:u.fontMono}})]}):null,s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:d,children:e==="custom-openai"?"Model (required)":"Model (optional)"}),s.jsx("input",{value:i,onChange:f=>a(f.target.value),placeholder:(t==null?void 0:t.model)||"Provider default",style:h})]}),t!=null&&t.supportsReasoningEffort&&n==="api"?s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:d,children:"Reasoning effort"}),s.jsxs("select",{value:c,onChange:f=>l(f.target.value),style:h,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 yl({provider:e,cliStatus:t,t:n,onSaved:r,onStatus:o}){const[i,a]=p.useState(e.enabled),[c,l]=p.useState(""),[u,h]=p.useState(e.baseUrl??""),[d,f]=p.useState(e.model??""),[m,S]=p.useState(e.reasoningEffort??"auto"),[v,b]=p.useState(!1),[w,j]=p.useState(!1),[C,x]=p.useState(null),E=e.authMode==="subscription_cli",P=e.id==="claude-code"?"/login":"login",A=e.supportsReasoningEffort===!0&&!E&&e.id!=="ollama";p.useEffect(()=>{a(e.enabled),h(e.baseUrl??""),f(e.model??""),S(e.reasoningEffort??"auto"),l(""),x(null)},[e.id,e.enabled,e.baseUrl,e.model,e.reasoningEffort]);const g=async()=>{b(!0);try{const O=await B.saveProviderSettings({id:e.id,enabled:i,apiKey:c||void 0,baseUrl:u,model:d,reasoningEffort:m});r(O.providers),o(`${e.label} settings saved.`)}catch(O){o(O instanceof Error?O.message:String(O))}finally{b(!1)}},I=async()=>{j(!0),x(null);const O=await B.testProviderSettings(e.id,{apiKey:c||void 0,baseUrl:u||void 0,model:d||void 0}),_=O.ok!==!1;x({ok:_,message:O.message||(_?`${e.label} is reachable.`:`${e.label} test failed.`)}),j(!1)},T=async O=>{const _=d||O;f(_),a(!0);try{const M=await B.saveProviderSettings({id:e.id,enabled:!0,model:_});r(M.providers),o(`${e.label} connected and activated.`)}catch(M){o(M instanceof Error?M.message:String(M))}};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:Dk(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:O=>a(O.target.checked)}),"Enabled"]})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:12},children:[E?s.jsx(Hp,{oauthProvider:Vp(e.id),label:e.label,model:d,setModel:f,cliStatus:t,command:e.command,loginCmd:P,t:n,onStatus:o,onConnected:T}):s.jsxs(s.Fragment,{children:[e.id!=="ollama"&&s.jsx("input",{value:c,onChange:O=>l(O.target.value),type:"password",placeholder:e.hasApiKey?"Leave blank to keep existing key":"API key",style:Ne(n)}),s.jsx("input",{value:u,onChange:O=>h(O.target.value),placeholder:Kp(e.id),style:Ne(n)})]}),!E&&s.jsx("input",{value:d,onChange:O=>f(O.target.value),placeholder:"Default model",style:Ne(n)}),A&&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:m,onChange:O=>S(O.target.value),style:Ne(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:m==="auto"?"The agent spends more reasoning on SQL generation, gates, and repairs, and less on chat.":`Caps every request at ${m} reasoning.`})]})]}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[s.jsx("button",{type:"button",onClick:g,disabled:v||w,style:Ft(n,!0),children:e.active?"Save active provider":"Save and use"}),s.jsx("button",{type:"button",onClick:I,disabled:v||w,style:Ft(n,!1),children:w?"Testing…":"Test"})]}),C&&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:C.ok?n.success:n.error,background:`${C.ok?n.success:n.error}12`,border:`1px solid ${C.ok?n.success:n.error}40`},children:[s.jsx("span",{style:{flexShrink:0,fontWeight:700},children:C.ok?"✓":"✗"}),s.jsx("span",{children:C.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 rt(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 bl(e){return[...new Map(e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean).map(t=>[t.toLowerCase(),t])).values()].slice(0,8)}function Ok({t:e,onStatus:t}){const[n,r]=p.useState([]),[o,i]=p.useState({candidate:0,approved:0,rejected:0,retired:0}),[a,c]=p.useState(null),[l,u]=p.useState(!1),[h,d]=p.useState({}),[f,m]=p.useState(null),S=p.useCallback(async()=>{try{const g=await B.listAgentHints();r(g.hints??[]),i(g.counts??{candidate:0,approved:0,rejected:0,retired:0})}catch{r([])}finally{u(!0)}},[]);p.useEffect(()=>{S()},[S]);const v=async(g,I)=>{var T;c(g.id),t(null);try{const O=(T=h[g.id])==null?void 0:T.trim(),_=await kk(()=>B.reviewAgentHint(g.id,I,O),S);_.ok?t(I==="approved"?`Approved. DQL will apply "${g.title}" to matching questions.`:`Rejected. "${g.title}" will not be used.`):t(_.error??`Could not ${I==="approved"?"approve":"reject"} this correction.`)}catch(O){t(O instanceof Error?O.message:String(O))}finally{c(null)}},b=async(g,I,T)=>{var O;c(g.id),t(null);try{const _=await B.transitionAgentHint(g.id,{action:I,targetHintId:T,note:((O=h[g.id])==null?void 0:O.trim())||void 0});t(_.ok?I==="retire"?`Retired "${g.title}". It is excluded from future answers.`:I==="reopen"?`Reopened "${g.title}" as a candidate.`:`Resolved the conflict. "${g.title}" is authoritative.`:_.error??`Could not ${I} this hint.`),await S()}catch(_){t(_ instanceof Error?_.message:String(_))}finally{c(null)}},w=async()=>{if(f){c(f.id),t(null);try{const g=await B.updateAgentHint(f.id,{title:f.title,guidance:f.guidance,lesson:{...rt(f),rule:f.guidance},correctedSql:f.correctedSql,scope:f.scope});g.ok?(t(`Updated "${f.title}" and refreshed its current dependencies.`),m(null)):t(g.error??"Could not update this candidate."),await S()}catch(g){t(g instanceof Error?g.message:String(g))}finally{c(null)}}},j=async g=>{var I;if(!((I=g.trace)!=null&&I.question)||!g.correctedSql){t("This hint is missing the question or SQL required for an analyst certification request.");return}c(g.id);try{const T=await B.requestCertification({question:g.trace.question,generatedSql:g.correctedSql,domain:g.scope.domain,context:{source:"governed_hint_review",hintId:g.id,evaluationId:g.evaluationId,snapshotId:g.snapshotId}});t(T.ok?`Certification research requested for "${g.title}". Approval of a hint did not certify an asset.`:T.error??"Could not request certification.")}catch(T){t(T instanceof Error?T.message:String(T))}finally{c(null)}},C=n.filter(g=>g.status==="candidate"),x=n.filter(g=>g.status==="approved"),E=n.filter(g=>g.status==="rejected"||g.status==="retired");if(!l)return null;const P=g=>{var I,T,O,_,M,q,G,J,H;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:[(I=g.trace)!=null&&I.question?s.jsxs("div",{children:[s.jsx("b",{children:"Question:"})," ",g.trace.question]}):null,(T=g.trace)!=null&&T.wrongAnswer?s.jsxs("div",{children:[s.jsx("b",{children:"Previous answer:"})," ",g.trace.wrongAnswer]}):null,(O=g.trace)!=null&&O.rationale?s.jsxs("div",{children:[s.jsx("b",{children:"Why the correction is right:"})," ",g.trace.rationale]}):null,s.jsxs("div",{children:[s.jsx("b",{children:"Snapshot:"})," ",g.snapshotId??"missing",(_=g.inspection)!=null&&_.currentSnapshotId?` · current ${g.inspection.currentSnapshotId}`:""]}),s.jsxs("div",{children:[s.jsx("b",{children:"Dependencies:"})," ",((M=g.dependencies)==null?void 0:M.map(L=>`${L.kind}:${L.id}@${L.fingerprint.slice(0,10)}`).join(", "))||"none recorded"]}),s.jsxs("div",{children:[s.jsx("b",{children:"Graph connections:"})," ",(q=g.graphEdges)!=null&&q.length?g.graphEdges.map(L=>`${L.kind.replace(/_/g," ")} → ${L.targetName}`).join(" · "):"none materialized"]}),(G=g.lifecycleErrors)==null?void 0:G.map(L=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:[L.code,":"]})," ",L.message]},`${L.code}-${L.at}`)),g.evaluation?s.jsxs("div",{children:[s.jsxs("b",{children:["Evaluation ",g.evaluation.status,":"]}),g.evaluation.checks.map(L=>s.jsxs("div",{style:{color:L.passed?e.success:e.error},children:[L.passed?"✓":"✕"," ",L.name," — ",L.evidence]},L.name))]}):s.jsxs("div",{children:[s.jsx("b",{children:"Evaluation:"})," not run"]}),(J=g.inspection)==null?void 0:J.checks.map(L=>s.jsxs("div",{style:{color:L.passed?e.success:e.error},children:[L.passed?"✓":"✕"," live ",L.name," — ",L.evidence]},`live-${L.name}`)),(H=g.exclusions)==null?void 0:H.map((L,$)=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:["Excluded: ",L.reason]})," — ",L.detail]},`${L.reason}-${$}`))]})]})},A=g=>{var _,M,q,G,J,H;const I=((_=g.exclusions)==null?void 0:_.filter(L=>L.reason==="conflict"&&L.relatedHintId))??[],T=(f==null?void 0:f.id)===g.id,O=g.status==="approved"&&((M=g.evaluation)==null?void 0:M.status)==="passed"&&((q=g.inspection)==null?void 0:q.state)==="current"&&(((G=g.exclusions)==null?void 0:G.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:g.title}),s.jsx("span",{style:{fontSize:10,color:(J=g.exclusions)!=null&&J.length||((H=g.evaluation)==null?void 0:H.status)==="failed"?e.error:e.success},children:Sk(g)})]}),T?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:f.title,onChange:L=>m({...f,title:L.target.value}),placeholder:"Hint title",style:Re(e,{size:"sm"})}),s.jsx("textarea",{value:f.guidance,onChange:L=>m({...f,guidance:L.target.value}),placeholder:"Guidance for matching questions",rows:3,style:{...Re(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:rt(f).category,onChange:L=>m({...f,lesson:{...rt(f),category:L.target.value}}),style:Re(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:rt(f).intentExamples.join(`
437
- `),onChange:L=>m({...f,lesson:{...rt(f),intentExamples:L.target.value.split(/\r?\n/)}}),onBlur:()=>m({...f,lesson:{...rt(f),intentExamples:bl(rt(f).intentExamples.join(`
436
+ `}),c?s.jsx(uk,{file:c,t:e,busy:u,error:d,onCancel:()=>{l(null),f(null)},onConfirm:()=>void E()}):null]})}function Up({nodes:e,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i=0}){return s.jsx(s.Fragment,{children:e.map(a=>a.kind==="folder"?s.jsx(lk,{node:a,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i},`notebook-folder:${a.path}`):s.jsx(dk,{file:a.file,active:t===a.file.path,onOpenFile:n,onDelete:r,t:o,depth:i},a.file.path))})}function lk({node:e,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i}){const[a,c]=p.useState(!0);return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>c(l=>!l),"aria-expanded":a,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(Is,{size:11,style:{transform:a?"rotate(90deg)":void 0,flexShrink:0}}),a?s.jsx(bp,{size:13}):s.jsx(ro,{size:13}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]}),a?s.jsx(Up,{nodes:e.children,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i+1}):null]})}function dk({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:{...qp(o,t),paddingLeft:10+i*14,paddingRight:30},title:`${e.path}${e.ownerDomain?` · Owner domain: ${e.ownerDomain}`:""}`,children:[s.jsx(Pa,{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:a=>{a.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(Sp,{size:12})})]})}function uk({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:a=>a.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:Re(t,{variant:"secondary",size:"md",disabled:n}),children:"Cancel"}),s.jsx("button",{type:"button",onClick:i,disabled:n,style:Re(t,{variant:"danger",size:"md",disabled:n}),children:n?"Deleting…":"Delete notebook"})]})]})})}function pk({t:e,search:t,onInsert:n,notebookMode:r,onSemanticCompose:o}){var X;const{state:i,dispatch:a}=et(),c=p.useMemo(()=>ok(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]),l=i.semanticLayer.loading,[u,h]=p.useState(new Set),[d,f]=p.useState(new Set),[m,S]=p.useState(null),[v,b]=p.useState("idle"),[w,j]=p.useState(null),[C,x]=p.useState(!1),[E,P]=p.useState(null),[A,g]=p.useState(null),[I,T]=p.useState(),O=new Map(i.semanticLayer.metrics.map(W=>[W.name,W])),_=()=>{a({type:"SET_SETTINGS_TAB",tab:"project"}),a({type:"SET_MAIN_VIEW",view:"settings"})};p.useEffect(()=>{let W=!0;return B.getConnections().then(te=>{W&&T(te.default?{target:"connection",connectionName:te.default}:void 0)}).catch(()=>{W&&T(void 0)}),()=>{W=!1}},[]),p.useEffect(()=>{let W=!0;if(P(null),g(null),u.size===0){S(null),b("idle"),j(null),f(new Set);return}return S(null),b("loading"),j(null),B.getCompatibility(Array.from(u)).then(te=>{if(!W)return;const F=new Set(te.dimensions.map(K=>K.reference??K.name));S(F),b("ready"),j(te.engine),f(K=>new Set(Array.from(K).filter(oe=>F.has(oe))))}).catch(te=>{W&&(S(new Set),b("error"),j(null),f(new Set),g(te instanceof St?`${te.code?`${te.code}: `:""}${te.message}`:te instanceof Error?te.message:"Semantic compatibility could not be verified."))}),()=>{W=!1}},[Array.from(u).sort().join("|")]);const M=p.useMemo(()=>!c||!r?c:sk(c,u.size,m,v),[c,r,u.size,m,v]),q=(W,te)=>{P(null),g(null),(W==="metric"?h:f)(K=>{const oe=new Set(K);return oe.has(te)?oe.delete(te):oe.add(te),oe})},G=(W,te)=>{var F;if(W==="metric"){const K=(F=O.get(te))==null?void 0:F.execution;return K&&K.status!=="ready"?{allowed:!1,reason:K.reason||"This metric requires semantic runtime setup."}:{allowed:!0}}return u.size===0?{allowed:!1,reason:"Select a metric first."}:m?m.has(te)?{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(u).map(W=>`metric:${W}`),...Array.from(d).map(W=>`dimension:${W}`)]),H=u.size>0&&v==="ready"&&!C,L=async()=>{if(u.size!==0){x(!0),g(null);try{const W=await B.previewSemanticBuilder({metrics:Array.from(u),dimensions:Array.from(d),executionTarget:I,limit:50});if("error"in W){P(null),g(W.error);return}P({sql:W.sql,rows:W.result.rowCount??W.result.rows.length,executionTarget:I,engine:W.engine})}catch(W){P(null),g(W instanceof St?`${W.code?`${W.code}: `:""}${W.message}`:W instanceof Error?W.message:"The governed semantic preview could not run.")}finally{x(!1)}}},$=()=>{if(!H)return;const W=Array.from(u),te=Array.from(d);if(o){o(W,te),h(new Set),f(new Set),P(null),g(null);return}const F=z0(W,te),K=Ra("dql",F);K.executionTarget=(E==null?void 0:E.executionTarget)??I,K.dqlArtifact={source:F,kind:"semantic_block",metrics:W,dimensions:te,persistence:"transient",trustState:"governed",reviewState:"draft",routeEvidence:[{route:"semantic",authoringState:E?"previewed":"selected",compatibilityState:v,...w?{compatibilityEngine:w}:{},...E?{engine:E.engine,executionTarget:E.executionTarget,previewRows:E.rows}:{}}],...E?{sql:E.sql,compiledSql:E.sql}:{}},a({type:"ADD_CELL",cell:K}),h(new Set),f(new Set),P(null),g(null)};return l&&!c?s.jsx(hr,{text:"Loading semantic layer…",t:e}):!c||!M||(((X=c.children)==null?void 0:X.length)??0)===0?s.jsx(hr,{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:u.size===0?"Choose a business metric. Related dimensions appear next.":v==="loading"?"Checking governed dimensions…":v==="ready"?`${u.size>1?"Common governed dimensions":"Governed dimensions"} · ${(m==null?void 0:m.size)??0} available${w?` · ${w}`:""}`:`${u.size} metric${u.size===1?"":"s"} selected`}),s.jsx("button",{type:"button",onClick:()=>void L(),disabled:C||u.size===0,style:{border:`1px solid ${e.btnBorder}`,background:e.btnBg,color:e.textSecondary,borderRadius:5,padding:"4px 7px",fontSize:10,cursor:u.size?"pointer":"not-allowed",opacity:u.size?1:.5},children:C?"Running…":"Preview & run"}),s.jsx("button",{type:"button",onClick:$,disabled:!H,title:H?o?"Apply this governed selection to the Block Studio visual builder":E?"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:H?"pointer":"not-allowed",opacity:H?1:.5},children:o?"Apply to block":"Add to cell"})]}),E&&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 · ",E.rows," row",E.rows===1?"":"s"]}),s.jsx("code",{style:{display:"block",maxHeight:48,overflow:"hidden",whiteSpace:"pre-wrap",fontSize:9,color:e.textMuted},children:E.sql})]}),A&&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:A}),/semantic runtime|MetricFlow/i.test(A)?s.jsx("button",{type:"button",onClick:_,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(W=>W.execution&&W.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:_,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(t0,{tree:M,themeMode:i.themeMode,search:t,onInsert:n,selectionMode:r,selected:J,onToggleSelection:q,canSelect:G})]})}function fk({t:e,search:t,domain:n,onDomainChange:r,onOpenBlock:o,onDeleteBlock:i,refreshKey:a}){const{state:c,dispatch:l}=et(),[u,h]=p.useState([]),[d,f]=p.useState(!0),[m,S]=p.useState(new Set),v=c.files.filter(g=>g.type==="block").map(g=>g.path).sort().join("|");p.useEffect(()=>{let g=!0;return f(!0),B.getBlockLibrary().then(I=>{g&&h(I.blocks)}).finally(()=>{g&&f(!1)}),()=>{g=!1}},[v,a]);const b=n0(u,c.authoredDomains),w=b.includes(n)?n:"",C=[...Jn(c.authoredDomains).filter(g=>b.includes(g.value)),...b.includes("uncategorized")?[{value:"uncategorized",label:"Unassigned"}]:[]],x=r0(u,w,t,c.authoredDomains),E=p.useMemo(()=>U0(x,w),[x,w]),P=w==="uncategorized"?"unassigned":w||"all domains",A=g=>{if(o){o(g);return}const I={name:g.path.split("/").pop()??g.name,path:g.path,type:"block",folder:"blocks"};c.files.some(T=>T.path===g.path)||l({type:"FILE_ADDED",file:I}),B.openBlockStudio(g.path).then(T=>l({type:"OPEN_BLOCK_STUDIO",file:I,payload:T}))};return d?s.jsx(hr,{text:"Loading blocks…",t:e}):u.length===0?s.jsx(hr,{text:"No blocks yet.",t:e}):s.jsxs("div",{children:[s.jsx(zp,{id:"block-domain-filter",ariaLabel:"Block domain",value:w,options:C,onChange:g=>r==null?void 0:r(g),summary:s.jsxs(s.Fragment,{children:[x.length," block",x.length===1?"":"s"," · ",P]}),t:e}),x.length===0?s.jsx(hr,{text:t?`No ${P} blocks match this search.`:w?`No blocks in ${w} yet.`:"No blocks yet.",t:e}):s.jsx(Wp,{nodes:E,depth:0,expandAll:!!t.trim(),expandedFolders:m,onToggleFolder:g=>S(I=>{const T=new Set(I);return T.has(g)?T.delete(g):T.add(g),T}),onOpen:A,onDelete:i,t:e})]})}function Wp({nodes:e,depth:t,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:a,t:c}){return s.jsx(s.Fragment,{children:e.map(l=>{if(l.kind==="block")return s.jsx(hk,{block:l.block,depth:t,t:c,onOpen:()=>i(l.block),onDelete:a?()=>a(l.block):void 0},l.block.path);const u=n||r.has(l.path);return s.jsxs(qe.Fragment,{children:[s.jsxs("button",{type:"button",onClick:()=>o(l.path),title:l.path,style:{...qp(c),paddingLeft:10+t*16,borderBottom:"none",fontWeight:650},children:[u?s.jsx(_a,{size:13,color:c.textMuted}):s.jsx(Is,{size:13,color:c.textMuted}),u?s.jsx(bp,{size:14,color:c.accent}):s.jsx(ro,{size:14,color:c.textMuted}),s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},children:l.name}),s.jsx("span",{style:{fontSize:10,color:c.textMuted},children:Kp(l.children)})]}),u?s.jsx(Wp,{nodes:l.children,depth:t+1,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:a,t:c}):null]},`folder:${l.path}`)})})}function Kp(e){return e.reduce((t,n)=>t+(n.kind==="block"?1:Kp(n.children)),0)}function hk({block:e,depth:t=0,t:n,onOpen:r,onDelete:o}){const i=String(e.status??"draft"),a=ik[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(Oa,{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:a}}),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(Sp,{size:13})}):null]})}const Ho=(e,t)=>`https://cdn.simpleicons.org/${e}/${t}`,mk={duckdb:[Ho("duckdb","FFF000")],file:[Ho("duckdb","FFF000")],snowflake:[Ho("snowflake","29B5E8")],databricks:[Ho("databricks","FF3621")]},gk={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"};function yk({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 Yr({driver:e,size:t=16,fallbackColor:n}){const r=mk[e]??[],o=n??gk[e]??"#888",[i,a]=p.useState(0);return r.length===0||i>=r.length?s.jsx(yk,{size:t,color:o}):s.jsx("img",{src:r[i],alt:`${e} logo`,width:t,height:t,loading:"lazy",onError:()=>a(i+1),style:{flexShrink:0,display:"block",objectFit:"contain"}})}function bk(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 Go="http://127.0.0.1:11434";function xk({t:e,onStatus:t}){const[n,r]=p.useState("hashed"),[o,i]=p.useState(Go),[a,c]=p.useState(""),[l,u]=p.useState(""),[h,d]=p.useState(!1),[f,m]=p.useState({ollama:[],openai:[]}),[S,v]=p.useState([]),[b,w]=p.useState(!1),[j,C]=p.useState({id:"",semantic:!1,reindexRequired:!1}),[x,E]=p.useState(null),[P,A]=p.useState(null),[g,I]=p.useState(null),T=p.useCallback($=>{r($.settings.provider),i($.settings.endpoint||Go),c($.settings.model),d($.settings.apiKeySet),C({id:$.activeProviderId,semantic:$.semantic,reindexRequired:$.reindexRequired})},[]),O=p.useCallback(async $=>{try{const X=await B.listEmbeddingModels($);m(X.catalog),v(X.installed),w(X.ollamaReachable)}catch{}},[]);p.useEffect(()=>{(async()=>{try{const $=await B.getEmbeddingSettings();T($),await O($.settings.endpoint||Go)}catch($){A($ instanceof Error?$.message:String($))}})()},[T,O]);const _=async($,X)=>{E($),A(null),I(null);try{await X()}catch(W){A(W instanceof Error?W.message:String(W))}finally{E(null)}},M=($,X)=>_("save",async()=>{const W=await B.saveEmbeddingSettings({provider:$,...$==="ollama"?{endpoint:o}:{},...X?{model:X}:{},...$==="openai"&&l?{apiKey:l}:{}});r($),c(X),l&&(d(!0),u("")),C({id:W.activeProviderId,semantic:W.semantic,reindexRequired:W.reindexRequired}),t==null||t(W.semantic?"Semantic embeddings enabled. Re-index to apply them to your catalog.":"Using the offline hashed embedder — retrieval stays lexical.")}),q=n==="openai"?f.openai:f.ollama,G={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"},H={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%"},L=$=>({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:G,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:j.semantic?"var(--status-success-bg)":"var(--status-warning-bg)",color:j.semantic?"var(--status-success)":"var(--status-warning)",border:`1px solid ${j.semantic?"var(--status-success-border)":"var(--status-warning-border)"}`},children:[j.semantic?s.jsx(zS,{size:11}):s.jsx(BS,{size:11}),j.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"&&M("hashed","")},style:{...L(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 O(o),style:H,placeholder:Go}),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 ",h?"(stored — leave blank to keep)":""]}),s.jsx("input",{type:"password",value:l,onChange:$=>u($.target.value),style:{...H,marginTop:4},placeholder:h?"••••••••":"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:q.map($=>{const X=n==="openai"||S.includes($.model),W=a===$.model;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"9px 11px",borderRadius:8,border:`1px solid ${W?e.accent:e.btnBorder}`,background:W?`${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})]}),X?s.jsx("button",{type:"button",onClick:()=>void M(n,$.model),disabled:x!==null,style:L(W),children:W?s.jsxs(s.Fragment,{children:[s.jsx(xv,{size:12})," In use"]}):"Use this"}):s.jsx("button",{type:"button",disabled:x!==null||!b,onClick:()=>void _(`install:${$.model}`,async()=>{await B.installEmbeddingModel($.model,o),await O(o),await B.saveEmbeddingSettings({provider:"ollama",endpoint:o,model:$.model}),c($.model);const te=await B.getEmbeddingSettings();T(te),t==null||t(`${$.model} installed and selected. Re-index to apply it.`)}),style:L(!0),children:x===`install:${$.model}`?s.jsxs(s.Fragment,{children:[s.jsx(Un,{size:12,className:"dql-spin"})," Installing…"]}):s.jsxs(s.Fragment,{children:[s.jsx(gp,{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:x!==null,onClick:()=>void _("test",async()=>{const $=await B.testEmbeddingProvider();t==null||t(`${$.providerId} responded in ${$.elapsedMs} ms (${$.dimensions} dims).`)}),style:L(),children:[x==="test"?s.jsx(Un,{size:12,className:"dql-spin"}):null," Test"]}),s.jsxs("button",{type:"button",disabled:x!==null,onClick:()=>void _("reindex",async()=>{const $=await B.reindexEmbeddings(),X=await B.getEmbeddingSettings();T(X);const W=bk($,X);I(W),t==null||t(W.message)}),style:L(j.reindexRequired),children:[x==="reindex"?s.jsx(Un,{size:12,className:"dql-spin"}):s.jsx(ps,{size:12}),x==="reindex"?"Re-indexing…":"Re-index catalog"]}),s.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.fontMono},children:["active: ",j.id||"—"]})]}),j.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."}),x==="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."}),g&&s.jsx("div",{role:g.ok?"status":"alert",style:{fontSize:11.5,color:g.ok?"var(--status-success)":"var(--status-error)",marginTop:8,lineHeight:1.5},children:g.message}),P&&s.jsx("div",{style:{fontSize:11.5,color:e.error,marginTop:8,lineHeight:1.5},children:P})]})}function vk({values:e,onChange:t,placeholder:n,style:r,ariaLabel:o,title:i,disabled:a}){const c=e.join(", "),[l,u]=p.useState(c),h=p.useRef(!1);return p.useEffect(()=>{h.current||u(c)},[c]),s.jsx("input",{type:"text",value:l,disabled:a,"aria-label":o,title:i,placeholder:n,style:r,onFocus:()=>{h.current=!0},onBlur:()=>{h.current=!1,u(fl(l).join(", "))},onChange:d=>{u(d.target.value),t(fl(d.target.value))}})}function fl(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Sk(e){var t;return((t=e.evaluation)==null?void 0:t.status)==="failed"?"Rerun checks & approve":"Run checks & approve"}function wk(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 kk(e,t,n){const r=n.trim();return{...e,[t]:r||void 0}}async function Ck(e,t){try{return await e()}finally{await t()}}const jk=["claude-code","codex","anthropic","openai","gemini","ollama","custom-openai"],Ek=["claude-code","codex"],Tk=["anthropic","openai","gemini","ollama","custom-openai"];function Vp(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 ti({includeMemory:e=!0,embedded:t=!1,section:n,editorMode:r="settings",onProviderConfigured:o}){const i=Qe[Ge(A=>A.themeMode)],[a,c]=p.useState([]),[l,u]=p.useState([]),[h,d]=p.useState({}),[f,m]=p.useState({path:"",entries:[],warnings:[]}),[S,v]=p.useState([]),[b,w]=p.useState(!0),[j,C]=p.useState(null),x=async()=>{w(!0);try{const A=!n||n==="providers",g=e&&(!n||n==="memory"),I=!n||n==="advanced",[T,O,_,M]=await Promise.all([I?B.getSettingsEnvStatus():Promise.resolve({groups:[]}),A?B.getProviderSettings():Promise.resolve({providers:[]}),I?B.getRemoteMcpSettings():Promise.resolve({settings:{path:"",entries:[],warnings:[]}}),g?B.listAgentMemory():Promise.resolve({memories:[]})]);c(T.groups),u(O.providers),m(_.settings),v(M.memories)}finally{w(!1)}};p.useEffect(()=>{x()},[]),p.useEffect(()=>{if(b||n&&n!=="providers")return;let A=!1;return B.getProviderCliStatus().then(g=>{A||d(g.status??{})}),()=>{A=!0}},[b]);const E=p.useMemo(()=>l.filter(A=>A.enabled&&A.configured).length,[l]),P=l.find(A=>A.active&&A.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:i.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(Ik,{configured:E,total:l.length||jk.length,activeLabel:P==null?void 0:P.label,t:i})]}),j&&s.jsx("div",{style:{marginTop:14,border:`1px solid ${i.headerBorder}`,borderRadius:8,padding:"10px 12px",fontSize:12,color:i.textSecondary,background:i.cellBg},children:j}),b?s.jsx("div",{style:{marginTop:24,color:i.textSecondary},children:"Loading settings..."}):s.jsxs(s.Fragment,{children:[n==="providers"&&s.jsxs(s.Fragment,{children:[s.jsx(Ok,{providers:l,cliStatus:h,t:i,onSaved:A=>u(A),onStatus:C,editorMode:r,onProviderConfigured:o}),s.jsx(xk,{t:i,onStatus:C})]}),!n&&s.jsxs("section",{style:{marginTop:22},children:[s.jsx(or,{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:i}),s.jsx(ml,{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:i}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:Ek.map(A=>{const g=l.find(I=>I.id===A);return g?s.jsx(bl,{provider:g,cliStatus:h[A],t:i,onSaved:I=>u(I),onStatus:C},A):null})}),s.jsx(ml,{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:i}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:Tk.map(A=>{const g=l.find(I=>I.id===A);return g?s.jsx(bl,{provider:g,t:i,onSaved:I=>u(I),onStatus:C},A):null})})]}),(!n||n==="memory")&&e&&s.jsxs("section",{style:{marginTop:n?0:22},children:[s.jsx(or,{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:i}),s.jsx(Pk,{memories:S,t:i,onChange:v,onStatus:C}),s.jsx(_k,{t:i,onStatus:C})]}),n==="advanced"&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsx(or,{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:i}),s.jsx(hl,{settings:f,t:i,onChange:m,onStatus:C})]}),s.jsxs("section",{style:{marginTop:22},children:[s.jsx(or,{title:"Runtime status",detail:"Environment variables remain supported for Docker, CI, and shell-based setup.",t:i}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:a.map(A=>s.jsx(vl,{group:A,t:i},A.id))})]})]}),!n&&s.jsxs("details",{style:{marginTop:22,border:`1px solid ${i.headerBorder}`,borderRadius:10,background:i.cellBg,overflow:"hidden"},children:[s.jsxs("summary",{style:{cursor:"pointer",padding:"13px 16px",fontSize:13,fontWeight:650,listStyle:"none",color:i.textPrimary},children:["Advanced — MCP connections & runtime status",s.jsx("span",{style:{color:i.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(or,{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:i}),s.jsx(hl,{settings:f,t:i,onChange:m,onStatus:C})]}),s.jsxs("section",{style:{marginTop:22},children:[s.jsx(or,{title:"Runtime status",detail:"Environment variables remain supported for Docker, CI, and shell-based setup.",t:i}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(320px, 1fr))",gap:14},children:a.map(A=>s.jsx(vl,{group:A,t:i},A.id))})]})]})]})]})]})}function hl({settings:e,t,onChange:n,onStatus:r}){const[o,i]=p.useState(e.entries),[a,c]=p.useState("form"),[l,u]=p.useState(()=>Ur(e.entries)),[h,d]=p.useState(null),[f,m]=p.useState(!1);p.useEffect(()=>{i(e.entries),u(Ur(e.entries)),d(null)},[e]);const S=O=>{i(O),u(Ur(O)),d(null)},v=(O,_)=>{S(o.map((M,q)=>q===O?Hn({...M,..._}):M))},b=O=>{S(o.filter((_,M)=>M!==O))},w=()=>{S([...o,{kind:"server",name:"",url:"",enabled:!0,trusted:!1,providers:["openai","anthropic"]}])},j=()=>{S([...o,{kind:"connector",name:"",connectorId:"connector_googledrive",enabled:!0,trusted:!1,providers:["openai"]}])},C=O=>{O==="json"&&u(Ur(o)),d(null),c(O)},x=()=>{const O=Mk(l);return i(O),u(Ur(O)),d(null),O},E=()=>{try{x()}catch(O){d(O instanceof Error?O.message:String(O))}},P=()=>{try{x(),c("form"),r("MCP JSON applied.")}catch(O){d(O instanceof Error?O.message:String(O))}},A=async()=>{m(!0);try{const O=a==="json"?x():o,_=await B.saveRemoteMcpSettings(O.map(q=>Hn(q)));n(_.settings);const M=_.settings.warnings.length?` ${_.settings.warnings.join(" ")}`:"";r(`MCP connections saved.${M}`)}catch(O){const _=O instanceof Error?O.message:String(O);a==="json"&&d(_),r(_)}finally{m(!1)}},g=o.filter(O=>O.enabled&&O.trusted).length,I=o.filter(O=>O.kind==="server").length,T=o.filter(O=>O.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:[g," trusted connection",g===1?"":"s"," available to SDK providers"]}),s.jsxs("div",{style:{fontSize:11,color:t.textMuted,marginTop:3},children:[I," remote server",I===1?"":"s"," / ",T," OpenAI connector",T===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:()=>C("form"),style:Sl(t,a==="form"),children:"Form"}),s.jsx("button",{type:"button",onClick:()=>C("json"),style:Sl(t,a==="json"),children:"JSON import"})]}),s.jsx("button",{type:"button",onClick:w,style:Ft(t,!1),children:"Add MCP server"}),s.jsx("button",{type:"button",onClick:j,style:Ft(t,!1),children:"Add OpenAI connector"}),s.jsx("button",{type:"button",onClick:A,disabled:f,style:Ft(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(ni,{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(ni,{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(ni,{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(" ")}),a==="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:l,onChange:O=>{u(O.target.value),d(null)},spellCheck:!1,rows:18,style:{...Ne(t),width:"100%",minHeight:360,resize:"vertical",fontFamily:t.fontMono,fontSize:12,lineHeight:1.45}}),h&&s.jsx("div",{style:{color:"#b42318",fontSize:12,marginTop:8},children:h}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:10},children:[s.jsx("button",{type:"button",onClick:E,style:Ft(t,!1),children:"Format JSON"}),s.jsx("button",{type:"button",onClick:P,style:Ft(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((O,_)=>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:O.kind,onChange:M=>v(_,{kind:M.target.value==="connector"?"connector":"server",providers:M.target.value==="connector"?["openai"]:O.providers}),style:{...Ne(t),width:116},children:[s.jsx("option",{value:"server",children:"Server"}),s.jsx("option",{value:"connector",children:"Connector"})]}),s.jsx("input",{value:O.name,onChange:M=>v(_,{name:M.target.value}),placeholder:"Name",style:{...Ne(t),flex:1}}),s.jsx("button",{type:"button",onClick:()=>b(_),style:Ft(t,!1),children:"Remove"})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:10},children:[O.kind==="connector"?s.jsx("input",{value:O.connectorId??"",onChange:M=>v(_,{connectorId:M.target.value}),placeholder:"connector_googledrive",style:Ne(t)}):s.jsx("input",{value:O.url??"",onChange:M=>v(_,{url:M.target.value}),placeholder:"https://example.com/mcp or /sse",style:Ne(t)}),s.jsx("input",{value:O.description??"",onChange:M=>v(_,{description:M.target.value}),placeholder:"Description shown to the model",style:Ne(t)}),s.jsx("input",{value:O.authorizationTokenEnv??"",onChange:M=>v(_,{authorizationTokenEnv:M.target.value}),placeholder:"Authorization token env var",style:Ne(t)}),s.jsx("input",{value:O.authorizationToken??"",onChange:M=>v(_,{authorizationToken:M.target.value}),type:"password",placeholder:O.hasAuthorizationToken?`Leave blank to keep ${O.authorizationTokenPreview??"stored token"}`:"Optional OAuth token",style:Ne(t)}),s.jsx(vk,{values:O.allowedTools??[],onChange:M=>v(_,{allowedTools:M}),placeholder:"Allowed tools, comma separated",style:Ne(t)})]}),s.jsxs("div",{style:{display:"flex",gap:12,flexWrap:"wrap",marginTop:10},children:[s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:O.enabled,onChange:M=>v(_,{enabled:M.target.checked})})," Enabled"]}),s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:O.trusted,onChange:M=>v(_,{trusted:M.target.checked})})," Trusted"]}),s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:!!O.deferLoading,onChange:M=>v(_,{deferLoading:M.target.checked})})," Defer tools"]}),s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:(O.providers??[]).includes("openai"),onChange:M=>v(_,{providers:kl(O.providers,"openai",M.target.checked)})})," OpenAI"]}),s.jsxs("label",{style:qr(t),children:[s.jsx("input",{type:"checkbox",checked:(O.providers??[]).includes("anthropic"),disabled:O.kind==="connector",onChange:M=>v(_,{providers:kl(O.providers,"anthropic",M.target.checked)})})," Anthropic"]})]})]},`${O.kind}-${O.name||_}`))})]})}function ni({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 Ak({status:e,command:t,loginCmd:n,t:r}){let o=r.textMuted,i=r.textMuted,a="Checking for the CLI…";if(e)if(!e.installed)o=r.warning,i=r.warning,a=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,a=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 c=[e.email,e.subscriptionType?`${e.subscriptionType} plan`:e.authMethod].filter(Boolean).join(" · ");a=s.jsxs(s.Fragment,{children:["Signed in",c?s.jsxs(s.Fragment,{children:[" — ",c]}):"",". 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:a})]})}function ml({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 Hp(e){return e==="codex"?"codex":"claude"}function Gp({oauthProvider:e,label:t,model:n,setModel:r,cliStatus:o,command:i,loginCmd:a,t:c,onStatus:l,onConnected:u}){const[h,d]=p.useState(null),[f,m]=p.useState(!1),S=p.useRef(null),v=p.useRef(!0),b=e==="codex"?"ChatGPT":"Claude",w=p.useCallback(()=>{S.current!==null&&(window.clearInterval(S.current),S.current=null)},[]);p.useEffect(()=>(v.current=!0,B.getOAuthStatus(e).then(x=>{v.current&&d(x)}).catch(()=>{}),()=>{v.current=!1,w()}),[e,w]);const j=async()=>{m(!0);try{const x=await B.startOAuth(e);d(x),window.open(x.url,"_blank","noopener,noreferrer"),l(`Opened your browser to sign in to ${b}. Complete it there — this updates automatically.`);const E=Date.now();w(),S.current=window.setInterval(async()=>{const P=await B.getOAuthStatus(e).catch(()=>null);if(!v.current){w();return}P&&d(P),P!=null&&P.connected?(w(),m(!1),u(P.defaultModel)):Date.now()-E>300*1e3&&(w(),m(!1),l(`${b} sign-in timed out. Try again.`))},2500)}catch(x){m(!1),l(x instanceof Error?x.message:String(x))}},C=async()=>{m(!0),w();try{d(await B.signOutOAuth(e)),l(`Signed out of ${b}.`)}catch(x){l(x instanceof Error?x.message:String(x))}finally{m(!1)}};if(h!=null&&h.connected){const x=h.models.length>0?h.models:[h.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]}),h.email?s.jsxs("span",{style:{color:c.textSecondary},children:["as ",h.email]}):null]}),s.jsx("label",{style:{fontSize:11,color:c.textSecondary,fontWeight:600},children:"Model"}),s.jsx("select",{value:n||h.defaultModel,onChange:E=>r(E.target.value),style:Ne(c),children:x.map(E=>s.jsx("option",{value:E,children:E},E))}),s.jsx("div",{children:s.jsx("button",{type:"button",onClick:C,disabled:f,style:Ft(c,!1),children:"Sign out"})})]})}return s.jsxs("div",{style:{display:"grid",gap:8},children:[s.jsx("button",{type:"button",onClick:j,disabled:f,style:Ft(c,!0),children:f||h!=null&&h.pending?`Waiting for ${b}…`:`Sign in with ${b}`}),s.jsxs("div",{style:{fontSize:12,color:c.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:c.textSecondary,cursor:"pointer"},children:"Prefer the CLI?"}),s.jsxs("div",{style:{marginTop:6,display:"grid",gap:6},children:[s.jsx(Ak,{status:o,command:i,loginCmd:a,t:c}),s.jsxs("div",{style:{fontSize:11.5,color:c.textSecondary,lineHeight:1.5},children:["Or install the ",s.jsx("code",{children:i})," CLI and run ",s.jsxs("code",{children:[i," ",a]}),", then Enable + Save."]})]})]})]})}const ts=[{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"}}],gl={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 Rk(e){if(!e)return"claude";const t=ts.find(n=>Object.values(n.modes).includes(e));return(t==null?void 0:t.key)??"claude"}function Ok({providers:e,cliStatus:t,t:n,onSaved:r,onStatus:o,editorMode:i,onProviderConfigured:a}){var F;const c=e.find(K=>K.active&&K.configured),[l,u]=p.useState(()=>Rk(c==null?void 0:c.id)),h=ts.find(K=>K.key===l)??ts[0],d=Object.keys(h.modes),[f,m]=p.useState(()=>d.find(oe=>h.modes[oe]===(c==null?void 0:c.id))??d[0]),S=d.includes(f)?f:d[0],v=h.modes[S],b=e.find(K=>K.id===v),[w,j]=p.useState(""),[C,x]=p.useState((b==null?void 0:b.baseUrl)??""),[E,P]=p.useState((b==null?void 0:b.model)??""),[A,g]=p.useState((b==null?void 0:b.reasoningEffort)??"auto"),[I,T]=p.useState(!1),[O,_]=p.useState({state:"idle"}),[M,q]=p.useState({state:"idle"});p.useEffect(()=>{j(""),x((b==null?void 0:b.baseUrl)??""),P((b==null?void 0:b.model)??""),g((b==null?void 0:b.reasoningEffort)??"auto"),q({state:"idle"})},[v,b==null?void 0:b.baseUrl,b==null?void 0:b.model,b==null?void 0:b.reasoningEffort]);const G=async()=>{if(!c)return;_({state:"testing"});const K=Date.now(),oe=await B.testProviderSettings(c.id,{}),ee=oe.ok!==!1;_({state:"done",ok:ee,message:oe.message,seconds:((Date.now()-K)/1e3).toFixed(1)})},J=()=>{var K;return v==="custom-openai"&&!C.trim()?"Custom OpenAI-compatible providers require a Base URL.":v==="custom-openai"&&!E.trim()?"Custom OpenAI-compatible providers require a model.":S==="api"&&v!=="custom-openai"&&!w.trim()&&!(b!=null&&b.hasApiKey)?`Add an API key${(K=b==null?void 0:b.envVars)!=null&&K[0]?` or set ${b.envVars[0]}`:""}.`:S==="local"&&!C.trim()&&!E.trim()&&!(b!=null&&b.configured)?"Set an Ollama endpoint or model before testing.":null},H=async()=>{const K=J();if(K)return q({state:"done",ok:!1,message:K}),!1;q({state:"testing"});const oe=await B.testProviderSettings(v,{apiKey:w||void 0,baseUrl:C||void 0,model:E||void 0});return q({state:"done",ok:oe.ok,message:oe.message}),oe.ok},L=async()=>{T(!0);try{if(!await H()){o("Test failed. Your existing provider configuration was not changed.");return}const oe=await B.saveProviderSettings({id:v,enabled:!0,apiKey:w||void 0,baseUrl:C,model:E,reasoningEffort:A});r(oe.providers);const ee=oe.providers.find(ce=>ce.id===v);ee&&(a==null||a(ee)),o(`${h.label} passed its test and is now the active provider.`)}catch(K){o(K instanceof Error?K.message:String(K))}finally{T(!1)}},$=async K=>{const oe=E||K;P(oe);try{const ee=await B.saveProviderSettings({id:v,enabled:!0,model:oe});r(ee.providers);const ce=ee.providers.find(ke=>ke.id===v);ce&&(a==null||a(ce)),o(`${h.label} subscription configured and activated. Run Test to verify the next governed request.`)}catch(ee){o(ee instanceof Error?ee.message:String(ee))}},X={fontSize:11,fontWeight:650,color:n.textSecondary},W={...Ne(n),borderRadius:8},te=S==="subscription"?"Uses your existing plan through the provider’s sign-in — nothing billed per token.":S==="local"?"Everything runs on this machine — no data leaves your network.":"Keys stay in .dql/ and are never returned raw.";return s.jsxs("div",{style:{width:"min(680px, 100%)",display:"flex",flexDirection:"column",gap:16},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:17,fontWeight:700,color:n.textPrimary},children:"AI provider"}),s.jsxs("div",{style:{fontSize:12.5,color:n.textMuted,marginTop:3,lineHeight:1.5},children:["AI is optional. Without it, deterministic queries, dbt metadata, connections, and governed non-AI paths remain available. Keys stay in ",s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:11.5},children:".dql/"})," and are never returned raw."]})]}),c?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(vp,{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 · ",c.label,c.model?` — ${c.model}`:""]}),s.jsx("div",{style:{fontSize:11.5,color:O.state==="done"&&O.ok===!1?"var(--status-error)":"var(--status-success)",marginTop:2},children:O.state==="testing"?"Testing…":O.state==="done"?O.ok?`Test passed · ${O.seconds}s`:O.message||"Test failed":c.source==="env"?"Configured from environment — run Test to verify":"Configured — run Test to verify reachability"})]}),s.jsx("button",{type:"button",onClick:()=>void G(),disabled:O.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:O.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:X,children:"Provider"}),s.jsx("select",{value:h.key,onChange:K=>{u(K.target.value),m("subscription")},style:W,children:ts.map(K=>s.jsx("option",{value:K.key,children:K.label},K.key))})]})}),s.jsxs("div",{children:[s.jsx("span",{style:{...X,display:"block",marginBottom:6},children:"How do you want to connect?"}),s.jsx("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:d.map(K=>{const oe=K===S;return s.jsxs("button",{type:"button",onClick:()=>m(K),style:{display:"inline-flex",alignItems:"center",gap:7,padding:"8px 13px",borderRadius:9,border:`1.5px solid ${oe?n.accent:n.headerBorder}`,background:oe?"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 ${oe?n.accent:"var(--border-strong)"}`,background:oe?n.accent:n.cellBg,boxShadow:oe?`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:gl[K].label}),s.jsx("span",{style:{fontSize:10,color:n.textMuted},children:gl[K].hint})]})]},K)})})]}),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(Gp,{oauthProvider:Hp(v),label:b.label,model:E,setModel:P,cliStatus:t[v],command:b.command,loginCmd:v==="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:X,children:"API key"}),s.jsx("input",{type:"password",value:w,onChange:K=>j(K.target.value),placeholder:b!=null&&b.hasApiKey?"Leave blank to keep existing key":"API key",style:{...W,fontFamily:n.fontMono}})]}),(F=b==null?void 0:b.envVars)!=null&&F[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:X,children:"Host"}),s.jsx("input",{value:C,onChange:K=>x(K.target.value),placeholder:"http://localhost:11434",style:{...W,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(yl,{providerId:v,provider:b,mode:S,baseUrl:C,setBaseUrl:x,model:E,setModel:P,reasoningEffort:A,setReasoningEffort:g,t:n,input:W,fieldLabel:X})})]}):s.jsx("div",{style:{display:"grid",gap:10},children:s.jsx(yl,{providerId:v,provider:b,mode:S,baseUrl:C,setBaseUrl:x,model:E,setModel:P,reasoningEffort:A,setReasoningEffort:g,t:n,input:W,fieldLabel:X})}),M.state!=="idle"?s.jsx("div",{role:M.ok===!1?"alert":"status",style:{fontSize:11.5,lineHeight:1.5,color:M.state==="testing"?n.textMuted:M.ok?"var(--status-success)":"var(--status-error)"},children:M.state==="testing"?"Testing these unsaved values through the governed runtime…":M.message}):null,s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,paddingTop:4,borderTop:"1px solid var(--border-subtle)"},children:[s.jsx("span",{style:{fontSize:10.5,color:n.textMuted,flex:1},children:te}),s.jsx("button",{type:"button",onClick:()=>void H(),disabled:I||M.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:M.state==="testing"?"Testing…":"Test unsaved values"}),s.jsx("button",{type:"button",onClick:()=>void L(),disabled:I,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:I?.7:1},children:I?"Testing…":"Test, save & activate"})]})]})]})}function yl({providerId:e,provider:t,mode:n,baseUrl:r,setBaseUrl:o,model:i,setModel:a,reasoningEffort:c,setReasoningEffort:l,t:u,input:h,fieldLabel:d}){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:d,children:e==="custom-openai"?"Base URL (required)":"Base URL (optional)"}),s.jsx("input",{value:r,onChange:f=>o(f.target.value),placeholder:Vp(e),style:{...h,fontFamily:u.fontMono}})]}):null,s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:d,children:e==="custom-openai"?"Model (required)":"Model (optional)"}),s.jsx("input",{value:i,onChange:f=>a(f.target.value),placeholder:(t==null?void 0:t.model)||"Provider default",style:h})]}),t!=null&&t.supportsReasoningEffort&&n==="api"?s.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsx("span",{style:d,children:"Reasoning effort"}),s.jsxs("select",{value:c,onChange:f=>l(f.target.value),style:h,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 bl({provider:e,cliStatus:t,t:n,onSaved:r,onStatus:o}){const[i,a]=p.useState(e.enabled),[c,l]=p.useState(""),[u,h]=p.useState(e.baseUrl??""),[d,f]=p.useState(e.model??""),[m,S]=p.useState(e.reasoningEffort??"auto"),[v,b]=p.useState(!1),[w,j]=p.useState(!1),[C,x]=p.useState(null),E=e.authMode==="subscription_cli",P=e.id==="claude-code"?"/login":"login",A=e.supportsReasoningEffort===!0&&!E&&e.id!=="ollama";p.useEffect(()=>{a(e.enabled),h(e.baseUrl??""),f(e.model??""),S(e.reasoningEffort??"auto"),l(""),x(null)},[e.id,e.enabled,e.baseUrl,e.model,e.reasoningEffort]);const g=async()=>{b(!0);try{const O=await B.saveProviderSettings({id:e.id,enabled:i,apiKey:c||void 0,baseUrl:u,model:d,reasoningEffort:m});r(O.providers),o(`${e.label} settings saved.`)}catch(O){o(O instanceof Error?O.message:String(O))}finally{b(!1)}},I=async()=>{j(!0),x(null);const O=await B.testProviderSettings(e.id,{apiKey:c||void 0,baseUrl:u||void 0,model:d||void 0}),_=O.ok!==!1;x({ok:_,message:O.message||(_?`${e.label} is reachable.`:`${e.label} test failed.`)}),j(!1)},T=async O=>{const _=d||O;f(_),a(!0);try{const M=await B.saveProviderSettings({id:e.id,enabled:!0,model:_});r(M.providers),o(`${e.label} connected and activated.`)}catch(M){o(M instanceof Error?M.message:String(M))}};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:$k(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:O=>a(O.target.checked)}),"Enabled"]})]}),s.jsxs("div",{style:{display:"grid",gap:8,marginTop:12},children:[E?s.jsx(Gp,{oauthProvider:Hp(e.id),label:e.label,model:d,setModel:f,cliStatus:t,command:e.command,loginCmd:P,t:n,onStatus:o,onConnected:T}):s.jsxs(s.Fragment,{children:[e.id!=="ollama"&&s.jsx("input",{value:c,onChange:O=>l(O.target.value),type:"password",placeholder:e.hasApiKey?"Leave blank to keep existing key":"API key",style:Ne(n)}),s.jsx("input",{value:u,onChange:O=>h(O.target.value),placeholder:Vp(e.id),style:Ne(n)})]}),!E&&s.jsx("input",{value:d,onChange:O=>f(O.target.value),placeholder:"Default model",style:Ne(n)}),A&&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:m,onChange:O=>S(O.target.value),style:Ne(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:m==="auto"?"The agent spends more reasoning on SQL generation, gates, and repairs, and less on chat.":`Caps every request at ${m} reasoning.`})]})]}),s.jsxs("div",{style:{display:"flex",gap:8,marginTop:12},children:[s.jsx("button",{type:"button",onClick:g,disabled:v||w,style:Ft(n,!0),children:e.active?"Save active provider":"Save and use"}),s.jsx("button",{type:"button",onClick:I,disabled:v||w,style:Ft(n,!1),children:w?"Testing…":"Test"})]}),C&&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:C.ok?n.success:n.error,background:`${C.ok?n.success:n.error}12`,border:`1px solid ${C.ok?n.success:n.error}40`},children:[s.jsx("span",{style:{flexShrink:0,fontWeight:700},children:C.ok?"✓":"✗"}),s.jsx("span",{children:C.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 rt(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 xl(e){return[...new Map(e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean).map(t=>[t.toLowerCase(),t])).values()].slice(0,8)}function _k({t:e,onStatus:t}){const[n,r]=p.useState([]),[o,i]=p.useState({candidate:0,approved:0,rejected:0,retired:0}),[a,c]=p.useState(null),[l,u]=p.useState(!1),[h,d]=p.useState({}),[f,m]=p.useState(null),S=p.useCallback(async()=>{try{const g=await B.listAgentHints();r(g.hints??[]),i(g.counts??{candidate:0,approved:0,rejected:0,retired:0})}catch{r([])}finally{u(!0)}},[]);p.useEffect(()=>{S()},[S]);const v=async(g,I)=>{var T;c(g.id),t(null);try{const O=(T=h[g.id])==null?void 0:T.trim(),_=await Ck(()=>B.reviewAgentHint(g.id,I,O),S);_.ok?t(I==="approved"?`Approved. DQL will apply "${g.title}" to matching questions.`:`Rejected. "${g.title}" will not be used.`):t(_.error??`Could not ${I==="approved"?"approve":"reject"} this correction.`)}catch(O){t(O instanceof Error?O.message:String(O))}finally{c(null)}},b=async(g,I,T)=>{var O;c(g.id),t(null);try{const _=await B.transitionAgentHint(g.id,{action:I,targetHintId:T,note:((O=h[g.id])==null?void 0:O.trim())||void 0});t(_.ok?I==="retire"?`Retired "${g.title}". It is excluded from future answers.`:I==="reopen"?`Reopened "${g.title}" as a candidate.`:`Resolved the conflict. "${g.title}" is authoritative.`:_.error??`Could not ${I} this hint.`),await S()}catch(_){t(_ instanceof Error?_.message:String(_))}finally{c(null)}},w=async()=>{if(f){c(f.id),t(null);try{const g=await B.updateAgentHint(f.id,{title:f.title,guidance:f.guidance,lesson:{...rt(f),rule:f.guidance},correctedSql:f.correctedSql,scope:f.scope});g.ok?(t(`Updated "${f.title}" and refreshed its current dependencies.`),m(null)):t(g.error??"Could not update this candidate."),await S()}catch(g){t(g instanceof Error?g.message:String(g))}finally{c(null)}}},j=async g=>{var I;if(!((I=g.trace)!=null&&I.question)||!g.correctedSql){t("This hint is missing the question or SQL required for an analyst certification request.");return}c(g.id);try{const T=await B.requestCertification({question:g.trace.question,generatedSql:g.correctedSql,domain:g.scope.domain,context:{source:"governed_hint_review",hintId:g.id,evaluationId:g.evaluationId,snapshotId:g.snapshotId}});t(T.ok?`Certification research requested for "${g.title}". Approval of a hint did not certify an asset.`:T.error??"Could not request certification.")}catch(T){t(T instanceof Error?T.message:String(T))}finally{c(null)}},C=n.filter(g=>g.status==="candidate"),x=n.filter(g=>g.status==="approved"),E=n.filter(g=>g.status==="rejected"||g.status==="retired");if(!l)return null;const P=g=>{var I,T,O,_,M,q,G,J,H;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:[(I=g.trace)!=null&&I.question?s.jsxs("div",{children:[s.jsx("b",{children:"Question:"})," ",g.trace.question]}):null,(T=g.trace)!=null&&T.wrongAnswer?s.jsxs("div",{children:[s.jsx("b",{children:"Previous answer:"})," ",g.trace.wrongAnswer]}):null,(O=g.trace)!=null&&O.rationale?s.jsxs("div",{children:[s.jsx("b",{children:"Why the correction is right:"})," ",g.trace.rationale]}):null,s.jsxs("div",{children:[s.jsx("b",{children:"Snapshot:"})," ",g.snapshotId??"missing",(_=g.inspection)!=null&&_.currentSnapshotId?` · current ${g.inspection.currentSnapshotId}`:""]}),s.jsxs("div",{children:[s.jsx("b",{children:"Dependencies:"})," ",((M=g.dependencies)==null?void 0:M.map(L=>`${L.kind}:${L.id}@${L.fingerprint.slice(0,10)}`).join(", "))||"none recorded"]}),s.jsxs("div",{children:[s.jsx("b",{children:"Graph connections:"})," ",(q=g.graphEdges)!=null&&q.length?g.graphEdges.map(L=>`${L.kind.replace(/_/g," ")} → ${L.targetName}`).join(" · "):"none materialized"]}),(G=g.lifecycleErrors)==null?void 0:G.map(L=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:[L.code,":"]})," ",L.message]},`${L.code}-${L.at}`)),g.evaluation?s.jsxs("div",{children:[s.jsxs("b",{children:["Evaluation ",g.evaluation.status,":"]}),g.evaluation.checks.map(L=>s.jsxs("div",{style:{color:L.passed?e.success:e.error},children:[L.passed?"✓":"✕"," ",L.name," — ",L.evidence]},L.name))]}):s.jsxs("div",{children:[s.jsx("b",{children:"Evaluation:"})," not run"]}),(J=g.inspection)==null?void 0:J.checks.map(L=>s.jsxs("div",{style:{color:L.passed?e.success:e.error},children:[L.passed?"✓":"✕"," live ",L.name," — ",L.evidence]},`live-${L.name}`)),(H=g.exclusions)==null?void 0:H.map((L,$)=>s.jsxs("div",{style:{color:e.error},children:[s.jsxs("b",{children:["Excluded: ",L.reason]})," — ",L.detail]},`${L.reason}-${$}`))]})]})},A=g=>{var _,M,q,G,J,H;const I=((_=g.exclusions)==null?void 0:_.filter(L=>L.reason==="conflict"&&L.relatedHintId))??[],T=(f==null?void 0:f.id)===g.id,O=g.status==="approved"&&((M=g.evaluation)==null?void 0:M.status)==="passed"&&((q=g.inspection)==null?void 0:q.state)==="current"&&(((G=g.exclusions)==null?void 0:G.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:g.title}),s.jsx("span",{style:{fontSize:10,color:(J=g.exclusions)!=null&&J.length||((H=g.evaluation)==null?void 0:H.status)==="failed"?e.error:e.success},children:wk(g)})]}),T?s.jsxs(s.Fragment,{children:[s.jsx("input",{value:f.title,onChange:L=>m({...f,title:L.target.value}),placeholder:"Hint title",style:Re(e,{size:"sm"})}),s.jsx("textarea",{value:f.guidance,onChange:L=>m({...f,guidance:L.target.value}),placeholder:"Guidance for matching questions",rows:3,style:{...Re(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:rt(f).category,onChange:L=>m({...f,lesson:{...rt(f),category:L.target.value}}),style:Re(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:rt(f).intentExamples.join(`
437
+ `),onChange:L=>m({...f,lesson:{...rt(f),intentExamples:L.target.value.split(/\r?\n/)}}),onBlur:()=>m({...f,lesson:{...rt(f),intentExamples:xl(rt(f).intentExamples.join(`
438
438
  `))}}),placeholder:"Similar questions, one per line",rows:3,style:{...Re(e,{size:"sm"}),resize:"vertical"}}),s.jsx("textarea",{value:rt(f).avoid.join(`
439
- `),onChange:L=>m({...f,lesson:{...rt(f),avoid:L.target.value.split(/\r?\n/)}}),onBlur:()=>m({...f,lesson:{...rt(f),avoid:bl(rt(f).avoid.join(`
440
- `))}}),placeholder:"Known mistakes to avoid, one per line",rows:2,style:{...Re(e,{size:"sm"}),resize:"vertical"}}),s.jsx("input",{value:rt(f).expectedOutcome??"",onChange:L=>m({...f,lesson:{...rt(f),expectedOutcome:L.target.value||void 0}}),placeholder:"Expected outcome or result shape",style:Re(e,{size:"sm"})})]})]}),s.jsx("textarea",{value:f.correctedSql??"",onChange:L=>m({...f,correctedSql:L.target.value}),placeholder:"Read-only corrected SQL",rows:5,style:{...Re(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(([L,$])=>s.jsxs("label",{style:{display:"grid",gap:3,fontSize:10,color:e.textMuted},children:[$,s.jsx("input",{value:f.scope[L]??"",onChange:X=>m({...f,scope:wk(f.scope,L,X.target.value)}),placeholder:`Optional ${$}`,style:Re(e,{size:"sm"})})]},L))}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void w(),style:Re(e,{variant:"primary",size:"sm",disabled:a===g.id}),children:"Save & recheck"}),s.jsx("button",{type:"button",onClick:()=>m(null),style:Re(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:g.guidance}),g.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:"})," ",g.lesson.category.replace(/_/g," ")]}),g.lesson.intentExamples.length?s.jsxs("div",{children:[s.jsx("b",{children:"Similar questions:"})," ",g.lesson.intentExamples.join(" · ")]}):null,g.lesson.avoid.length?s.jsxs("div",{children:[s.jsx("b",{children:"Avoid:"})," ",g.lesson.avoid.join(" · ")]}):null,g.lesson.expectedOutcome?s.jsxs("div",{children:[s.jsx("b",{children:"Expected:"})," ",g.lesson.expectedOutcome]}):null]}):null,g.correctedSql?s.jsx("pre",{style:{margin:0,fontSize:10.5,fontFamily:e.fontMono,color:e.textMuted,whiteSpace:"pre-wrap",maxHeight:120,overflow:"auto"},children:g.correctedSql}):null,P(g),s.jsx("textarea",{value:h[g.id]??"",onChange:L=>d({...h,[g.id]:L.target.value}),placeholder:"Reviewer note or result assertion (required evidence when this surface cannot execute)",rows:2,style:{...Re(e,{size:"sm"}),resize:"vertical"}}),s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[g.status==="candidate"?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void v(g,"approved"),style:Re(e,{variant:"primary",size:"sm",disabled:a===g.id}),children:a===g.id?"Checking…":vk(g)}),s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>m({...g,lesson:rt(g)}),style:Re(e,{size:"sm",disabled:a===g.id}),children:"Edit candidate"}),s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void v(g,"rejected"),style:Re(e,{variant:"danger",size:"sm",disabled:a===g.id}),children:"Reject"})]}):null,g.status==="approved"?s.jsxs(s.Fragment,{children:[O?s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void j(g),style:Re(e,{variant:"primary",size:"sm",disabled:a===g.id}),children:"Request certification"}):null,s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void b(g,"reopen"),style:Re(e,{size:"sm",disabled:a===g.id}),children:"Reopen & edit"}),s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void b(g,"retire"),style:Re(e,{variant:"danger",size:"sm",disabled:a===g.id}),children:"Retire"}),I.map(L=>s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void b(g,"supersede",L.relatedHintId),style:Re(e,{size:"sm",disabled:a===g.id}),children:"Keep this; supersede conflict"},L.relatedHintId))]}):null,g.status==="retired"?s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void b(g,"reopen"),style:Re(e,{size:"sm",disabled:a===g.id}),children:"Reopen as candidate"}):null,s.jsx("span",{style:{fontSize:10.5,color:e.textMuted},children:[g.scope.dbtModel,g.scope.metric,g.scope.domain].filter(Boolean).join(" · ")||"project-wide"})]})]})]},g.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`:""]})]}),C.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:C.map(A)}),x.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:x.map(A)})]}):null,E.length>0?s.jsxs("details",{style:{marginTop:16},children:[s.jsxs("summary",{style:{cursor:"pointer",fontSize:12,color:e.textSecondary},children:["Rejected & retired history (",E.length,")"]}),s.jsx("div",{style:{display:"grid",gap:8,marginTop:8},children:E.map(A)})]}):null]})}function _k({memories:e,t,onChange:n,onStatus:r}){const[o,i]=p.useState("project"),[a,c]=p.useState(""),[l,u]=p.useState(""),[h,d]=p.useState(""),f=async()=>{const T=await B.listAgentMemory();n(T.memories)},m=async T=>{await B.deleteAgentMemory(T),await f(),r("Memory deleted.")},[S,v]=p.useState(!1),[b,w]=p.useState("all"),[j,C]=p.useState(null),x=T=>T==="project"?{label:"project",bg:"var(--accent-dim)",color:t.accent}:T==="user"?{label:"just me",bg:`${t.textMuted}1f`,color:t.textMuted}:{label:T,bg:"var(--status-success-bg)",color:"var(--status-success)"},E=e.filter(T=>b==="all"?!0:b==="project"?T.scope==="project":T.scope==="user"),P=T=>{C(T.id),i(T.scope),c(T.title),u(T.content),d(T.tags.join(", ")),v(!0)},A=()=>{v(!1),C(null),c(""),u(""),d("")},g=async()=>{if(!l.trim())return;a.trim()||c(l.trim().slice(0,60));const T=a.trim()||l.trim().slice(0,60);await B.saveAgentMemory({scope:o,title:T,content:l,tags:h.split(",").map(O=>O.trim()).filter(Boolean),source:"settings-ui",confidence:.8,importance:o==="project"?.7:.5,enabled:!0}),j&&await B.deleteAgentMemory(j).catch(()=>{}),A(),await f(),r(j?"Memory updated.":"Memory saved.")},I=(T,O)=>s.jsx("button",{type:"button",onClick:()=>w(T),style:{border:"none",borderRadius:5,padding:"4px 11px",fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:t.font,background:b===T?"var(--accent-dim)":"transparent",color:b===T?t.accent:t.textMuted},children:O},T);return s.jsxs("div",{style:{width:"min(640px, 100%)",display:"flex",flexDirection:"column",gap:14},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:2,padding:2,border:`1px solid ${t.headerBorder}`,borderRadius:7,background:t.cellBg},children:[I("all","All"),I("project","Project"),I("me","Just me")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{type:"button",onClick:()=>S?A():v(!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:l,onChange:T=>u(T.target.value),placeholder:"e.g. Fiscal quarters start in February. 'Sales' means recognized revenue unless someone says bookings.",style:{...Ne(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:T=>i(T.target.value),style:{...Ne(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:h,onChange:T=>d(T.target.value),placeholder:"Tags (optional)",style:{...Ne(t),width:160,borderRadius:7,padding:"5px 8px"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{type:"button",onClick:A,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 g(),disabled:!l.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:l.trim()?1:.6},children:j?"Update memory":"Save memory"})]})]}):null,s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:E.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."}):E.slice(0,30).map(T=>{const O=!["settings-ui","manual",""].includes(T.source),_=x(T.scope),M=O?`Saved from ${T.source}${typeof T.confidence=="number"?` · ${Math.round(T.confidence*100)}% confidence`:""}`:`Added by hand${T.tags.length?` · ${T.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:_.bg,color:_.color},children:_.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:T.content||T.title}),s.jsx("div",{style:{fontSize:10.5,color:t.textMuted,marginTop:4},children:M})]}),s.jsx("button",{type:"button",title:"Edit",onClick:()=>P(T),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 m(T.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:"🗑"})]},T.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 xl({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(Ik,{present:n.present})]},n.key))]})}function or({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 Pk({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 Ik({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 Ne(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 Ft(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 vl(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 Dk(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 qr(e){return{display:"flex",alignItems:"center",gap:5,fontSize:12,color:e.textSecondary}}function Ur(e){const t=e.filter(r=>r.kind!=="connector").map(r=>Sl({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:Hn(r).providers})),n=e.filter(r=>r.kind==="connector").map(r=>Sl({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 $k(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON: ${r instanceof Error?r.message:String(r)}`)}if(!Vn(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)=>ms(r,"server",`servers[${o}]`))),Array.isArray(t.connectors)&&n.push(...t.connectors.map((r,o)=>ms(r,"connector",`connectors[${o}]`))),Array.isArray(t.tools)&&n.push(...Mk(t.tools)),Array.isArray(t.mcp_servers)&&n.push(...Lk(t.mcp_servers)),Vn(t.mcpServers)&&n.push(...Nk(t.mcpServers)),n.map(Hn)}function Mk(e){return e.flatMap((t,n)=>{if(!Vn(t)||t.type!=="mcp")return[];const r=ct(t,["connectorId","connector_id"]),o=ct(t,["authorization"]);return r?[Hn({kind:"connector",name:ct(t,["name","server_label","serverLabel"])??r,connectorId:r,authorizationToken:o,allowedTools:fo(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]})]:[ms({...t,name:ct(t,["name","server_label","serverLabel"]),url:ct(t,["url","server_url","serverUrl"]),authorizationToken:o??La(t.headers),allowedTools:fo(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]},"server",`tools[${n}]`)]})}function Lk(e){return e.map((t,n)=>{const r=ms(t,"server",`mcp_servers[${n}]`);return Hn({...r,authorizationToken:r.authorizationToken??(Vn(t)?ct(t,["authorization_token"]):void 0),providers:["anthropic"]})})}function Nk(e){return Object.entries(e).map(([t,n])=>{if(!Vn(n))throw new Error(`mcpServers.${t} must be an object.`);const r=ct(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 Hn({kind:"server",name:t,url:r,authorizationToken:La(n.headers),enabled:n.enabled!==!1,trusted:n.trusted===!0,allowedTools:fo(n,["allowedTools","allowed_tools"]),providers:Gp(n,["providers"])??["openai","anthropic"]})})}function ms(e,t,n){if(!Vn(e))throw new Error(`${n} must be an object.`);const r=ct(e,["name","server_label","serverLabel"]);if(!r)throw new Error(`${n} needs a name.`);const o=ct(e,["url","server_url","serverUrl"]),i=ct(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:ct(e,["description","server_description","serverDescription"]),authorizationToken:ct(e,["authorizationToken","authorization","authorization_token"])??La(e.headers),authorizationTokenEnv:ct(e,["authorizationTokenEnv","authorizationEnv","authorization_token_env"]),allowedTools:fo(e,["allowedTools","allowed_tools"]),enabled:e.enabled!==!1,trusted:e.trusted===!0,deferLoading:e.deferLoading===!0||e.defer_loading===!0,providers:Gp(e,["providers"])}}function Sl(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>!(t==null||t===""||Array.isArray(t)&&t.length===0)))}function Vn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ct(e,t){for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function fo(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 Gp(e,t){const n=fo(e,t);if(!n)return;const r=n.filter(o=>o==="openai"||o==="anthropic");return r.length?r:void 0}function La(e){if(!Vn(e))return;const t=ct(e,["Authorization","authorization"]);return(t==null?void 0:t.replace(/^Bearer\s+/i,"").trim())||void 0}function wl(e,t,n){const r=new Set(e??[]);return n?r.add(t):r.delete(t),Array.from(r)}function Hn(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 ri(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 Bk=e=>new Promise(t=>{window.setTimeout(t,e)});async function Fk({jobId:e,loadStatus:t,onCompleted:n,onFailed:r,isCancelled:o=()=>!1,wait:i=Bk,intervalMs:a=700}){for(;!o();){if(await i(a),o())return;const c=await t();if(o())return;const l=c.job;if(!l||l.id!==e)return;if(!(l.state==="queued"||l.state==="running")){l.state==="completed"?await n(c):l.state==="failed"&&await r(c);return}}}function zk(e){return/^(?:https?:\/\/|ssh:\/\/|git@|file:\/\/)/i.test(e.trim())}function qk(e){const t=e.trim();return t?zk(t)?{repoUrl:t}:{projectDir:t}:{}}const oi={auto:"Auto",native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function Uk({compact:e=!1,reapplyRequired:t=!1,onConfigured:n}){var en,tn,Tn,An;const{state:r,dispatch:o}=et(),i=Qe[r.themeMode],[a,c]=p.useState(null),[l,u]=p.useState(!1),[h,d]=p.useState(""),[f,m]=p.useState(null),[S,v]=p.useState(null),[b,w]=p.useState("loading"),[j,C]=p.useState(null),[x,E]=p.useState(null),[P,A]=p.useState(""),[g,I]=p.useState(""),[T,O]=p.useState(""),[_,M]=p.useState(null),[q,G]=p.useState(null),[J,H]=p.useState(null),[L,$]=p.useState(""),[X,W]=p.useState(!1),te=p.useCallback(async()=>{const U=await B.getSemanticRuntimeSettings();return E(U),A(U.dbtCloud.host??""),I(U.dbtCloud.environmentId??""),O(""),U},[]),F=p.useCallback(async()=>{const U=await B.getMetricFlowInstallerStatus();return H(U),$(se=>se||U.recommendedAdapter||U.supportedAdapters[0]||""),U},[]),K=p.useCallback(async()=>{var me,nn,ie;const[U,se]=await Promise.all([B.getOnboardingStatus(),B.getBlockStudioDbtStatus().catch(()=>null)]);c(U),v(U.preparation??null);const je=((me=U.dbt)==null?void 0:me.configured)===!0||!!(se!=null&&se.configured&&se.artifacts.manifest.exists);u(je);const ve=((nn=U.dbt)==null?void 0:nn.repoUrl)||((ie=U.dbt)==null?void 0:ie.projectDir)||(se==null?void 0:se.projectPath)||"";return d(je?ve:""),U},[]);p.useEffect(()=>{let U=!0;return K().catch(se=>U&&C({ok:!1,text:se instanceof Error?se.message:String(se)})).finally(()=>U&&w(null)),()=>{U=!1}},[K]),p.useEffect(()=>{let U=!0;return Promise.all([te(),F()]).catch(se=>{U&&G({ok:!1,text:se instanceof Error?se.message:String(se)})}),()=>{U=!1}},[F,te]),p.useEffect(()=>{const U=J==null?void 0:J.job;if(!U||U.state!=="queued"&&U.state!=="running")return;let se=!1;return Fk({jobId:U.id,loadStatus:F,isCancelled:()=>se,onCompleted:async je=>{var me;await te();const ve=await B.getSemanticLayer();se||(o({type:"SET_SEMANTIC_LAYER",layer:ve}),G({ok:!0,text:((me=je.job)==null?void 0:me.message)||"Local MetricFlow is installed and ready."}))},onFailed:je=>{var ve,me;se||G({ok:!1,text:((ve=je.job)==null?void 0:ve.error)||((me=je.job)==null?void 0:me.message)||"Local MetricFlow installation failed."})}}).catch(je=>{se||G({ok:!1,text:je instanceof Error?je.message:String(je)})}),()=>{se=!0}},[o,F,te,(en=J==null?void 0:J.job)==null?void 0:en.id]),p.useEffect(()=>{if(!S||S.status!=="queued"&&S.status!=="running")return;let U=!0,se;const je=async()=>{try{const ve=await B.getOnboardingJob(S.id);if(!U)return;const me=ri(ve);if(!me)return;v(me),me.status==="completed"?(await K(),U&&C({ok:!0,text:me.message||"dbt metadata and governed search indexes are ready."})):me.status==="failed"||me.status==="cancelled"?C({ok:!1,text:me.error||me.message||`dbt preparation ${me.status}.`}):se=window.setTimeout(()=>void je(),650)}catch(ve){U&&C({ok:!1,text:ve instanceof Error?ve.message:String(ve)})}};return se=window.setTimeout(()=>void je(),350),()=>{U=!1,se!==void 0&&window.clearTimeout(se)}},[K,S==null?void 0:S.id,S==null?void 0:S.status]);const oe=async()=>{w("preview"),C(null);try{const U=await B.previewDbtOnboarding(qk(h));m(U),C({ok:!0,text:`Preview ready: ${U.counts.models??0} models, ${U.counts.sources??0} sources, ${U.counts.metrics??0} metrics. Nothing has changed yet.`})}catch(U){m(null),C({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}},ee=async()=>{if(f){w("apply"),C(null);try{const U=await B.applyDbtOnboarding({...f.repoUrl?{repoUrl:f.repoUrl,branch:f.branch,subPath:f.subPath}:{projectDir:f.projectDir},manifestPath:f.manifestPath,profilesDir:f.profilesDir,expectedFingerprint:f.fingerprint}),se=ri(U);se&&v(se);const je=await K();await F();const ve=je.preparation??se,me=`${f.counts.models??0} models · ${f.counts.sources??0} sources · ${f.counts.metrics??0} metrics`;C({ok:!0,text:(ve==null?void 0:ve.status)==="completed"?ve.message||`Connected ${f.projectName||f.projectDir}. Governed search is ready.`:ve?`Connected ${f.projectName||f.projectDir}. DQL is preparing ${me} for fast governed search in the background.`:`Applied ${f.projectName||f.projectDir}. ${me}.`}),n==null||n({name:f.projectName||"dbt project",path:f.projectDir,summary:me,readiness:(ve==null?void 0:ve.status)==="completed"?"ready":"preparing",readinessDetail:ve==null?void 0:ve.message}),m(null)}catch(U){C({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}}},ce=async()=>{w("refresh"),C(null);try{const U=await B.previewDbtOnboarding({}),se=await B.refreshDbtOnboarding({expectedFingerprint:U.fingerprint}),je=ri(se);je&&v(je);const me=(await K()).preparation??je;C({ok:!0,text:(me==null?void 0:me.status)==="completed"?me.message||"dbt artifacts and governed search indexes are ready.":me?"dbt artifacts refreshed. Governed search indexes are updating in the background.":"dbt artifacts refreshed from the configured project."})}catch(U){C({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}},ke=()=>({preference:(x==null?void 0:x.preference)??"auto",dbtCloud:{host:P,environmentId:g,serviceToken:T}}),xe=async U=>{M("apply"),G(null);try{const se=await B.setSemanticRuntimePreference(U);E(se),G({ok:!0,text:`Preferred runtime set to ${oi[U]??U}.`})}catch(se){G({ok:!1,text:se instanceof Error?se.message:String(se)})}finally{M(null)}},De=async()=>{M("test"),G(null);try{const U=await B.testDbtCloudSemanticRuntime(ke());G({ok:U.ok,text:U.message||U.error||"dbt Cloud Semantic Layer test failed."})}finally{M(null)}},We=async()=>{M("apply"),G(null);try{const U=await B.applyDbtCloudSemanticRuntime(ke());E(U),O(""),G({ok:!0,text:`${U.dbtCloud.testMessage||"dbt Cloud Semantic Layer tested."} Compilation is now bound to the active warehouse target.`})}catch(U){G({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{M(null)}},Be=async()=>{if(!L){G({ok:!1,text:"Choose the warehouse adapter used by this dbt project."});return}W(!0),G(null);try{const U=await B.installMetricFlow(L);H(se=>se?{...se,job:U.job}:{job:U.job,recommendedAdapter:L,supportedAdapters:[L],projectConfigured:!0,semanticManifestFound:!1})}catch(U){G({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{W(!1)}},Ee=l,ge=(J==null?void 0:J.job)??null,Je=X||(ge==null?void 0:ge.state)==="queued"||(ge==null?void 0:ge.state)==="running",tt=(ge==null?void 0:ge.state)==="failed",Fe=(S==null?void 0:S.status)==="queued"||(S==null?void 0:S.status)==="running",Ke=(S==null?void 0:S.status)==="failed"||(S==null?void 0:S.status)==="cancelled",bt=t?"Reapply required after DQL update":Ke?"dbt project needs attention":Fe?"Preparing governed search":Ee?"dbt project ready":"dbt project missing",Mt=t?"Review the prefilled project, choose Preview, then Reapply project.":(S==null?void 0:S.message)??(Ee?((tn=a==null?void 0:a.dbt)==null?void 0:tn.repoUrl)||((Tn=a==null?void 0:a.dbt)==null?void 0:Tn.projectDir)||"Configured dbt project.":"Choose a local path or Git repository."),jt={width:"100%",boxSizing:"border-box",height:36,borderRadius:8,border:`1px solid ${i.inputBorder}`,background:i.inputBg,color:i.textPrimary,padding:"0 11px",fontFamily:i.fontMono,fontSize:12,outline:"none"},Et={height:32,padding:"0 13px",borderRadius:8,border:`1px solid ${i.headerBorder}`,background:i.cellBg,color:i.textSecondary,fontFamily:i.font,fontSize:12,fontWeight:650,cursor:b?"wait":"pointer",opacity:b?.7:1};return s.jsxs("div",{style:{width:"min(680px, 100%)",display:"flex",flexDirection:"column",gap:14},children:[e?null:s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:17,fontWeight:700,color:i.textPrimary},children:"Project & dbt"}),s.jsx("div",{style:{fontSize:12.5,color:i.textMuted,marginTop:3,lineHeight:1.5},children:"Preview a local project or Git repository before DQL replaces the active dbt configuration."})]}),s.jsxs("div",{style:{border:`1px solid ${t?"var(--status-warning-border)":Ke?"var(--status-error-border)":Fe?"var(--status-info-border)":Ee?"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)":Ke?"var(--status-error)":Fe?"var(--status-info)":Ee?"var(--status-success)":"var(--status-warning)",background:t?"var(--status-warning-bg)":Ke?"var(--status-error-bg)":Fe?"var(--status-info-bg)":Ee?"var(--status-success-bg)":"var(--status-warning-bg)"},children:t?s.jsx(ps,{size:17}):Ke?s.jsx(Ev,{size:17}):Fe?s.jsx(Un,{className:"dql-dbt-preparing-icon",size:17}):Ee?s.jsx(hp,{size:17}):s.jsx(Nr,{size:17})}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:i.textPrimary},children:bt}),s.jsx("div",{style:{fontSize:11.5,color:Ke?"var(--status-error)":i.textMuted,marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Mt}),Fe?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]}),Ee&&!t?s.jsxs("button",{type:"button",onClick:()=>void ce(),disabled:!!b,style:Et,children:[s.jsx(ps,{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:h,onChange:U=>{d(U.target.value),m(null)},placeholder:". or https://github.com/org/analytics.git",style:jt})]}),f?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:f.projectName||f.projectDir}),s.jsx("br",{}),f.counts.models??0," models · ",f.counts.sources??0," sources · ",f.counts.metrics??0," metrics",s.jsx("br",{}),s.jsx("span",{style:{fontFamily:i.fontMono},children:f.manifestPath})]}):null,j?s.jsx("div",{role:j.ok?"status":"alert",style:{fontSize:11.5,lineHeight:1.5,color:j.ok?"var(--status-success)":"var(--status-error)"},children:j.text}):null,s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void oe(),disabled:!!b,style:Et,children:b==="preview"?"Inspecting…":"Preview"}),f?s.jsx("button",{type:"button",onClick:()=>void ee(),disabled:!!b,style:{...Et,border:"none",background:i.accent,color:"#fff"},children:b==="apply"?"Applying…":t?"Reapply project":"Apply project"}):null]})]}),s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:i.cellBg,padding:16,display:"grid",gap:12},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:i.textPrimary},children:"Semantic execution adapters"}),s.jsx("div",{style:{fontSize:11.5,color:i.textMuted,marginTop:3,lineHeight:1.5},children:"Adapter code is included with DQL. Auto selects one ready adapter in priority order: dbt Cloud, local MetricFlow, then native for simple metrics. Once selected, an adapter failure is shown directly and never silently downgraded."}),x!=null&&x.dbtCloud.configured?s.jsxs("div",{style:{fontSize:10.5,color:x.dbtCloud.targetBindingState==="bound"&&x.dbtCloud.metricInventoryState==="complete"?"var(--status-success)":"var(--status-warning)",marginTop:6,lineHeight:1.5},children:["dbt Cloud target: ",x.dbtCloud.targetBindingState==="bound"?`bound · ${(An=x.dbtCloud.executionTargetFingerprint)==null?void 0:An.slice(0,12)}`:"reapply required before execution",s.jsx("br",{}),"Metric inventory: ",x.dbtCloud.metricInventoryState,x.dbtCloud.semanticCatalogFingerprint?` · ${x.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:(x==null?void 0:x.preference)??"auto",onChange:U=>{xe(U.target.value)},disabled:_==="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)"})]}),x!=null&&x.runtime.active?s.jsxs("span",{style:{fontSize:10.5,color:i.textMuted},children:["Active: ",s.jsx("strong",{style:{color:i.textSecondary},children:oi[x.runtime.active]??x.runtime.active}),x.preference&&x.preference!=="auto"&&x.preference!==x.runtime.active?` (preferred ${oi[x.preference]??x.preference} is not ready)`:""]}):null]})]}),s.jsx("div",{style:{display:"grid",gap:7},children:((x==null?void 0:x.runtime.adapters)??[]).map(U=>s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:9,padding:"9px 10px",display:"grid",gap:U.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:U.ready?"var(--status-success)":U.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:U.label}),(x==null?void 0:x.runtime.active)===U.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:U.detail})]}),s.jsx("span",{style:{fontSize:9.5,color:U.ready?"var(--status-success)":i.textMuted},children:U.ready?"Ready":U.configured?"Configured":"Setup required"})]}),U.id==="metricflow-cli"&&(!U.ready||ge)?s.jsxs("div",{style:{marginLeft:17,paddingTop:9,borderTop:"1px solid var(--border-subtle)",display:"grid",gap:8},children:[U.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:L,onChange:se=>$(se.target.value),disabled:Je,style:{...jt,width:160,height:32,fontFamily:i.font},children:((J==null?void 0:J.supportedAdapters)??[]).map(se=>s.jsx("option",{value:se,children:se==="postgres"?"PostgreSQL":se.charAt(0).toUpperCase()+se.slice(1)},se))}),s.jsxs("button",{type:"button",onClick:()=>void Be(),disabled:!Ee||Je||!L,style:{...Et,border:"none",background:i.accent,color:"#fff",opacity:!Ee||Je||!L?.55:1,cursor:!Ee||Je?"not-allowed":"pointer"},children:[Je?s.jsx(Un,{className:"dql-dbt-preparing-icon",size:12,style:{verticalAlign:-2,marginRight:6}}):s.jsx(mp,{size:12,style:{verticalAlign:-2,marginRight:6}}),Je?"Installing…":"Install local MetricFlow"]})]}),Ee?null:s.jsx("div",{style:{fontSize:9.5,color:i.textMuted},children:"Connect the dbt project first, then install its matching runtime."})]}),ge?s.jsxs("div",{style:{display:"grid",gap:6},children:[s.jsx("div",{role:tt?"alert":"status",style:{fontSize:10.5,color:tt?"var(--status-error)":ge.state==="completed"?"var(--status-success)":i.textSecondary,lineHeight:1.45},children:ge.message}),ge.state==="queued"||ge.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,ge.progress)}%`,background:i.accent,transition:"width 180ms ease"}})}):null,ge.error||ge.logs.length>0?s.jsxs("details",{children:[s.jsx("summary",{style:{cursor:"pointer",fontSize:9.5,color:i.textMuted},children:tt?"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:tt?"var(--status-error)":i.textMuted},children:[...ge.logs.slice(-30),...ge.error?[ge.error]:[]].join(`
439
+ `),onChange:L=>m({...f,lesson:{...rt(f),avoid:L.target.value.split(/\r?\n/)}}),onBlur:()=>m({...f,lesson:{...rt(f),avoid:xl(rt(f).avoid.join(`
440
+ `))}}),placeholder:"Known mistakes to avoid, one per line",rows:2,style:{...Re(e,{size:"sm"}),resize:"vertical"}}),s.jsx("input",{value:rt(f).expectedOutcome??"",onChange:L=>m({...f,lesson:{...rt(f),expectedOutcome:L.target.value||void 0}}),placeholder:"Expected outcome or result shape",style:Re(e,{size:"sm"})})]})]}),s.jsx("textarea",{value:f.correctedSql??"",onChange:L=>m({...f,correctedSql:L.target.value}),placeholder:"Read-only corrected SQL",rows:5,style:{...Re(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(([L,$])=>s.jsxs("label",{style:{display:"grid",gap:3,fontSize:10,color:e.textMuted},children:[$,s.jsx("input",{value:f.scope[L]??"",onChange:X=>m({...f,scope:kk(f.scope,L,X.target.value)}),placeholder:`Optional ${$}`,style:Re(e,{size:"sm"})})]},L))}),s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void w(),style:Re(e,{variant:"primary",size:"sm",disabled:a===g.id}),children:"Save & recheck"}),s.jsx("button",{type:"button",onClick:()=>m(null),style:Re(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:g.guidance}),g.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:"})," ",g.lesson.category.replace(/_/g," ")]}),g.lesson.intentExamples.length?s.jsxs("div",{children:[s.jsx("b",{children:"Similar questions:"})," ",g.lesson.intentExamples.join(" · ")]}):null,g.lesson.avoid.length?s.jsxs("div",{children:[s.jsx("b",{children:"Avoid:"})," ",g.lesson.avoid.join(" · ")]}):null,g.lesson.expectedOutcome?s.jsxs("div",{children:[s.jsx("b",{children:"Expected:"})," ",g.lesson.expectedOutcome]}):null]}):null,g.correctedSql?s.jsx("pre",{style:{margin:0,fontSize:10.5,fontFamily:e.fontMono,color:e.textMuted,whiteSpace:"pre-wrap",maxHeight:120,overflow:"auto"},children:g.correctedSql}):null,P(g),s.jsx("textarea",{value:h[g.id]??"",onChange:L=>d({...h,[g.id]:L.target.value}),placeholder:"Reviewer note or result assertion (required evidence when this surface cannot execute)",rows:2,style:{...Re(e,{size:"sm"}),resize:"vertical"}}),s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[g.status==="candidate"?s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void v(g,"approved"),style:Re(e,{variant:"primary",size:"sm",disabled:a===g.id}),children:a===g.id?"Checking…":Sk(g)}),s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>m({...g,lesson:rt(g)}),style:Re(e,{size:"sm",disabled:a===g.id}),children:"Edit candidate"}),s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void v(g,"rejected"),style:Re(e,{variant:"danger",size:"sm",disabled:a===g.id}),children:"Reject"})]}):null,g.status==="approved"?s.jsxs(s.Fragment,{children:[O?s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void j(g),style:Re(e,{variant:"primary",size:"sm",disabled:a===g.id}),children:"Request certification"}):null,s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void b(g,"reopen"),style:Re(e,{size:"sm",disabled:a===g.id}),children:"Reopen & edit"}),s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void b(g,"retire"),style:Re(e,{variant:"danger",size:"sm",disabled:a===g.id}),children:"Retire"}),I.map(L=>s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void b(g,"supersede",L.relatedHintId),style:Re(e,{size:"sm",disabled:a===g.id}),children:"Keep this; supersede conflict"},L.relatedHintId))]}):null,g.status==="retired"?s.jsx("button",{type:"button",disabled:a===g.id,onClick:()=>void b(g,"reopen"),style:Re(e,{size:"sm",disabled:a===g.id}),children:"Reopen as candidate"}):null,s.jsx("span",{style:{fontSize:10.5,color:e.textMuted},children:[g.scope.dbtModel,g.scope.metric,g.scope.domain].filter(Boolean).join(" · ")||"project-wide"})]})]})]},g.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`:""]})]}),C.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:C.map(A)}),x.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:x.map(A)})]}):null,E.length>0?s.jsxs("details",{style:{marginTop:16},children:[s.jsxs("summary",{style:{cursor:"pointer",fontSize:12,color:e.textSecondary},children:["Rejected & retired history (",E.length,")"]}),s.jsx("div",{style:{display:"grid",gap:8,marginTop:8},children:E.map(A)})]}):null]})}function Pk({memories:e,t,onChange:n,onStatus:r}){const[o,i]=p.useState("project"),[a,c]=p.useState(""),[l,u]=p.useState(""),[h,d]=p.useState(""),f=async()=>{const T=await B.listAgentMemory();n(T.memories)},m=async T=>{await B.deleteAgentMemory(T),await f(),r("Memory deleted.")},[S,v]=p.useState(!1),[b,w]=p.useState("all"),[j,C]=p.useState(null),x=T=>T==="project"?{label:"project",bg:"var(--accent-dim)",color:t.accent}:T==="user"?{label:"just me",bg:`${t.textMuted}1f`,color:t.textMuted}:{label:T,bg:"var(--status-success-bg)",color:"var(--status-success)"},E=e.filter(T=>b==="all"?!0:b==="project"?T.scope==="project":T.scope==="user"),P=T=>{C(T.id),i(T.scope),c(T.title),u(T.content),d(T.tags.join(", ")),v(!0)},A=()=>{v(!1),C(null),c(""),u(""),d("")},g=async()=>{if(!l.trim())return;a.trim()||c(l.trim().slice(0,60));const T=a.trim()||l.trim().slice(0,60);await B.saveAgentMemory({scope:o,title:T,content:l,tags:h.split(",").map(O=>O.trim()).filter(Boolean),source:"settings-ui",confidence:.8,importance:o==="project"?.7:.5,enabled:!0}),j&&await B.deleteAgentMemory(j).catch(()=>{}),A(),await f(),r(j?"Memory updated.":"Memory saved.")},I=(T,O)=>s.jsx("button",{type:"button",onClick:()=>w(T),style:{border:"none",borderRadius:5,padding:"4px 11px",fontSize:11.5,fontWeight:600,cursor:"pointer",fontFamily:t.font,background:b===T?"var(--accent-dim)":"transparent",color:b===T?t.accent:t.textMuted},children:O},T);return s.jsxs("div",{style:{width:"min(640px, 100%)",display:"flex",flexDirection:"column",gap:14},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:2,padding:2,border:`1px solid ${t.headerBorder}`,borderRadius:7,background:t.cellBg},children:[I("all","All"),I("project","Project"),I("me","Just me")]}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{type:"button",onClick:()=>S?A():v(!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:l,onChange:T=>u(T.target.value),placeholder:"e.g. Fiscal quarters start in February. 'Sales' means recognized revenue unless someone says bookings.",style:{...Ne(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:T=>i(T.target.value),style:{...Ne(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:h,onChange:T=>d(T.target.value),placeholder:"Tags (optional)",style:{...Ne(t),width:160,borderRadius:7,padding:"5px 8px"}}),s.jsx("div",{style:{flex:1}}),s.jsx("button",{type:"button",onClick:A,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 g(),disabled:!l.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:l.trim()?1:.6},children:j?"Update memory":"Save memory"})]})]}):null,s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:E.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."}):E.slice(0,30).map(T=>{const O=!["settings-ui","manual",""].includes(T.source),_=x(T.scope),M=O?`Saved from ${T.source}${typeof T.confidence=="number"?` · ${Math.round(T.confidence*100)}% confidence`:""}`:`Added by hand${T.tags.length?` · ${T.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:_.bg,color:_.color},children:_.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:T.content||T.title}),s.jsx("div",{style:{fontSize:10.5,color:t.textMuted,marginTop:4},children:M})]}),s.jsx("button",{type:"button",title:"Edit",onClick:()=>P(T),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 m(T.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:"🗑"})]},T.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 vl({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(Dk,{present:n.present})]},n.key))]})}function or({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 Ik({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 Dk({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 Ne(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 Ft(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 Sl(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 $k(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 qr(e){return{display:"flex",alignItems:"center",gap:5,fontSize:12,color:e.textSecondary}}function Ur(e){const t=e.filter(r=>r.kind!=="connector").map(r=>wl({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:Hn(r).providers})),n=e.filter(r=>r.kind==="connector").map(r=>wl({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 Mk(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON: ${r instanceof Error?r.message:String(r)}`)}if(!Vn(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)=>ms(r,"server",`servers[${o}]`))),Array.isArray(t.connectors)&&n.push(...t.connectors.map((r,o)=>ms(r,"connector",`connectors[${o}]`))),Array.isArray(t.tools)&&n.push(...Lk(t.tools)),Array.isArray(t.mcp_servers)&&n.push(...Nk(t.mcp_servers)),Vn(t.mcpServers)&&n.push(...Bk(t.mcpServers)),n.map(Hn)}function Lk(e){return e.flatMap((t,n)=>{if(!Vn(t)||t.type!=="mcp")return[];const r=ct(t,["connectorId","connector_id"]),o=ct(t,["authorization"]);return r?[Hn({kind:"connector",name:ct(t,["name","server_label","serverLabel"])??r,connectorId:r,authorizationToken:o,allowedTools:fo(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]})]:[ms({...t,name:ct(t,["name","server_label","serverLabel"]),url:ct(t,["url","server_url","serverUrl"]),authorizationToken:o??La(t.headers),allowedTools:fo(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]},"server",`tools[${n}]`)]})}function Nk(e){return e.map((t,n)=>{const r=ms(t,"server",`mcp_servers[${n}]`);return Hn({...r,authorizationToken:r.authorizationToken??(Vn(t)?ct(t,["authorization_token"]):void 0),providers:["anthropic"]})})}function Bk(e){return Object.entries(e).map(([t,n])=>{if(!Vn(n))throw new Error(`mcpServers.${t} must be an object.`);const r=ct(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 Hn({kind:"server",name:t,url:r,authorizationToken:La(n.headers),enabled:n.enabled!==!1,trusted:n.trusted===!0,allowedTools:fo(n,["allowedTools","allowed_tools"]),providers:Qp(n,["providers"])??["openai","anthropic"]})})}function ms(e,t,n){if(!Vn(e))throw new Error(`${n} must be an object.`);const r=ct(e,["name","server_label","serverLabel"]);if(!r)throw new Error(`${n} needs a name.`);const o=ct(e,["url","server_url","serverUrl"]),i=ct(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:ct(e,["description","server_description","serverDescription"]),authorizationToken:ct(e,["authorizationToken","authorization","authorization_token"])??La(e.headers),authorizationTokenEnv:ct(e,["authorizationTokenEnv","authorizationEnv","authorization_token_env"]),allowedTools:fo(e,["allowedTools","allowed_tools"]),enabled:e.enabled!==!1,trusted:e.trusted===!0,deferLoading:e.deferLoading===!0||e.defer_loading===!0,providers:Qp(e,["providers"])}}function wl(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>!(t==null||t===""||Array.isArray(t)&&t.length===0)))}function Vn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ct(e,t){for(const n of t){const r=e[n];if(typeof r=="string"&&r.trim())return r.trim()}}function fo(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 Qp(e,t){const n=fo(e,t);if(!n)return;const r=n.filter(o=>o==="openai"||o==="anthropic");return r.length?r:void 0}function La(e){if(!Vn(e))return;const t=ct(e,["Authorization","authorization"]);return(t==null?void 0:t.replace(/^Bearer\s+/i,"").trim())||void 0}function kl(e,t,n){const r=new Set(e??[]);return n?r.add(t):r.delete(t),Array.from(r)}function Hn(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 ri(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 Fk=e=>new Promise(t=>{window.setTimeout(t,e)});async function zk({jobId:e,loadStatus:t,onCompleted:n,onFailed:r,isCancelled:o=()=>!1,wait:i=Fk,intervalMs:a=700}){for(;!o();){if(await i(a),o())return;const c=await t();if(o())return;const l=c.job;if(!l||l.id!==e)return;if(!(l.state==="queued"||l.state==="running")){l.state==="completed"?await n(c):l.state==="failed"&&await r(c);return}}}function qk(e){return/^(?:https?:\/\/|ssh:\/\/|git@|file:\/\/)/i.test(e.trim())}function Uk(e){const t=e.trim();return t?qk(t)?{repoUrl:t}:{projectDir:t}:{}}const oi={auto:"Auto",native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function Wk({compact:e=!1,reapplyRequired:t=!1,onConfigured:n}){var en,tn,Tn,An;const{state:r,dispatch:o}=et(),i=Qe[r.themeMode],[a,c]=p.useState(null),[l,u]=p.useState(!1),[h,d]=p.useState(""),[f,m]=p.useState(null),[S,v]=p.useState(null),[b,w]=p.useState("loading"),[j,C]=p.useState(null),[x,E]=p.useState(null),[P,A]=p.useState(""),[g,I]=p.useState(""),[T,O]=p.useState(""),[_,M]=p.useState(null),[q,G]=p.useState(null),[J,H]=p.useState(null),[L,$]=p.useState(""),[X,W]=p.useState(!1),te=p.useCallback(async()=>{const U=await B.getSemanticRuntimeSettings();return E(U),A(U.dbtCloud.host??""),I(U.dbtCloud.environmentId??""),O(""),U},[]),F=p.useCallback(async()=>{const U=await B.getMetricFlowInstallerStatus();return H(U),$(se=>se||U.recommendedAdapter||U.supportedAdapters[0]||""),U},[]),K=p.useCallback(async()=>{var me,nn,ie;const[U,se]=await Promise.all([B.getOnboardingStatus(),B.getBlockStudioDbtStatus().catch(()=>null)]);c(U),v(U.preparation??null);const je=((me=U.dbt)==null?void 0:me.configured)===!0||!!(se!=null&&se.configured&&se.artifacts.manifest.exists);u(je);const ve=((nn=U.dbt)==null?void 0:nn.repoUrl)||((ie=U.dbt)==null?void 0:ie.projectDir)||(se==null?void 0:se.projectPath)||"";return d(je?ve:""),U},[]);p.useEffect(()=>{let U=!0;return K().catch(se=>U&&C({ok:!1,text:se instanceof Error?se.message:String(se)})).finally(()=>U&&w(null)),()=>{U=!1}},[K]),p.useEffect(()=>{let U=!0;return Promise.all([te(),F()]).catch(se=>{U&&G({ok:!1,text:se instanceof Error?se.message:String(se)})}),()=>{U=!1}},[F,te]),p.useEffect(()=>{const U=J==null?void 0:J.job;if(!U||U.state!=="queued"&&U.state!=="running")return;let se=!1;return zk({jobId:U.id,loadStatus:F,isCancelled:()=>se,onCompleted:async je=>{var me;await te();const ve=await B.getSemanticLayer();se||(o({type:"SET_SEMANTIC_LAYER",layer:ve}),G({ok:!0,text:((me=je.job)==null?void 0:me.message)||"Local MetricFlow is installed and ready."}))},onFailed:je=>{var ve,me;se||G({ok:!1,text:((ve=je.job)==null?void 0:ve.error)||((me=je.job)==null?void 0:me.message)||"Local MetricFlow installation failed."})}}).catch(je=>{se||G({ok:!1,text:je instanceof Error?je.message:String(je)})}),()=>{se=!0}},[o,F,te,(en=J==null?void 0:J.job)==null?void 0:en.id]),p.useEffect(()=>{if(!S||S.status!=="queued"&&S.status!=="running")return;let U=!0,se;const je=async()=>{try{const ve=await B.getOnboardingJob(S.id);if(!U)return;const me=ri(ve);if(!me)return;v(me),me.status==="completed"?(await K(),U&&C({ok:!0,text:me.message||"dbt metadata and governed search indexes are ready."})):me.status==="failed"||me.status==="cancelled"?C({ok:!1,text:me.error||me.message||`dbt preparation ${me.status}.`}):se=window.setTimeout(()=>void je(),650)}catch(ve){U&&C({ok:!1,text:ve instanceof Error?ve.message:String(ve)})}};return se=window.setTimeout(()=>void je(),350),()=>{U=!1,se!==void 0&&window.clearTimeout(se)}},[K,S==null?void 0:S.id,S==null?void 0:S.status]);const oe=async()=>{w("preview"),C(null);try{const U=await B.previewDbtOnboarding(Uk(h));m(U),C({ok:!0,text:`Preview ready: ${U.counts.models??0} models, ${U.counts.sources??0} sources, ${U.counts.metrics??0} metrics. Nothing has changed yet.`})}catch(U){m(null),C({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}},ee=async()=>{if(f){w("apply"),C(null);try{const U=await B.applyDbtOnboarding({...f.repoUrl?{repoUrl:f.repoUrl,branch:f.branch,subPath:f.subPath}:{projectDir:f.projectDir},manifestPath:f.manifestPath,profilesDir:f.profilesDir,expectedFingerprint:f.fingerprint}),se=ri(U);se&&v(se);const je=await K();await F();const ve=je.preparation??se,me=`${f.counts.models??0} models · ${f.counts.sources??0} sources · ${f.counts.metrics??0} metrics`;C({ok:!0,text:(ve==null?void 0:ve.status)==="completed"?ve.message||`Connected ${f.projectName||f.projectDir}. Governed search is ready.`:ve?`Connected ${f.projectName||f.projectDir}. DQL is preparing ${me} for fast governed search in the background.`:`Applied ${f.projectName||f.projectDir}. ${me}.`}),n==null||n({name:f.projectName||"dbt project",path:f.projectDir,summary:me,readiness:(ve==null?void 0:ve.status)==="completed"?"ready":"preparing",readinessDetail:ve==null?void 0:ve.message}),m(null)}catch(U){C({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}}},ce=async()=>{w("refresh"),C(null);try{const U=await B.previewDbtOnboarding({}),se=await B.refreshDbtOnboarding({expectedFingerprint:U.fingerprint}),je=ri(se);je&&v(je);const me=(await K()).preparation??je;C({ok:!0,text:(me==null?void 0:me.status)==="completed"?me.message||"dbt artifacts and governed search indexes are ready.":me?"dbt artifacts refreshed. Governed search indexes are updating in the background.":"dbt artifacts refreshed from the configured project."})}catch(U){C({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{w(null)}},ke=()=>({preference:(x==null?void 0:x.preference)??"auto",dbtCloud:{host:P,environmentId:g,serviceToken:T}}),xe=async U=>{M("apply"),G(null);try{const se=await B.setSemanticRuntimePreference(U);E(se),G({ok:!0,text:`Preferred runtime set to ${oi[U]??U}.`})}catch(se){G({ok:!1,text:se instanceof Error?se.message:String(se)})}finally{M(null)}},De=async()=>{M("test"),G(null);try{const U=await B.testDbtCloudSemanticRuntime(ke());G({ok:U.ok,text:U.message||U.error||"dbt Cloud Semantic Layer test failed."})}finally{M(null)}},We=async()=>{M("apply"),G(null);try{const U=await B.applyDbtCloudSemanticRuntime(ke());E(U),O(""),G({ok:!0,text:`${U.dbtCloud.testMessage||"dbt Cloud Semantic Layer tested."} Compilation is now bound to the active warehouse target.`})}catch(U){G({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{M(null)}},Be=async()=>{if(!L){G({ok:!1,text:"Choose the warehouse adapter used by this dbt project."});return}W(!0),G(null);try{const U=await B.installMetricFlow(L);H(se=>se?{...se,job:U.job}:{job:U.job,recommendedAdapter:L,supportedAdapters:[L],projectConfigured:!0,semanticManifestFound:!1})}catch(U){G({ok:!1,text:U instanceof Error?U.message:String(U)})}finally{W(!1)}},Ee=l,ge=(J==null?void 0:J.job)??null,Je=X||(ge==null?void 0:ge.state)==="queued"||(ge==null?void 0:ge.state)==="running",tt=(ge==null?void 0:ge.state)==="failed",Fe=(S==null?void 0:S.status)==="queued"||(S==null?void 0:S.status)==="running",Ke=(S==null?void 0:S.status)==="failed"||(S==null?void 0:S.status)==="cancelled",bt=t?"Reapply required after DQL update":Ke?"dbt project needs attention":Fe?"Preparing governed search":Ee?"dbt project ready":"dbt project missing",Mt=t?"Review the prefilled project, choose Preview, then Reapply project.":(S==null?void 0:S.message)??(Ee?((tn=a==null?void 0:a.dbt)==null?void 0:tn.repoUrl)||((Tn=a==null?void 0:a.dbt)==null?void 0:Tn.projectDir)||"Configured dbt project.":"Choose a local path or Git repository."),jt={width:"100%",boxSizing:"border-box",height:36,borderRadius:8,border:`1px solid ${i.inputBorder}`,background:i.inputBg,color:i.textPrimary,padding:"0 11px",fontFamily:i.fontMono,fontSize:12,outline:"none"},Et={height:32,padding:"0 13px",borderRadius:8,border:`1px solid ${i.headerBorder}`,background:i.cellBg,color:i.textSecondary,fontFamily:i.font,fontSize:12,fontWeight:650,cursor:b?"wait":"pointer",opacity:b?.7:1};return s.jsxs("div",{style:{width:"min(680px, 100%)",display:"flex",flexDirection:"column",gap:14},children:[e?null:s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:17,fontWeight:700,color:i.textPrimary},children:"Project & dbt"}),s.jsx("div",{style:{fontSize:12.5,color:i.textMuted,marginTop:3,lineHeight:1.5},children:"Preview a local project or Git repository before DQL replaces the active dbt configuration."})]}),s.jsxs("div",{style:{border:`1px solid ${t?"var(--status-warning-border)":Ke?"var(--status-error-border)":Fe?"var(--status-info-border)":Ee?"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)":Ke?"var(--status-error)":Fe?"var(--status-info)":Ee?"var(--status-success)":"var(--status-warning)",background:t?"var(--status-warning-bg)":Ke?"var(--status-error-bg)":Fe?"var(--status-info-bg)":Ee?"var(--status-success-bg)":"var(--status-warning-bg)"},children:t?s.jsx(ps,{size:17}):Ke?s.jsx(Tv,{size:17}):Fe?s.jsx(Un,{className:"dql-dbt-preparing-icon",size:17}):Ee?s.jsx(mp,{size:17}):s.jsx(Nr,{size:17})}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:i.textPrimary},children:bt}),s.jsx("div",{style:{fontSize:11.5,color:Ke?"var(--status-error)":i.textMuted,marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Mt}),Fe?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]}),Ee&&!t?s.jsxs("button",{type:"button",onClick:()=>void ce(),disabled:!!b,style:Et,children:[s.jsx(ps,{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:h,onChange:U=>{d(U.target.value),m(null)},placeholder:". or https://github.com/org/analytics.git",style:jt})]}),f?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:f.projectName||f.projectDir}),s.jsx("br",{}),f.counts.models??0," models · ",f.counts.sources??0," sources · ",f.counts.metrics??0," metrics",s.jsx("br",{}),s.jsx("span",{style:{fontFamily:i.fontMono},children:f.manifestPath})]}):null,j?s.jsx("div",{role:j.ok?"status":"alert",style:{fontSize:11.5,lineHeight:1.5,color:j.ok?"var(--status-success)":"var(--status-error)"},children:j.text}):null,s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void oe(),disabled:!!b,style:Et,children:b==="preview"?"Inspecting…":"Preview"}),f?s.jsx("button",{type:"button",onClick:()=>void ee(),disabled:!!b,style:{...Et,border:"none",background:i.accent,color:"#fff"},children:b==="apply"?"Applying…":t?"Reapply project":"Apply project"}):null]})]}),s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:i.cellBg,padding:16,display:"grid",gap:12},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:i.textPrimary},children:"Semantic execution adapters"}),s.jsx("div",{style:{fontSize:11.5,color:i.textMuted,marginTop:3,lineHeight:1.5},children:"Adapter code is included with DQL. Auto selects one ready adapter in priority order: dbt Cloud, local MetricFlow, then native for simple metrics. Once selected, an adapter failure is shown directly and never silently downgraded."}),x!=null&&x.dbtCloud.configured?s.jsxs("div",{style:{fontSize:10.5,color:x.dbtCloud.targetBindingState==="bound"&&x.dbtCloud.metricInventoryState==="complete"?"var(--status-success)":"var(--status-warning)",marginTop:6,lineHeight:1.5},children:["dbt Cloud target: ",x.dbtCloud.targetBindingState==="bound"?`bound · ${(An=x.dbtCloud.executionTargetFingerprint)==null?void 0:An.slice(0,12)}`:"reapply required before execution",s.jsx("br",{}),"Metric inventory: ",x.dbtCloud.metricInventoryState,x.dbtCloud.semanticCatalogFingerprint?` · ${x.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:(x==null?void 0:x.preference)??"auto",onChange:U=>{xe(U.target.value)},disabled:_==="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)"})]}),x!=null&&x.runtime.active?s.jsxs("span",{style:{fontSize:10.5,color:i.textMuted},children:["Active: ",s.jsx("strong",{style:{color:i.textSecondary},children:oi[x.runtime.active]??x.runtime.active}),x.preference&&x.preference!=="auto"&&x.preference!==x.runtime.active?` (preferred ${oi[x.preference]??x.preference} is not ready)`:""]}):null]})]}),s.jsx("div",{style:{display:"grid",gap:7},children:((x==null?void 0:x.runtime.adapters)??[]).map(U=>s.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:9,padding:"9px 10px",display:"grid",gap:U.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:U.ready?"var(--status-success)":U.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:U.label}),(x==null?void 0:x.runtime.active)===U.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:U.detail})]}),s.jsx("span",{style:{fontSize:9.5,color:U.ready?"var(--status-success)":i.textMuted},children:U.ready?"Ready":U.configured?"Configured":"Setup required"})]}),U.id==="metricflow-cli"&&(!U.ready||ge)?s.jsxs("div",{style:{marginLeft:17,paddingTop:9,borderTop:"1px solid var(--border-subtle)",display:"grid",gap:8},children:[U.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:L,onChange:se=>$(se.target.value),disabled:Je,style:{...jt,width:160,height:32,fontFamily:i.font},children:((J==null?void 0:J.supportedAdapters)??[]).map(se=>s.jsx("option",{value:se,children:se==="postgres"?"PostgreSQL":se.charAt(0).toUpperCase()+se.slice(1)},se))}),s.jsxs("button",{type:"button",onClick:()=>void Be(),disabled:!Ee||Je||!L,style:{...Et,border:"none",background:i.accent,color:"#fff",opacity:!Ee||Je||!L?.55:1,cursor:!Ee||Je?"not-allowed":"pointer"},children:[Je?s.jsx(Un,{className:"dql-dbt-preparing-icon",size:12,style:{verticalAlign:-2,marginRight:6}}):s.jsx(gp,{size:12,style:{verticalAlign:-2,marginRight:6}}),Je?"Installing…":"Install local MetricFlow"]})]}),Ee?null:s.jsx("div",{style:{fontSize:9.5,color:i.textMuted},children:"Connect the dbt project first, then install its matching runtime."})]}),ge?s.jsxs("div",{style:{display:"grid",gap:6},children:[s.jsx("div",{role:tt?"alert":"status",style:{fontSize:10.5,color:tt?"var(--status-error)":ge.state==="completed"?"var(--status-success)":i.textSecondary,lineHeight:1.45},children:ge.message}),ge.state==="queued"||ge.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,ge.progress)}%`,background:i.accent,transition:"width 180ms ease"}})}):null,ge.error||ge.logs.length>0?s.jsxs("details",{children:[s.jsx("summary",{style:{cursor:"pointer",fontSize:9.5,color:i.textMuted},children:tt?"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:tt?"var(--status-error)":i.textMuted},children:[...ge.logs.slice(-30),...ge.error?[ge.error]:[]].join(`
441
441
  `)})]}):null]}):null]}):null]},U.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:P,onChange:U=>A(U.target.value),placeholder:"semantic-layer.cloud.getdbt.com",style:jt})]}),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:g,onChange:U=>I(U.target.value),placeholder:"123456",style:jt})]}),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:T,onChange:U=>O(U.target.value),placeholder:(x==null?void 0:x.dbtCloud.serviceTokenPreview)||"Semantic Layer service token",autoComplete:"off",style:jt}),s.jsx("span",{style:{fontSize:9.5,color:i.textMuted},children:"Requires Semantic Layer and Metadata permissions. Leave blank to preserve the stored token."})]}),q?s.jsx("div",{role:q.ok?"status":"alert",style:{fontSize:11,color:q.ok?"var(--status-success)":"var(--status-error)"},children:q.text}):null,s.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void De(),disabled:!!_,style:Et,children:_==="test"?"Testing…":"Test draft"}),s.jsx("button",{type:"button",onClick:()=>void We(),disabled:!!_,style:{...Et,border:"none",background:i.accent,color:"#fff"},children:_==="apply"?"Testing & binding…":"Test, bind & save"})]})]})]})]})]})}function Qo(e){return e.map(t=>`${t.catalogOrDatabase}: ${t.schemas.join(", ")}`).join(`
442
- `)}function si(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(l=>l.trim()).filter(Boolean);if(!o||i.length===0)continue;const a=o.toLowerCase(),c=t.get(a)??{catalogOrDatabase:o,schemas:new Set};for(const l of i)c.schemas.add(l);t.set(a,c)}return Array.from(t.values()).map(n=>({catalogOrDatabase:n.catalogOrDatabase,schemas:Array.from(n.schemas)}))}function Wk(e,t,n){return e.some(r=>r.catalogOrDatabase.toLowerCase()===t.toLowerCase()&&r.schemas.some(o=>o.toLowerCase()===n.toLowerCase()))}function Kk(e,t,n,r){const o=new Map(e.map(c=>[c.catalogOrDatabase.toLowerCase(),{catalogOrDatabase:c.catalogOrDatabase,schemas:new Map(c.schemas.map(l=>[l.toLowerCase(),l]))}])),i=t.toLowerCase(),a=o.get(i)??{catalogOrDatabase:t,schemas:new Map};return r?a.schemas.set(n.toLowerCase(),n):a.schemas.delete(n.toLowerCase()),a.schemas.size>0?o.set(i,a):o.delete(i),Array.from(o.values()).map(c=>({catalogOrDatabase:c.catalogOrDatabase,schemas:Array.from(c.schemas.values())}))}function Vk(e){return e.scopes.reduce((t,n)=>t+n.schemas.filter(r=>!r.inDbtProject).length,0)}const ii={duckdb:"DuckDB",file:"Local File / DuckDB",snowflake:"Snowflake",databricks:"Databricks"},ns={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"},Hk={duckdb:"In-process analytical database",file:"Local CSV / Parquet via DuckDB",snowflake:"Cloud data platform",databricks:"Lakehouse platform"},$s=[{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"}]}],Na=Object.fromEntries($s.map(e=>[e.driver,e])),Gk=[{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 Xr(e){return e==="postgres"?"postgresql":e}function Ki(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 Qk(e){return`${e.profileName}_${e.targetName}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"dbt_profile"}function Jk(e){const t={};return Object.entries(e.connection??{}).forEach(([n,r])=>{n!=="driver"&&r!==void 0&&r!==null&&(t[Ki(n)]=String(r))}),t}function Yk(e){const n=e.indexOf("/.dbt/");return n>=0?`~${e.slice(n)}`:e.split("/").slice(-3).join("/")}function Xk(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 kl(e,t){return e.startsWith("Error")||e.toLowerCase().includes("failed")?t.error:e.toLowerCase().includes("testing")?t.warning:t.success}function ho(e){const t=Xr(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 Zk(e,t,n,r){const o=r!==null&&r===t,i=!!(t&&e[t]),a=e[n];return r===null||o||!i||t==="default"&&ho(e.default)&&!ho(a)?n:t}function e1(e){const t=Object.keys(e);return t.find(n=>!ho(e[n]))??t[0]}function Qp({variant:e="panel",onConfigured:t}={}){var Ga,Qa,Ja,Ya,Xa;const n=Ge(Lr(D=>({settingsTab:D.settingsTab,themeMode:D.themeMode}))),r=jn(),o=Qe[n.themeMode],i=e==="page",a=e==="setup",[c,l]=p.useState(null),[u,h]=p.useState(!1),[d,f]=p.useState(null),[m,S]=p.useState(null),[v,b]=p.useState(!1),[w,j]=p.useState(!1),[C,x]=p.useState(null),[E,P]=p.useState(null),[A,g]=p.useState(""),[I,T]=p.useState(!1),[O,_]=p.useState(null),[M,q]=p.useState([]),[G,J]=p.useState(!1),[H,L]=p.useState(null),[$,X]=p.useState("dbt_relations"),[W,te]=p.useState(""),[F,K]=p.useState(!1),[oe,ee]=p.useState(null),[ce,ke]=p.useState(null),[xe,De]=p.useState(!1),[We,Be]=p.useState(""),[Ee,ge]=p.useState("duckdb"),[Je,tt]=p.useState({}),[Fe,Ke]=p.useState("duckdb"),[bt,Mt]=p.useState({}),jt=p.useRef(null);p.useEffect(()=>{B.getConnections().then(D=>{l(D),D.metadataScope&&(X(D.metadataScope.mode),te(Qo(D.metadataScope.selectedScopes??D.metadataScope.scopes)))})},[]);const Et=c?`${c.default}:${JSON.stringify(((Ga=c.connections)==null?void 0:Ga[c.default])??null)}`:"";p.useEffect(()=>{if(!c||i&&n.settingsTab!=="database"||!Object.values(c.connections).some(z=>!ho(z)))return;let D=!0;return h(!0),B.testConnection().then(z=>{D&&f(z)}).catch(z=>{D&&f({ok:!1,message:z instanceof Error?z.message:String(z)})}).finally(()=>{D&&h(!1)}),()=>{D=!1}},[Et,i,n.settingsTab]),p.useEffect(()=>{if(!i)return;let D=!0;return Promise.all([B.getProviderSettings(),B.getOnboardingStatus(),B.getBlockStudioDbtStatus().catch(()=>null)]).then(([z,ae,re])=>{var ue;D&&(q(z.providers),J(((ue=ae.dbt)==null?void 0:ue.configured)===!0||!!(re!=null&&re.configured&&re.artifacts.manifest.exists)),L(ae.preparation??null))}).catch(()=>{}),()=>{D=!1}},[i]),p.useEffect(()=>{if(!i||!H||H.status!=="queued"&&H.status!=="running")return;let D=!0,z;const ae=async()=>{var re,ue,we;try{const Ve=await B.getOnboardingStatus();if(!D)return;L(Ve.preparation??null),J(((re=Ve.dbt)==null?void 0:re.configured)===!0),(((ue=Ve.preparation)==null?void 0:ue.status)==="queued"||((we=Ve.preparation)==null?void 0:we.status)==="running")&&(z=window.setTimeout(()=>void ae(),700))}catch{}};return z=window.setTimeout(()=>void ae(),500),()=>{D=!1,z!==void 0&&window.clearTimeout(z)}},[H==null?void 0:H.id,H==null?void 0:H.status,i]),p.useEffect(()=>{var re;if(!c)return;const D=c.default,z=D?(re=c.connections)==null?void 0:re[D]:void 0,ae=z?`${D}::${JSON.stringify(z)}`:"::none";if(jt.current!==ae)if(jt.current=ae,z){Ke(Xr(String(z.driver??z.type??"duckdb")));const ue={};Object.entries(z).forEach(([we,Ve])=>{we!=="driver"&&we!=="type"&&(ue[Ki(we)]=String(Ve??""))}),Mt(ue)}else Ke("duckdb"),Mt({})},[c]);const en=async()=>{if(!c||Object.keys(c.connections??{}).length===0){f({ok:!1,message:"Add or import a connection before testing."});return}h(!0),f(null);const D=await B.testConnection();f(D),D.ok&&(t==null||t(D.message)),h(!1)},tn=D=>{l(z=>z&&{...z,metadataScope:D.scope,metadataStatus:D.status}),X(D.scope.mode),te(Qo(D.scope.selectedScopes??D.scope.scopes))},Tn=async()=>{if(!(!(c!=null&&c.default)||!(d!=null&&d.ok))){De(!0),ee("Finding databases/catalogs and schemas visible to this connection…");try{const D=await B.discoverConnectionMetadataScopes(c.default);ke(D),ee(D.message)}catch(D){ke(null),ee(D instanceof Error?D.message:String(D))}finally{De(!1)}}},An=(D,z,ae)=>{const re=Kk(si(W),D,z,ae);te(Qo(re)),X(((ce==null?void 0:ce.dbtScopes.length)??0)>0?"dbt_plus_selected":"selected_scopes")},U=async()=>{if(!(c!=null&&c.default))return;const D=si(W);if($==="selected_scopes"&&D.length===0){ee("Add at least one line such as ANALYTICS_PROD: SALES, FINANCE.");return}K(!0),ee("Synchronizing selected metadata into local SQLite…");try{const z=await B.applyConnectionMetadataScope(c.default,{mode:$,...$==="dbt_relations"?{}:{scopes:D}});tn(z),ee(`Ready · ${z.status.relationCount.toLocaleString()} relations · ${z.status.columnCount.toLocaleString()} columns · ${z.status.queryCount??0} metadata queries`)}catch(z){ee(z instanceof Error?z.message:String(z))}finally{K(!1)}},se=async()=>{if(c!=null&&c.default){K(!0),ee("Refreshing the applied metadata scope…");try{const D=await B.refreshConnectionMetadata(c.default);tn(D),ee(`Refreshed · ${D.status.relationCount.toLocaleString()} relations · ${D.status.columnCount.toLocaleString()} columns`)}catch(D){ee(D instanceof Error?D.message:String(D))}finally{K(!1)}}},je=(D,z)=>{S(D),b(!1),Be(D),ge(Xr((z==null?void 0:z.driver)??(z==null?void 0:z.type)??"duckdb"));const ae={};Object.entries(z??{}).forEach(([re,ue])=>{re!=="driver"&&re!=="type"&&(ae[Ki(re)]=String(ue??""))}),tt(ae)},ve=()=>{b(!0),S(null),Be(""),ge("duckdb"),tt({})},me=()=>{S(null),b(!1)},nn=async D=>{P(D),x(null);try{const z=await B.installConnector(D);if(z.connectorStatus&&c)l({...c,connectorStatus:z.connectorStatus});else{const ae=await B.getConnections();l(ae)}x(z.ok?"Connector installed":`Error: ${z.error??"Install failed"}`)}catch(z){x(`Error: ${(z==null?void 0:z.message)??"Install failed"}`)}finally{P(null)}},ie=async D=>{if(!c)return!1;j(!0),x(null);const z=D.name.trim()||(D.previousName??"default"),ae={driver:D.driver},re=Na[D.driver],ue=new Map(((re==null?void 0:re.fields)??[]).map(Ye=>[Ye.key,Ye]));Object.entries(D.fields).forEach(([Ye,nt])=>{const At=ue.get(Ye);if((At==null?void 0:At.type)==="checkbox"){nt!==""&&(ae[Ye]=nt==="true");return}const Do=nt.trim();Do&&((At==null?void 0:At.type)==="number"&&!isNaN(Number(Do))?ae[Ye]=Number(Do):ae[Ye]=Do)});const we={...c.connections},Ve=c.default,Zn={...c.connections};D.previousName&&D.previousName!==z&&delete Zn[D.previousName],Zn[z]=ae;const Af=Zk(Zn,c.default,z,D.previousName);let Za=!1;try{await B.saveConnections(Zn,Af);const Ye=await B.getConnections();l(Ye),Ye.metadataScope&&(X(Ye.metadataScope.mode),te(Qo(Ye.metadataScope.selectedScopes??Ye.metadataScope.scopes))),ke(null),x("Saved. Testing connection..."),S(null),b(!1);try{h(!0);const nt=await B.testConnection();if(f(nt),Za=nt.ok,nt.ok)x("Test passed. Connection saved and activated."),t==null||t(nt.message),setTimeout(()=>x(null),2e3);else{await B.saveConnections(we,Ve||void 0);const At=await B.getConnections();l(At),x(`Test failed. Previous connection preserved: ${nt.message}`)}}catch(nt){await B.saveConnections(we,Ve||void 0).catch(()=>{});const At=await B.getConnections().catch(()=>null);At&&l(At),x(`Test failed. Previous connection preserved: ${nt.message??"Connection failed"}`)}finally{h(!1)}}catch(Ye){await B.saveConnections(we,Ve||void 0).catch(()=>{});const nt=await B.getConnections().catch(()=>null);nt&&l(nt),x(`Test or save failed. Previous connection preserved: ${Ye.message}`)}finally{j(!1)}return Za},Y=D=>{const z=Xr(String(D.connection.driver??D.adapter??"duckdb")),ae=Jk(D);f(null),(i||a)&&(Ke(z),Mt(ae)),b(!1),S(null),ie({name:Qk(D),driver:z,fields:ae,previousName:null})},$e=async()=>{const D=A.trim();if(!D){_("Enter a profiles.yml file or folder path.");return}T(!0),_(null);try{const z=await B.previewDbtProfiles(D);l(ae=>{if(!ae)return ae;const re=new Map((ae.dbtProfiles??[]).map(ue=>[ue.id,ue]));return z.dbtProfiles.forEach(ue=>re.set(ue.id,ue)),{...ae,dbtProfiles:[...re.values()]}})}catch(z){_(z instanceof Error?z.message:"Could not read that profiles.yml path.")}finally{T(!1)}},Yn=()=>ie({name:We,driver:Ee,fields:Je,previousName:m}),Xn=()=>ie({name:(c==null?void 0:c.default)||"default",driver:Fe,fields:bt,previousName:(c==null?void 0:c.default)||null}),Ro=D=>{Ke(D),Mt({}),f(null)},yf=async D=>{if(!c)return;const z={...c.connections};delete z[D];const ae=D===c.default?e1(z):c.default;j(!0);try{await B.saveConnections(z,ae);const re=await B.getConnections();l(re),S(null)}finally{j(!1)}},bf=async D=>{if(!c)return;const z=c.default;j(!0),x(null);try{await B.saveConnections(c.connections,D);const ae=await B.getConnections();l(ae),x("Default updated. Testing connection..."),h(!0);const re=await B.testConnection();if(f(re),re.ok)x("Test passed. Default connection updated."),t==null||t(re.message),setTimeout(()=>x(null),2e3);else{await B.saveConnections(c.connections,z||void 0);const ue=await B.getConnections();l(ue),x(`Test failed. Previous default preserved: ${re.message}`)}}catch(ae){await B.saveConnections(c.connections,z||void 0).catch(()=>{});const re=await B.getConnections().catch(()=>null);re&&l(re),x(`Test or save failed. Previous default preserved: ${ae.message}`)}finally{h(!1),j(!1)}},Oo={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:o.textMuted,fontFamily:o.font,marginBottom:6},_o={background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},Po=(c==null?void 0:c.connections)??{},xf=(c==null?void 0:c.default)??"",qa=(c==null?void 0:c.dbtProfiles)??[],Ua=Object.fromEntries(((c==null?void 0:c.connectorStatus)??[]).map(D=>[D.driver,D])),Wa=Object.keys(Po).length,Io=Wa>0,vf=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:Oo,children:"Connections"}),c===null?s.jsx("div",{style:{fontSize:12,color:o.textMuted,fontFamily:o.font},children:"Loading…"}):Object.entries(Po).map(([D,z])=>{const ae=(z==null?void 0:z.driver)??(z==null?void 0:z.type)??"unknown",re=D===xf,ue=ns[ae]??o.accent;return m===D?s.jsx(Cl,{t:o,editName:We,setEditName:Be,editDriver:Ee,setEditDriver:ge,editFields:Je,setEditFields:tt,onSave:Yn,onCancel:me,onDelete:()=>yf(D),saving:w,isNew:!1},D):s.jsxs("div",{style:{..._o,borderLeft:re?`3px solid ${ue}`:`1px solid ${o.cellBorder}`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[s.jsx(Yr,{driver:ae,size:18,fallbackColor:ue}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:ii[ae]??ae}),s.jsx("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted},children:D}),re&&(d==null?void 0:d.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`}}),re&&d&&!d.ok&&s.jsx("span",{title:d.message,"aria-label":"Disconnected",style:{width:7,height:7,borderRadius:"50%",background:o.error,flexShrink:0,boxShadow:`0 0 0 2px ${o.error}25`}}),re&&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}}),!re&&s.jsx("button",{onClick:()=>bf(D),disabled:w,style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:3,cursor:w?"not-allowed":"pointer",color:o.textMuted,fontSize:10,fontFamily:o.font,padding:"1px 6px",transition:"all 0.15s"},children:"Use"}),s.jsx("button",{onClick:()=>je(D,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(([we])=>we!=="driver"&&we!=="type").map(([we,Ve])=>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:we}),s.jsx("span",{style:{fontSize:11,color:o.textSecondary,fontFamily:o.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Xk(we)?"••••••••":String(Ve)})]},we))})]},D)}),c!==null&&Wa===0&&s.jsx("div",{style:{..._o,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."})]}),Ka=s.jsxs("div",{style:{..._o,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:A,onChange:D=>g(D.target.value),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),$e())},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 $e(),disabled:I,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:I?"wait":"pointer"},children:I?"Reading…":"Find profiles"})]}),O?s.jsx("div",{role:"alert",style:{marginTop:6,color:o.error,fontSize:10.5,fontFamily:o.font},children:O}):null]}),Va=s.jsx(s.Fragment,{children:!v&&!m&&qa.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Oo,marginTop:8},children:"dbt profiles"}),s.jsx("div",{style:{display:"grid",gap:8,marginBottom:12},children:qa.map(D=>{var we;const z=Xr(String(D.connection.driver??D.adapter)),ae=ns[z]??o.accent,re=D.missingFields.length===0,ue=((we=c==null?void 0:c.activeConnection)==null?void 0:we.source)==="dbt_profile"&&c.activeConnection.profileId===D.id;return s.jsxs("div",{style:{..._o,marginBottom:0,display:"flex",alignItems:"center",gap:10},children:[s.jsx(Yr,{driver:z,size:18,fallbackColor:ae}),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:D.profileName}),s.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.fontMono},children:D.targetName})]}),s.jsxs("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[ii[z]??D.adapter," from ",Yk(D.path)]}),s.jsx("div",{style:{fontSize:10,color:re?o.success:o.warning,fontFamily:o.font,marginTop:2},children:re?ue?"Active runtime connection · import to save":"Ready to import and test":`Imports now · needs ${D.missingFields.join(", ")}`})]}),s.jsx("button",{onClick:()=>Y(D),disabled:w,title:D.warnings.join(" ")||void 0,style:{background:o.btnBg,border:`1px solid ${o.btnBorder}`,borderRadius:4,cursor:w?"wait":"pointer",color:o.textSecondary,fontSize:11,fontFamily:o.font,padding:"4px 8px",flexShrink:0},children:"Import & test"})]},D.id)})})]})}),Sf=s.jsx(s.Fragment,{children:!v&&!m&&Object.keys(Po).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Oo,marginTop:8},children:"Quick Connect"}),s.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:Gk.map(D=>s.jsxs("button",{onClick:async()=>{j(!0);try{const z={...Po,[D.name]:D.config};await B.saveConnections(z,D.name);const ae=await B.getConnections();l(ae),h(!0);const re=await B.testConnection();f(re),h(!1)}finally{j(!1)}},disabled:w,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:7,cursor:w?"not-allowed":"pointer",textAlign:"left",transition:"border-color 0.15s"},children:[s.jsx(Yr,{driver:D.config.driver,size:18}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:D.label}),s.jsx("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:D.description})]})]},D.name))})]})}),wf=s.jsx(s.Fragment,{children:v?s.jsx(Cl,{t:o,editName:We,setEditName:Be,editDriver:Ee,setEditDriver:ge,editFields:Je,setEditFields:tt,onSave:Yn,onCancel:me,saving:w,isNew:!0}):s.jsxs("button",{onClick:ve,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"]})}),kf=s.jsx(s.Fragment,{children:C&&s.jsx("div",{style:{fontSize:11,fontFamily:o.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:kl(C,o),background:`${kl(C,o)}12`},children:C})}),Cf=s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:en,disabled:u||!Io,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:u||!Io?"not-allowed":"pointer",marginBottom:8,opacity:u||!Io?.7:1,transition:"all 0.15s"},children:u?"Testing...":Io?"Test Connection":"Add connection to test"}),d&&s.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:d.ok?o.success:o.error,background:d.ok?`${o.success}12`:`${o.error}12`,border:`1px solid ${d.ok?o.success:o.error}40`,borderRadius:6,padding:"7px 10px",marginBottom:12},children:[d.ok?"✓ ":"✗ ",d.message]})]}),jf=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Oo,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:$s.map(({driver:D,label:z})=>{const ae=ns[D]??o.accent,re=Hk[D]??"",ue=Ua[D],we=(ue==null?void 0:ue.installed)??!0,Ve=(ue==null?void 0:ue.builtIn)??!1,Zn=E===D;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(Yr,{driver:D,size:18,fallbackColor:ae}),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:re}),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:we?o.success:o.warning,letterSpacing:"0.05em",textTransform:"uppercase"},children:Ve?"Built in":we?"Installed":"Install required"}),!we&&s.jsx("button",{onClick:()=>nn(D),disabled:!!E,title:ue==null?void 0:ue.installCommand,style:{border:`1px solid ${o.btnBorder}`,background:o.btnBg,color:o.textSecondary,borderRadius:4,padding:"2px 7px",fontSize:10,fontFamily:o.font,cursor:E?"not-allowed":"pointer",whiteSpace:"nowrap"},children:Zn?"Installing...":"Install"})]}),s.jsx("code",{style:{fontSize:9,color:o.textMuted,fontFamily:o.fontMono},children:D})]},D)})})]}),Tt=!!(c&&Object.values(c.connections??{}).some(D=>!ho(D))),Me=c==null?void 0:c.metadataStatus,Ef=si(W),Tf=Tt?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 Tn(),disabled:xe||F||!(d!=null&&d.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||F||!(d!=null&&d.ok)?"not-allowed":"pointer",opacity:d!=null&&d.ok?1:.55,fontFamily:o.font},children:xe?"Finding available schemas…":"Find available databases & schemas"})}),ce?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:[ce.dbtScopes.reduce((D,z)=>D+z.schemas.length,0).toLocaleString()," dbt-covered schema(s)"," · ",Vk(ce).toLocaleString()," additional schema(s) available"," · ",ce.queryCount.toLocaleString()," discovery query(s)"]}),ce.scopes.map(D=>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:D.catalogOrDatabase}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:5},children:D.schemas.map(z=>{const ae=Wk(Ef,D.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||ae,disabled:z.inDbtProject||F,onChange:re=>An(D.catalogOrDatabase,z.name,re.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"]})]},`${D.catalogOrDatabase}.${z.name}`)})})]},D.catalogOrDatabase)),ce.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:D=>X(D.target.value),disabled:F,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:W,onChange:D=>te(D.target.value),disabled:F,placeholder:`ANALYTICS_PROD: SALES, FINANCE
443
- 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,Me?s.jsxs("div",{style:{fontSize:11.5,color:Me.state==="ready"?"var(--status-success)":"var(--status-warning)",fontFamily:o.font},children:[Me.state==="ready"?"Warehouse metadata index ready":Me.state==="stale"?"Warehouse metadata refresh required":G?"Optional warehouse metadata index not synchronized · dbt project objects remain available":"Warehouse metadata index not synchronized"," · ",Me.relationCount.toLocaleString()," indexed warehouse relations"," · ",Me.columnCount.toLocaleString()," indexed warehouse columns",Me.capturedAt?` · ${new Date(Me.capturedAt).toLocaleString()}`:""]}):null,Me!=null&&Me.observedTarget?s.jsx("div",{style:{fontSize:10.5,color:o.textMuted,fontFamily:o.fontMono},children:[Me.observedTarget.accountOrWorkspace,Me.observedTarget.role,Me.observedTarget.warehouse,Me.observedTarget.defaultCatalogOrDatabase,Me.observedTarget.defaultSchema].filter(Boolean).join(" · ")}):null,oe?s.jsx("div",{style:{fontSize:11.5,color:oe.toLowerCase().includes("failed")||oe.toLowerCase().includes("error")?"var(--status-error)":o.textSecondary,fontFamily:o.font},children:oe}):null,s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void U(),disabled:F||!(d!=null&&d.ok),style:{height:32,padding:"0 13px",borderRadius:8,border:"none",background:o.accent,color:"var(--accent-fg)",fontSize:12,fontWeight:700,cursor:F||!(d!=null&&d.ok)?"not-allowed":"pointer",opacity:F||!(d!=null&&d.ok)?.55:1,fontFamily:o.font},children:F?"Synchronizing…":"Apply and synchronize"}),s.jsx("button",{type:"button",onClick:()=>void se(),disabled:F||(Me==null?void 0:Me.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:F?"not-allowed":"pointer",fontFamily:o.font},children:"Refresh metadata"})]}),d!=null&&d.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,Ha=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 ${d!=null&&d.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:Tt?"var(--status-success-bg)":"var(--status-warning-bg)",color:Tt?"var(--status-success)":"var(--status-warning)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx(To,{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:[ii[String(((Ja=(Qa=c==null?void 0:c.connections)==null?void 0:Qa[(c==null?void 0:c.default)??""])==null?void 0:Ja.driver)??"")]??((Xa=(Ya=c==null?void 0:c.connections)==null?void 0:Ya[(c==null?void 0:c.default)??""])==null?void 0:Xa.driver)??"No connection yet",Tt?" · configured":""]}),s.jsx("div",{style:{fontSize:11.5,marginTop:2,color:u?o.textMuted:d?d.ok?"var(--status-success)":"var(--status-error)":o.textMuted},children:u?"Testing…":d?d.ok?`Test passed · ${d.message}`:`Test failed · ${d.message}`:Tt?"Configured — run Test connection to verify.":"Add a connection below to get started."})]}),s.jsx("button",{type:"button",onClick:()=>void en(),disabled:u||!Tt,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:Tt?"pointer":"not-allowed",fontFamily:o.font,flexShrink:0,opacity:Tt?1:.55},children:u?"Testing…":"Test connection"})]}),s.jsxs("div",{style:{maxWidth:640},children:[Ka,Va]}),s.jsx(o1,{t:o,driver:Fe,fields:bt,onDriverChange:Ro,onFieldsChange:Mt,onSave:()=>void Xn(),saving:w,saveMessage:C,connectorStatus:Ua[Fe],installing:E===Fe,onInstall:()=>void nn(Fe)}),Tf]});if(a)return Ha;if(i){const D=n.settingsTab,z=M.some(re=>re.configured&&re.enabled),ae=(re,ue,we,Ve)=>s.jsxs("button",{type:"button",onClick:we,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:re?"var(--accent-dim)":"transparent",color:re?o.accent:o.textSecondary},children:[s.jsx("span",{style:{flex:1},children:ue}),Ve]},ue);return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:n1}),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:[ae(D==="overview","Overview",()=>r({type:"SET_SETTINGS_TAB",tab:"overview"})),ae(D==="project","Project & dbt",()=>r({type:"SET_SETTINGS_TAB",tab:"project"}),s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:(H==null?void 0:H.status)==="failed"?"var(--status-error)":(H==null?void 0:H.status)==="running"||(H==null?void 0:H.status)==="queued"?"var(--status-info)":G?"var(--status-success)":"var(--status-warning)"},title:(H==null?void 0:H.status)==="failed"?"Needs attention":(H==null?void 0:H.status)==="running"||(H==null?void 0:H.status)==="queued"?"Preparing":G?"Ready":"Missing"})),ae(D==="database","Database",()=>r({type:"SET_SETTINGS_TAB",tab:"database"}),s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:Tt?"var(--status-success)":"var(--status-warning)"},title:Tt?"Configured":"Missing"})),ae(D==="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"})),ae(D==="memory","Agent memory",()=>r({type:"SET_SETTINGS_TAB",tab:"memory"})),s.jsx("div",{style:{height:1,background:o.cellBorder,margin:"10px 10px 10px 0"}}),ae(D==="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:D==="overview"?s.jsx(t1,{dbtConfigured:G,dbtPreparation:H,databaseConfigured:Tt,databaseTest:d,providers:M}):D==="project"?s.jsx(Uk,{onConfigured:()=>{J(!0),B.getOnboardingStatus().then(re=>L(re.preparation??null)).catch(()=>{})}}):D==="advanced"?s.jsx(ti,{embedded:!0,section:"advanced"}):D==="database"?Ha:D==="ai"?s.jsx(ti,{embedded:!0,section:"providers",onProviderConfigured:re=>q(ue=>ue.map(we=>we.id===re.id?re:{...we,active:!1}))}):s.jsx(ti,{embedded:!0,section:"memory"})})]})]})}return s.jsxs(Ta,{title:"Connections",bodyPadding:12,children:[vf,Ka,Va,Sf,wf,kf,Cf,jf]})}function t1({dbtConfigured:e,dbtPreparation:t,databaseConfigured:n,databaseTest:r,providers:o}){const i=Ge(d=>d.themeMode),a=jn(),c=Qe[i],l=o.find(d=>d.active&&d.configured)??o.find(d=>d.enabled&&d.configured),u=[{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(Nr,{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(To,{size:18})},{title:"AI provider",detail:l?`${l.label}${l.model?` · ${l.model}`:""}. Run Test to verify reachability.`:"Optional. Deterministic and non-AI workflows remain available.",state:l?"configured":"missing",tab:"ai",icon:s.jsx(xp,{size:18}),optional:!0}],h={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:c.textPrimary},children:"Settings overview"}),s.jsx("div",{style:{fontSize:12.5,color:c.textMuted,marginTop:4,lineHeight:1.5},children:"One place for project, data, AI, memory, and advanced runtime configuration."})]}),s.jsxs("button",{type:"button",onClick:()=>a({type:"OPEN_SETUP"}),style:{display:"inline-flex",alignItems:"center",gap:7,height:34,padding:"0 15px",borderRadius:8,border:"none",background:c.accent,color:"#fff",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:c.font,whiteSpace:"nowrap"},children:[s.jsx(DS,{size:14})," Guided Setup"]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:12},children:u.map(d=>{const f=d.state==="configured"||d.state==="passed",m=d.state==="preparing",S=d.state==="failed",v=S?"var(--status-error)":m?"var(--status-info)":f?"var(--status-success)":"var(--status-warning)",b=S?"var(--status-error-bg)":m?"var(--status-info-bg)":f?"var(--status-success-bg)":"var(--status-warning-bg)";return s.jsxs("button",{type:"button",onClick:()=>a({type:"SET_SETTINGS_TAB",tab:d.tab}),style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:c.cellBg,padding:16,textAlign:"left",cursor:"pointer",fontFamily:c.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:v,background:b},children:f?s.jsx(hp,{size:18}):d.icon}),s.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:c.textPrimary,marginTop:12},children:d.title}),s.jsxs("span",{style:{fontSize:11,fontWeight:700,color:v,marginTop:4},children:[h[d.state],d.optional?" · optional":""]}),s.jsx("span",{style:{fontSize:11.5,color:c.textMuted,lineHeight:1.45,marginTop:7},children:d.detail})]},d.title)})}),l?null:s.jsx("div",{style:{border:"1px solid var(--status-info-border)",background:"var(--status-info-bg)",color:c.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 n1=`
442
+ `)}function si(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(l=>l.trim()).filter(Boolean);if(!o||i.length===0)continue;const a=o.toLowerCase(),c=t.get(a)??{catalogOrDatabase:o,schemas:new Set};for(const l of i)c.schemas.add(l);t.set(a,c)}return Array.from(t.values()).map(n=>({catalogOrDatabase:n.catalogOrDatabase,schemas:Array.from(n.schemas)}))}function Kk(e,t,n){return e.some(r=>r.catalogOrDatabase.toLowerCase()===t.toLowerCase()&&r.schemas.some(o=>o.toLowerCase()===n.toLowerCase()))}function Vk(e,t,n,r){const o=new Map(e.map(c=>[c.catalogOrDatabase.toLowerCase(),{catalogOrDatabase:c.catalogOrDatabase,schemas:new Map(c.schemas.map(l=>[l.toLowerCase(),l]))}])),i=t.toLowerCase(),a=o.get(i)??{catalogOrDatabase:t,schemas:new Map};return r?a.schemas.set(n.toLowerCase(),n):a.schemas.delete(n.toLowerCase()),a.schemas.size>0?o.set(i,a):o.delete(i),Array.from(o.values()).map(c=>({catalogOrDatabase:c.catalogOrDatabase,schemas:Array.from(c.schemas.values())}))}function Hk(e){return e.scopes.reduce((t,n)=>t+n.schemas.filter(r=>!r.inDbtProject).length,0)}const ii={duckdb:"DuckDB",file:"Local File / DuckDB",snowflake:"Snowflake",databricks:"Databricks"},ns={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"},Gk={duckdb:"In-process analytical database",file:"Local CSV / Parquet via DuckDB",snowflake:"Cloud data platform",databricks:"Lakehouse platform"},$s=[{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"}]}],Na=Object.fromEntries($s.map(e=>[e.driver,e])),Qk=[{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 Xr(e){return e==="postgres"?"postgresql":e}function Ki(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 Jk(e){return`${e.profileName}_${e.targetName}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"dbt_profile"}function Yk(e){const t={};return Object.entries(e.connection??{}).forEach(([n,r])=>{n!=="driver"&&r!==void 0&&r!==null&&(t[Ki(n)]=String(r))}),t}function Xk(e){const n=e.indexOf("/.dbt/");return n>=0?`~${e.slice(n)}`:e.split("/").slice(-3).join("/")}function Zk(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 Cl(e,t){return e.startsWith("Error")||e.toLowerCase().includes("failed")?t.error:e.toLowerCase().includes("testing")?t.warning:t.success}function ho(e){const t=Xr(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 e1(e,t,n,r){const o=r!==null&&r===t,i=!!(t&&e[t]),a=e[n];return r===null||o||!i||t==="default"&&ho(e.default)&&!ho(a)?n:t}function t1(e){const t=Object.keys(e);return t.find(n=>!ho(e[n]))??t[0]}function Jp({variant:e="panel",onConfigured:t}={}){var Ga,Qa,Ja,Ya,Xa;const n=Ge(Lr(D=>({settingsTab:D.settingsTab,themeMode:D.themeMode}))),r=jn(),o=Qe[n.themeMode],i=e==="page",a=e==="setup",[c,l]=p.useState(null),[u,h]=p.useState(!1),[d,f]=p.useState(null),[m,S]=p.useState(null),[v,b]=p.useState(!1),[w,j]=p.useState(!1),[C,x]=p.useState(null),[E,P]=p.useState(null),[A,g]=p.useState(""),[I,T]=p.useState(!1),[O,_]=p.useState(null),[M,q]=p.useState([]),[G,J]=p.useState(!1),[H,L]=p.useState(null),[$,X]=p.useState("dbt_relations"),[W,te]=p.useState(""),[F,K]=p.useState(!1),[oe,ee]=p.useState(null),[ce,ke]=p.useState(null),[xe,De]=p.useState(!1),[We,Be]=p.useState(""),[Ee,ge]=p.useState("duckdb"),[Je,tt]=p.useState({}),[Fe,Ke]=p.useState("duckdb"),[bt,Mt]=p.useState({}),jt=p.useRef(null);p.useEffect(()=>{B.getConnections().then(D=>{l(D),D.metadataScope&&(X(D.metadataScope.mode),te(Qo(D.metadataScope.selectedScopes??D.metadataScope.scopes)))})},[]);const Et=c?`${c.default}:${JSON.stringify(((Ga=c.connections)==null?void 0:Ga[c.default])??null)}`:"";p.useEffect(()=>{if(!c||i&&n.settingsTab!=="database"||!Object.values(c.connections).some(z=>!ho(z)))return;let D=!0;return h(!0),B.testConnection().then(z=>{D&&f(z)}).catch(z=>{D&&f({ok:!1,message:z instanceof Error?z.message:String(z)})}).finally(()=>{D&&h(!1)}),()=>{D=!1}},[Et,i,n.settingsTab]),p.useEffect(()=>{if(!i)return;let D=!0;return Promise.all([B.getProviderSettings(),B.getOnboardingStatus(),B.getBlockStudioDbtStatus().catch(()=>null)]).then(([z,ae,re])=>{var ue;D&&(q(z.providers),J(((ue=ae.dbt)==null?void 0:ue.configured)===!0||!!(re!=null&&re.configured&&re.artifacts.manifest.exists)),L(ae.preparation??null))}).catch(()=>{}),()=>{D=!1}},[i]),p.useEffect(()=>{if(!i||!H||H.status!=="queued"&&H.status!=="running")return;let D=!0,z;const ae=async()=>{var re,ue,we;try{const Ve=await B.getOnboardingStatus();if(!D)return;L(Ve.preparation??null),J(((re=Ve.dbt)==null?void 0:re.configured)===!0),(((ue=Ve.preparation)==null?void 0:ue.status)==="queued"||((we=Ve.preparation)==null?void 0:we.status)==="running")&&(z=window.setTimeout(()=>void ae(),700))}catch{}};return z=window.setTimeout(()=>void ae(),500),()=>{D=!1,z!==void 0&&window.clearTimeout(z)}},[H==null?void 0:H.id,H==null?void 0:H.status,i]),p.useEffect(()=>{var re;if(!c)return;const D=c.default,z=D?(re=c.connections)==null?void 0:re[D]:void 0,ae=z?`${D}::${JSON.stringify(z)}`:"::none";if(jt.current!==ae)if(jt.current=ae,z){Ke(Xr(String(z.driver??z.type??"duckdb")));const ue={};Object.entries(z).forEach(([we,Ve])=>{we!=="driver"&&we!=="type"&&(ue[Ki(we)]=String(Ve??""))}),Mt(ue)}else Ke("duckdb"),Mt({})},[c]);const en=async()=>{if(!c||Object.keys(c.connections??{}).length===0){f({ok:!1,message:"Add or import a connection before testing."});return}h(!0),f(null);const D=await B.testConnection();f(D),D.ok&&(t==null||t(D.message)),h(!1)},tn=D=>{l(z=>z&&{...z,metadataScope:D.scope,metadataStatus:D.status}),X(D.scope.mode),te(Qo(D.scope.selectedScopes??D.scope.scopes))},Tn=async()=>{if(!(!(c!=null&&c.default)||!(d!=null&&d.ok))){De(!0),ee("Finding databases/catalogs and schemas visible to this connection…");try{const D=await B.discoverConnectionMetadataScopes(c.default);ke(D),ee(D.message)}catch(D){ke(null),ee(D instanceof Error?D.message:String(D))}finally{De(!1)}}},An=(D,z,ae)=>{const re=Vk(si(W),D,z,ae);te(Qo(re)),X(((ce==null?void 0:ce.dbtScopes.length)??0)>0?"dbt_plus_selected":"selected_scopes")},U=async()=>{if(!(c!=null&&c.default))return;const D=si(W);if($==="selected_scopes"&&D.length===0){ee("Add at least one line such as ANALYTICS_PROD: SALES, FINANCE.");return}K(!0),ee("Synchronizing selected metadata into local SQLite…");try{const z=await B.applyConnectionMetadataScope(c.default,{mode:$,...$==="dbt_relations"?{}:{scopes:D}});tn(z),ee(`Ready · ${z.status.relationCount.toLocaleString()} relations · ${z.status.columnCount.toLocaleString()} columns · ${z.status.queryCount??0} metadata queries`)}catch(z){ee(z instanceof Error?z.message:String(z))}finally{K(!1)}},se=async()=>{if(c!=null&&c.default){K(!0),ee("Refreshing the applied metadata scope…");try{const D=await B.refreshConnectionMetadata(c.default);tn(D),ee(`Refreshed · ${D.status.relationCount.toLocaleString()} relations · ${D.status.columnCount.toLocaleString()} columns`)}catch(D){ee(D instanceof Error?D.message:String(D))}finally{K(!1)}}},je=(D,z)=>{S(D),b(!1),Be(D),ge(Xr((z==null?void 0:z.driver)??(z==null?void 0:z.type)??"duckdb"));const ae={};Object.entries(z??{}).forEach(([re,ue])=>{re!=="driver"&&re!=="type"&&(ae[Ki(re)]=String(ue??""))}),tt(ae)},ve=()=>{b(!0),S(null),Be(""),ge("duckdb"),tt({})},me=()=>{S(null),b(!1)},nn=async D=>{P(D),x(null);try{const z=await B.installConnector(D);if(z.connectorStatus&&c)l({...c,connectorStatus:z.connectorStatus});else{const ae=await B.getConnections();l(ae)}x(z.ok?"Connector installed":`Error: ${z.error??"Install failed"}`)}catch(z){x(`Error: ${(z==null?void 0:z.message)??"Install failed"}`)}finally{P(null)}},ie=async D=>{if(!c)return!1;j(!0),x(null);const z=D.name.trim()||(D.previousName??"default"),ae={driver:D.driver},re=Na[D.driver],ue=new Map(((re==null?void 0:re.fields)??[]).map(Ye=>[Ye.key,Ye]));Object.entries(D.fields).forEach(([Ye,nt])=>{const At=ue.get(Ye);if((At==null?void 0:At.type)==="checkbox"){nt!==""&&(ae[Ye]=nt==="true");return}const Do=nt.trim();Do&&((At==null?void 0:At.type)==="number"&&!isNaN(Number(Do))?ae[Ye]=Number(Do):ae[Ye]=Do)});const we={...c.connections},Ve=c.default,Zn={...c.connections};D.previousName&&D.previousName!==z&&delete Zn[D.previousName],Zn[z]=ae;const Rf=e1(Zn,c.default,z,D.previousName);let Za=!1;try{await B.saveConnections(Zn,Rf);const Ye=await B.getConnections();l(Ye),Ye.metadataScope&&(X(Ye.metadataScope.mode),te(Qo(Ye.metadataScope.selectedScopes??Ye.metadataScope.scopes))),ke(null),x("Saved. Testing connection..."),S(null),b(!1);try{h(!0);const nt=await B.testConnection();if(f(nt),Za=nt.ok,nt.ok)x("Test passed. Connection saved and activated."),t==null||t(nt.message),setTimeout(()=>x(null),2e3);else{await B.saveConnections(we,Ve||void 0);const At=await B.getConnections();l(At),x(`Test failed. Previous connection preserved: ${nt.message}`)}}catch(nt){await B.saveConnections(we,Ve||void 0).catch(()=>{});const At=await B.getConnections().catch(()=>null);At&&l(At),x(`Test failed. Previous connection preserved: ${nt.message??"Connection failed"}`)}finally{h(!1)}}catch(Ye){await B.saveConnections(we,Ve||void 0).catch(()=>{});const nt=await B.getConnections().catch(()=>null);nt&&l(nt),x(`Test or save failed. Previous connection preserved: ${Ye.message}`)}finally{j(!1)}return Za},Y=D=>{const z=Xr(String(D.connection.driver??D.adapter??"duckdb")),ae=Yk(D);f(null),(i||a)&&(Ke(z),Mt(ae)),b(!1),S(null),ie({name:Jk(D),driver:z,fields:ae,previousName:null})},$e=async()=>{const D=A.trim();if(!D){_("Enter a profiles.yml file or folder path.");return}T(!0),_(null);try{const z=await B.previewDbtProfiles(D);l(ae=>{if(!ae)return ae;const re=new Map((ae.dbtProfiles??[]).map(ue=>[ue.id,ue]));return z.dbtProfiles.forEach(ue=>re.set(ue.id,ue)),{...ae,dbtProfiles:[...re.values()]}})}catch(z){_(z instanceof Error?z.message:"Could not read that profiles.yml path.")}finally{T(!1)}},Yn=()=>ie({name:We,driver:Ee,fields:Je,previousName:m}),Xn=()=>ie({name:(c==null?void 0:c.default)||"default",driver:Fe,fields:bt,previousName:(c==null?void 0:c.default)||null}),Ro=D=>{Ke(D),Mt({}),f(null)},bf=async D=>{if(!c)return;const z={...c.connections};delete z[D];const ae=D===c.default?t1(z):c.default;j(!0);try{await B.saveConnections(z,ae);const re=await B.getConnections();l(re),S(null)}finally{j(!1)}},xf=async D=>{if(!c)return;const z=c.default;j(!0),x(null);try{await B.saveConnections(c.connections,D);const ae=await B.getConnections();l(ae),x("Default updated. Testing connection..."),h(!0);const re=await B.testConnection();if(f(re),re.ok)x("Test passed. Default connection updated."),t==null||t(re.message),setTimeout(()=>x(null),2e3);else{await B.saveConnections(c.connections,z||void 0);const ue=await B.getConnections();l(ue),x(`Test failed. Previous default preserved: ${re.message}`)}}catch(ae){await B.saveConnections(c.connections,z||void 0).catch(()=>{});const re=await B.getConnections().catch(()=>null);re&&l(re),x(`Test or save failed. Previous default preserved: ${ae.message}`)}finally{h(!1),j(!1)}},Oo={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:o.textMuted,fontFamily:o.font,marginBottom:6},_o={background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},Po=(c==null?void 0:c.connections)??{},vf=(c==null?void 0:c.default)??"",qa=(c==null?void 0:c.dbtProfiles)??[],Ua=Object.fromEntries(((c==null?void 0:c.connectorStatus)??[]).map(D=>[D.driver,D])),Wa=Object.keys(Po).length,Io=Wa>0,Sf=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:Oo,children:"Connections"}),c===null?s.jsx("div",{style:{fontSize:12,color:o.textMuted,fontFamily:o.font},children:"Loading…"}):Object.entries(Po).map(([D,z])=>{const ae=(z==null?void 0:z.driver)??(z==null?void 0:z.type)??"unknown",re=D===vf,ue=ns[ae]??o.accent;return m===D?s.jsx(jl,{t:o,editName:We,setEditName:Be,editDriver:Ee,setEditDriver:ge,editFields:Je,setEditFields:tt,onSave:Yn,onCancel:me,onDelete:()=>bf(D),saving:w,isNew:!1},D):s.jsxs("div",{style:{..._o,borderLeft:re?`3px solid ${ue}`:`1px solid ${o.cellBorder}`},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[s.jsx(Yr,{driver:ae,size:18,fallbackColor:ue}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:ii[ae]??ae}),s.jsx("span",{style:{fontSize:11,fontFamily:o.fontMono,color:o.textMuted},children:D}),re&&(d==null?void 0:d.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`}}),re&&d&&!d.ok&&s.jsx("span",{title:d.message,"aria-label":"Disconnected",style:{width:7,height:7,borderRadius:"50%",background:o.error,flexShrink:0,boxShadow:`0 0 0 2px ${o.error}25`}}),re&&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}}),!re&&s.jsx("button",{onClick:()=>xf(D),disabled:w,style:{background:"transparent",border:`1px solid ${o.btnBorder}`,borderRadius:3,cursor:w?"not-allowed":"pointer",color:o.textMuted,fontSize:10,fontFamily:o.font,padding:"1px 6px",transition:"all 0.15s"},children:"Use"}),s.jsx("button",{onClick:()=>je(D,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(([we])=>we!=="driver"&&we!=="type").map(([we,Ve])=>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:we}),s.jsx("span",{style:{fontSize:11,color:o.textSecondary,fontFamily:o.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Zk(we)?"••••••••":String(Ve)})]},we))})]},D)}),c!==null&&Wa===0&&s.jsx("div",{style:{..._o,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."})]}),Ka=s.jsxs("div",{style:{..._o,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:A,onChange:D=>g(D.target.value),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),$e())},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 $e(),disabled:I,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:I?"wait":"pointer"},children:I?"Reading…":"Find profiles"})]}),O?s.jsx("div",{role:"alert",style:{marginTop:6,color:o.error,fontSize:10.5,fontFamily:o.font},children:O}):null]}),Va=s.jsx(s.Fragment,{children:!v&&!m&&qa.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Oo,marginTop:8},children:"dbt profiles"}),s.jsx("div",{style:{display:"grid",gap:8,marginBottom:12},children:qa.map(D=>{var we;const z=Xr(String(D.connection.driver??D.adapter)),ae=ns[z]??o.accent,re=D.missingFields.length===0,ue=((we=c==null?void 0:c.activeConnection)==null?void 0:we.source)==="dbt_profile"&&c.activeConnection.profileId===D.id;return s.jsxs("div",{style:{..._o,marginBottom:0,display:"flex",alignItems:"center",gap:10},children:[s.jsx(Yr,{driver:z,size:18,fallbackColor:ae}),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:D.profileName}),s.jsx("span",{style:{fontSize:11,color:o.textMuted,fontFamily:o.fontMono},children:D.targetName})]}),s.jsxs("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[ii[z]??D.adapter," from ",Xk(D.path)]}),s.jsx("div",{style:{fontSize:10,color:re?o.success:o.warning,fontFamily:o.font,marginTop:2},children:re?ue?"Active runtime connection · import to save":"Ready to import and test":`Imports now · needs ${D.missingFields.join(", ")}`})]}),s.jsx("button",{onClick:()=>Y(D),disabled:w,title:D.warnings.join(" ")||void 0,style:{background:o.btnBg,border:`1px solid ${o.btnBorder}`,borderRadius:4,cursor:w?"wait":"pointer",color:o.textSecondary,fontSize:11,fontFamily:o.font,padding:"4px 8px",flexShrink:0},children:"Import & test"})]},D.id)})})]})}),wf=s.jsx(s.Fragment,{children:!v&&!m&&Object.keys(Po).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Oo,marginTop:8},children:"Quick Connect"}),s.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:Qk.map(D=>s.jsxs("button",{onClick:async()=>{j(!0);try{const z={...Po,[D.name]:D.config};await B.saveConnections(z,D.name);const ae=await B.getConnections();l(ae),h(!0);const re=await B.testConnection();f(re),h(!1)}finally{j(!1)}},disabled:w,style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:7,cursor:w?"not-allowed":"pointer",textAlign:"left",transition:"border-color 0.15s"},children:[s.jsx(Yr,{driver:D.config.driver,size:18}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:12,fontWeight:600,color:o.textPrimary,fontFamily:o.font},children:D.label}),s.jsx("div",{style:{fontSize:10,color:o.textMuted,fontFamily:o.font},children:D.description})]})]},D.name))})]})}),kf=s.jsx(s.Fragment,{children:v?s.jsx(jl,{t:o,editName:We,setEditName:Be,editDriver:Ee,setEditDriver:ge,editFields:Je,setEditFields:tt,onSave:Yn,onCancel:me,saving:w,isNew:!0}):s.jsxs("button",{onClick:ve,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"]})}),Cf=s.jsx(s.Fragment,{children:C&&s.jsx("div",{style:{fontSize:11,fontFamily:o.font,padding:"4px 10px",borderRadius:4,marginBottom:8,color:Cl(C,o),background:`${Cl(C,o)}12`},children:C})}),jf=s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:en,disabled:u||!Io,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:u||!Io?"not-allowed":"pointer",marginBottom:8,opacity:u||!Io?.7:1,transition:"all 0.15s"},children:u?"Testing...":Io?"Test Connection":"Add connection to test"}),d&&s.jsxs("div",{style:{fontSize:12,fontFamily:o.font,color:d.ok?o.success:o.error,background:d.ok?`${o.success}12`:`${o.error}12`,border:`1px solid ${d.ok?o.success:o.error}40`,borderRadius:6,padding:"7px 10px",marginBottom:12},children:[d.ok?"✓ ":"✗ ",d.message]})]}),Ef=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Oo,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:$s.map(({driver:D,label:z})=>{const ae=ns[D]??o.accent,re=Gk[D]??"",ue=Ua[D],we=(ue==null?void 0:ue.installed)??!0,Ve=(ue==null?void 0:ue.builtIn)??!1,Zn=E===D;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(Yr,{driver:D,size:18,fallbackColor:ae}),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:re}),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:we?o.success:o.warning,letterSpacing:"0.05em",textTransform:"uppercase"},children:Ve?"Built in":we?"Installed":"Install required"}),!we&&s.jsx("button",{onClick:()=>nn(D),disabled:!!E,title:ue==null?void 0:ue.installCommand,style:{border:`1px solid ${o.btnBorder}`,background:o.btnBg,color:o.textSecondary,borderRadius:4,padding:"2px 7px",fontSize:10,fontFamily:o.font,cursor:E?"not-allowed":"pointer",whiteSpace:"nowrap"},children:Zn?"Installing...":"Install"})]}),s.jsx("code",{style:{fontSize:9,color:o.textMuted,fontFamily:o.fontMono},children:D})]},D)})})]}),Tt=!!(c&&Object.values(c.connections??{}).some(D=>!ho(D))),Me=c==null?void 0:c.metadataStatus,Tf=si(W),Af=Tt?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 Tn(),disabled:xe||F||!(d!=null&&d.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||F||!(d!=null&&d.ok)?"not-allowed":"pointer",opacity:d!=null&&d.ok?1:.55,fontFamily:o.font},children:xe?"Finding available schemas…":"Find available databases & schemas"})}),ce?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:[ce.dbtScopes.reduce((D,z)=>D+z.schemas.length,0).toLocaleString()," dbt-covered schema(s)"," · ",Hk(ce).toLocaleString()," additional schema(s) available"," · ",ce.queryCount.toLocaleString()," discovery query(s)"]}),ce.scopes.map(D=>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:D.catalogOrDatabase}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:5},children:D.schemas.map(z=>{const ae=Kk(Tf,D.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||ae,disabled:z.inDbtProject||F,onChange:re=>An(D.catalogOrDatabase,z.name,re.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"]})]},`${D.catalogOrDatabase}.${z.name}`)})})]},D.catalogOrDatabase)),ce.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:D=>X(D.target.value),disabled:F,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:W,onChange:D=>te(D.target.value),disabled:F,placeholder:`ANALYTICS_PROD: SALES, FINANCE
443
+ 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,Me?s.jsxs("div",{style:{fontSize:11.5,color:Me.state==="ready"?"var(--status-success)":"var(--status-warning)",fontFamily:o.font},children:[Me.state==="ready"?"Warehouse metadata index ready":Me.state==="stale"?"Warehouse metadata refresh required":G?"Optional warehouse metadata index not synchronized · dbt project objects remain available":"Warehouse metadata index not synchronized"," · ",Me.relationCount.toLocaleString()," indexed warehouse relations"," · ",Me.columnCount.toLocaleString()," indexed warehouse columns",Me.capturedAt?` · ${new Date(Me.capturedAt).toLocaleString()}`:""]}):null,Me!=null&&Me.observedTarget?s.jsx("div",{style:{fontSize:10.5,color:o.textMuted,fontFamily:o.fontMono},children:[Me.observedTarget.accountOrWorkspace,Me.observedTarget.role,Me.observedTarget.warehouse,Me.observedTarget.defaultCatalogOrDatabase,Me.observedTarget.defaultSchema].filter(Boolean).join(" · ")}):null,oe?s.jsx("div",{style:{fontSize:11.5,color:oe.toLowerCase().includes("failed")||oe.toLowerCase().includes("error")?"var(--status-error)":o.textSecondary,fontFamily:o.font},children:oe}):null,s.jsxs("div",{style:{display:"flex",gap:8},children:[s.jsx("button",{type:"button",onClick:()=>void U(),disabled:F||!(d!=null&&d.ok),style:{height:32,padding:"0 13px",borderRadius:8,border:"none",background:o.accent,color:"var(--accent-fg)",fontSize:12,fontWeight:700,cursor:F||!(d!=null&&d.ok)?"not-allowed":"pointer",opacity:F||!(d!=null&&d.ok)?.55:1,fontFamily:o.font},children:F?"Synchronizing…":"Apply and synchronize"}),s.jsx("button",{type:"button",onClick:()=>void se(),disabled:F||(Me==null?void 0:Me.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:F?"not-allowed":"pointer",fontFamily:o.font},children:"Refresh metadata"})]}),d!=null&&d.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,Ha=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 ${d!=null&&d.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:Tt?"var(--status-success-bg)":"var(--status-warning-bg)",color:Tt?"var(--status-success)":"var(--status-warning)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx(To,{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:[ii[String(((Ja=(Qa=c==null?void 0:c.connections)==null?void 0:Qa[(c==null?void 0:c.default)??""])==null?void 0:Ja.driver)??"")]??((Xa=(Ya=c==null?void 0:c.connections)==null?void 0:Ya[(c==null?void 0:c.default)??""])==null?void 0:Xa.driver)??"No connection yet",Tt?" · configured":""]}),s.jsx("div",{style:{fontSize:11.5,marginTop:2,color:u?o.textMuted:d?d.ok?"var(--status-success)":"var(--status-error)":o.textMuted},children:u?"Testing…":d?d.ok?`Test passed · ${d.message}`:`Test failed · ${d.message}`:Tt?"Configured — run Test connection to verify.":"Add a connection below to get started."})]}),s.jsx("button",{type:"button",onClick:()=>void en(),disabled:u||!Tt,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:Tt?"pointer":"not-allowed",fontFamily:o.font,flexShrink:0,opacity:Tt?1:.55},children:u?"Testing…":"Test connection"})]}),s.jsxs("div",{style:{maxWidth:640},children:[Ka,Va]}),s.jsx(s1,{t:o,driver:Fe,fields:bt,onDriverChange:Ro,onFieldsChange:Mt,onSave:()=>void Xn(),saving:w,saveMessage:C,connectorStatus:Ua[Fe],installing:E===Fe,onInstall:()=>void nn(Fe)}),Af]});if(a)return Ha;if(i){const D=n.settingsTab,z=M.some(re=>re.configured&&re.enabled),ae=(re,ue,we,Ve)=>s.jsxs("button",{type:"button",onClick:we,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:re?"var(--accent-dim)":"transparent",color:re?o.accent:o.textSecondary},children:[s.jsx("span",{style:{flex:1},children:ue}),Ve]},ue);return s.jsxs(s.Fragment,{children:[s.jsx("style",{children:r1}),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:[ae(D==="overview","Overview",()=>r({type:"SET_SETTINGS_TAB",tab:"overview"})),ae(D==="project","Project & dbt",()=>r({type:"SET_SETTINGS_TAB",tab:"project"}),s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:(H==null?void 0:H.status)==="failed"?"var(--status-error)":(H==null?void 0:H.status)==="running"||(H==null?void 0:H.status)==="queued"?"var(--status-info)":G?"var(--status-success)":"var(--status-warning)"},title:(H==null?void 0:H.status)==="failed"?"Needs attention":(H==null?void 0:H.status)==="running"||(H==null?void 0:H.status)==="queued"?"Preparing":G?"Ready":"Missing"})),ae(D==="database","Database",()=>r({type:"SET_SETTINGS_TAB",tab:"database"}),s.jsx("span",{style:{width:7,height:7,borderRadius:999,background:Tt?"var(--status-success)":"var(--status-warning)"},title:Tt?"Configured":"Missing"})),ae(D==="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"})),ae(D==="memory","Agent memory",()=>r({type:"SET_SETTINGS_TAB",tab:"memory"})),s.jsx("div",{style:{height:1,background:o.cellBorder,margin:"10px 10px 10px 0"}}),ae(D==="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:D==="overview"?s.jsx(n1,{dbtConfigured:G,dbtPreparation:H,databaseConfigured:Tt,databaseTest:d,providers:M}):D==="project"?s.jsx(Wk,{onConfigured:()=>{J(!0),B.getOnboardingStatus().then(re=>L(re.preparation??null)).catch(()=>{})}}):D==="advanced"?s.jsx(ti,{embedded:!0,section:"advanced"}):D==="database"?Ha:D==="ai"?s.jsx(ti,{embedded:!0,section:"providers",onProviderConfigured:re=>q(ue=>ue.map(we=>we.id===re.id?re:{...we,active:!1}))}):s.jsx(ti,{embedded:!0,section:"memory"})})]})]})}return s.jsxs(Ta,{title:"Connections",bodyPadding:12,children:[Sf,Ka,Va,wf,kf,Cf,jf,Ef]})}function n1({dbtConfigured:e,dbtPreparation:t,databaseConfigured:n,databaseTest:r,providers:o}){const i=Ge(d=>d.themeMode),a=jn(),c=Qe[i],l=o.find(d=>d.active&&d.configured)??o.find(d=>d.enabled&&d.configured),u=[{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(Nr,{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(To,{size:18})},{title:"AI provider",detail:l?`${l.label}${l.model?` · ${l.model}`:""}. Run Test to verify reachability.`:"Optional. Deterministic and non-AI workflows remain available.",state:l?"configured":"missing",tab:"ai",icon:s.jsx(vp,{size:18}),optional:!0}],h={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:c.textPrimary},children:"Settings overview"}),s.jsx("div",{style:{fontSize:12.5,color:c.textMuted,marginTop:4,lineHeight:1.5},children:"One place for project, data, AI, memory, and advanced runtime configuration."})]}),s.jsxs("button",{type:"button",onClick:()=>a({type:"OPEN_SETUP"}),style:{display:"inline-flex",alignItems:"center",gap:7,height:34,padding:"0 15px",borderRadius:8,border:"none",background:c.accent,color:"#fff",fontSize:12,fontWeight:700,cursor:"pointer",fontFamily:c.font,whiteSpace:"nowrap"},children:[s.jsx($S,{size:14})," Guided Setup"]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:12},children:u.map(d=>{const f=d.state==="configured"||d.state==="passed",m=d.state==="preparing",S=d.state==="failed",v=S?"var(--status-error)":m?"var(--status-info)":f?"var(--status-success)":"var(--status-warning)",b=S?"var(--status-error-bg)":m?"var(--status-info-bg)":f?"var(--status-success-bg)":"var(--status-warning-bg)";return s.jsxs("button",{type:"button",onClick:()=>a({type:"SET_SETTINGS_TAB",tab:d.tab}),style:{border:"1px solid var(--border-subtle)",borderRadius:12,background:c.cellBg,padding:16,textAlign:"left",cursor:"pointer",fontFamily:c.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:v,background:b},children:f?s.jsx(mp,{size:18}):d.icon}),s.jsx("span",{style:{fontSize:13.5,fontWeight:700,color:c.textPrimary,marginTop:12},children:d.title}),s.jsxs("span",{style:{fontSize:11,fontWeight:700,color:v,marginTop:4},children:[h[d.state],d.optional?" · optional":""]}),s.jsx("span",{style:{fontSize:11.5,color:c.textMuted,lineHeight:1.45,marginTop:7},children:d.detail})]},d.title)})}),l?null:s.jsx("div",{style:{border:"1px solid var(--status-info-border)",background:"var(--status-info-bg)",color:c.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 r1=`
444
444
  .dql-connection-page-stack {
445
445
  display: grid;
446
446
  gap: 16px;
@@ -468,18 +468,18 @@ REFERENCE_DATA: SHARED`,rows:4,style:{resize:"vertical",borderRadius:7,border:`1
468
468
  .dql-connector-installing {
469
469
  animation: dql-connector-shimmer 1.4s ease-in-out infinite;
470
470
  }
471
- `;function Cl({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:i,setEditFields:a,onSave:c,onCancel:l,onDelete:u,saving:h,isNew:d}){const f=Na[r],m=(f==null?void 0:f.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%"},v={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:d?"New Connection":"Edit Connection"}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:v,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:v,children:"Driver"}),s.jsx("select",{style:{...S,fontFamily:e.font},value:r,onChange:b=>{o(b.target.value),a({})},children:$s.map(b=>s.jsx("option",{value:b.driver,children:b.label},b.driver))})]}),m.map(b=>s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("div",{style:v,children:[b.label,b.required?" *":""]}),b.type==="select"?s.jsxs("select",{style:{...S,fontFamily:e.font},value:i[b.key]??"",onChange:w=>a({...i,[b.key]:w.target.value}),children:[s.jsx("option",{value:"",children:"Default"}),(b.options??[]).map(w=>s.jsx("option",{value:w.value,children:w.label},w.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:w=>a({...i,[b.key]:w.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:w=>a({...i,[b.key]:w.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:w=>a({...i,[b.key]:w.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:c,disabled:h,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:h?"not-allowed":"pointer",opacity:h?.6:1},children:h?"Saving…":"Save"}),s.jsx("button",{onClick:l,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"}),u&&!d&&s.jsx("button",{onClick:u,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 r1(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 jl=new Set(["filepath","httpPath","accessUrl"]);function o1({t:e,driver:t,fields:n,onDriverChange:r,onFieldsChange:o,onSave:i,saving:a,saveMessage:c,connectorStatus:l,installing:u,onInstall:h}){const[d,f]=p.useState(!1),m=Na[t],S=(m==null?void 0:m.fields)??[],v=r1(t,n),b=new Set(v),w=S.filter(x=>b.has(x.key)),j=S.filter(x=>!b.has(x.key)),C=(x,E)=>o({...n,[x]:E});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:x=>r(x.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:$s.map(({driver:x,label:E})=>s.jsx("option",{value:x,children:E},x))})]}),s.jsx(s1,{t:e,driver:t,label:(m==null?void 0:m.label)??t,status:l,installing:u,onInstall:h}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:w.map(x=>s.jsx(El,{t:e,field:x,value:n[x.key]??"",onChange:E=>C(x.key,E),fullWidth:jl.has(x.key)},x.key))}),j.length>0&&s.jsxs("details",{open:d,onToggle:x=>f(x.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:d?"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:[j.length," more"]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginTop:12},children:j.map(x=>s.jsx(El,{t:e,field:x,value:n[x.key]??"",onChange:E=>C(x.key,E),fullWidth:jl.has(x.key)||x.type==="textarea"},x.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:c??"Changes apply after a successful test."}),s.jsx("button",{type:"button",onClick:i,disabled:a,style:{height:30,padding:"0 15px",borderRadius:8,border:"none",background:e.accent,color:"#fff",fontSize:12,fontWeight:650,cursor:a?"not-allowed":"pointer",fontFamily:e.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)",opacity:a?.7:1},children:a?"Saving…":"Save connection"})]})]})}function s1({t:e,driver:t,label:n,status:r,installing:o,onInstall:i}){const a=(r==null?void 0:r.builtIn)??!0,c=(r==null?void 0:r.installed)??!0,l=!c&&!a,u=o||l?e.warning:e.success,h=o||l?"var(--status-warning-bg)":"var(--status-success-bg)",d=o||l?"var(--status-warning-border)":"var(--status-success-border)",f=o?"Installing connector package…":a?"Built in — no installation needed":c?"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 ${d}`,borderRadius:9,background:h,padding:"10px 12px"},children:[s.jsx(Yr,{driver:t,size:18,fallbackColor:ns[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:u,fontFamily:e.font,marginTop:1},children:f})]}),l||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:u,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"})}),a?"Ready":"Installed"]})]})}function El({t:e,field:t,value:n,onChange:r,fullWidth:o}){const[i,a]=p.useState(!1),l={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"},u={display:"flex",flexDirection:"column",gap:4,gridColumn:o?"1 / -1":void 0},h=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:{...u,flexDirection:"row",alignItems:"center",gap:8},children:[s.jsx("input",{type:"checkbox",checked:n==="true",onChange:d=>r(d.target.checked?"true":"false")}),h]}):s.jsxs("label",{style:u,children:[h,t.type==="select"?s.jsxs("select",{value:n,onChange:d=>r(d.target.value),onFocus:()=>a(!0),onBlur:()=>a(!1),style:{...l,fontFamily:e.font,fontSize:12.5,padding:"8px 9px"},children:[s.jsx("option",{value:"",children:"Default"}),(t.options??[]).map(d=>s.jsx("option",{value:d.value,children:d.label},d.value))]}):t.type==="textarea"?s.jsx("textarea",{value:n,placeholder:t.placeholder??"",onChange:d=>r(d.target.value),onFocus:()=>a(!0),onBlur:()=>a(!1),style:{...l,minHeight:72,resize:"vertical"}}):s.jsx("input",{type:t.type==="password"?"password":t.type==="number"?"number":"text",value:n,placeholder:t.placeholder??"",onChange:d=>r(d.target.value),onFocus:()=>a(!0),onBlur:()=>a(!1),style:l}),t.helpText&&s.jsx("span",{style:{fontSize:10,color:e.textMuted,fontFamily:e.font,lineHeight:1.35},children:t.helpText})]})}const i1=Object.freeze(Object.defineProperty({__proto__:null,ConnectionPanel:Qp},Symbol.toStringTag,{value:"Module"}));function a1({type:e}){const t=Tw[e]??"#8b949e";return s.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:Ap[e]??e,children:Aw[e]??e.slice(0,4).toUpperCase()})}function c1({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 Jp({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(a1,{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 l1=30,ai=200;function ut(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 ci({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 ot({title:e,nodes:t,t:n,onSelect:r,secondaryFor:o}){const i=t.length>l1,[a,c]=p.useState(!i),[l,u]=p.useState(ai);if(t.length===0)return null;const h=a?Math.min(l,t.length):0,d=Math.max(0,t.length-h);return s.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[s.jsxs("button",{onClick:()=>c(f=>!f),"aria-expanded":a,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:a?"▾":"▸"}),s.jsx("span",{children:e}),s.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),a&&t.slice(0,h).map(f=>s.jsx(Jp,{node:f,t:n,onClick:()=>r(f),secondary:o==null?void 0:o(f)},f.id)),a&&d>0&&s.jsxs("button",{onClick:()=>u(f=>f+ai),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(ai,d)," more (",d," hidden)"]})]})}function d1({variant:e="sidebar"}){const{state:t,dispatch:n}=et(),r=Qe[t.themeMode],o=e==="page",[i,a]=p.useState(()=>typeof window<"u"?window.innerWidth<700:!1),[c,l]=p.useState(!0),[u,h]=p.useState([]),[d,f]=p.useState([]),[m,S]=p.useState(""),[v,b]=p.useState([]),w=p.useCallback(async()=>{l(!0);const g=await B.fetchLineage();h(g.nodes??[]),f(g.edges??[]),l(!1)},[]);p.useEffect(()=>{w()},[w]),p.useEffect(()=>{if(!o)return;const g=()=>a(window.innerWidth<700);return g(),window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[o]),p.useEffect(()=>{let g=!1;if(m.trim().length<2){b([]);return}return B.searchLineage(m.trim()).then(I=>{g||b(I.matches??[])}),()=>{g=!0}},[m]);const j=p.useCallback(g=>{n({type:"OPEN_LINEAGE_DETAIL",nodeId:g.id})},[n]),[C,x]=p.useState("type"),E=p.useMemo(()=>({terms:u.filter(g=>g.type==="term"),businessViews:u.filter(g=>g.type==="business_view"),dashboards:u.filter(g=>g.type==="dashboard"),notebooks:u.filter(g=>g.type==="notebook"),apps:u.filter(g=>g.type==="app"),charts:u.filter(g=>g.type==="chart"),blocks:u.filter(g=>g.type==="block"),metrics:u.filter(g=>g.type==="metric"),dimensions:u.filter(g=>g.type==="dimension"),dbtModels:u.filter(g=>g.type==="dbt_model"),dbtSources:u.filter(g=>g.type==="dbt_source"),tables:u.filter(g=>g.type==="source_table"),domains:u.filter(g=>g.type==="domain")}),[u]),P=p.useMemo(()=>({businessNodes:E.terms.length+E.businessViews.length,businessEdges:d.filter(g=>g.type==="defines"||g.type==="composes").length,technicalNodes:E.tables.length+E.dbtSources.length+E.dbtModels.length+E.metrics.length+E.dimensions.length+E.blocks.length,consumptionNodes:E.charts.length+E.notebooks.length+E.dashboards.length+E.apps.length}),[d,E]),A=p.useMemo(()=>{const g={source:[],transform:[],answer:[],consumption:[]};for(const I of u){const T=_w(I);g[T].push(I)}return g},[u]);return c?s.jsx("div",{style:{padding:16,color:r.textMuted,fontSize:12},children:"Loading lineage..."}):u.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(no,{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(c1,{value:m,onChange:S,placeholder:"Search lineage...",t:r})}),s.jsxs("div",{style:{flex:1,overflow:"auto"},children:[m.trim().length>=2&&v.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"}),v.slice(0,8).map(g=>s.jsx(Jp,{node:g.node,t:r,onClick:()=>j(g.node),secondary:g.node.domain},g.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(ci,{Icon:gv,label:"Business",value:P.businessNodes,detail:`${E.terms.length} terms · ${E.businessViews.length} views · ${P.businessEdges} edges`,t:r}),s.jsx(ci,{Icon:To,label:"Technical",value:P.technicalNodes,detail:`${E.tables.length} tables · ${E.dbtModels.length+E.dbtSources.length} dbt · ${E.blocks.length} blocks`,t:r}),s.jsx(ci,{Icon:gS,label:"Consumption",value:P.consumptionNodes,detail:`${E.dashboards.length} dashboards · ${E.notebooks.length} notebooks · ${E.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:[Zc.map(g=>{const I=A[g].length;return I===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:Rw[g],display:"inline-block"}}),Xc[g],": ",I]},g)}),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:()=>x("type"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",background:C==="type"?`${r.headerBorder}`:"transparent",color:C==="type"?r.textPrimary:r.textMuted},children:"Type"}),s.jsx("button",{onClick:()=>x("layer"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",borderLeft:`1px solid ${r.headerBorder}`,background:C==="layer"?`${r.headerBorder}`:"transparent",color:C==="layer"?r.textPrimary:r.textMuted},children:"Layer"})]})]}),C==="type"?s.jsxs(s.Fragment,{children:[s.jsx(ot,{title:"Business Terms",nodes:E.terms,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Business Views",nodes:E.businessViews,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"DQL Blocks",nodes:E.blocks,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Metrics",nodes:E.metrics,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Dimensions",nodes:E.dimensions,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Dashboards",nodes:E.dashboards,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Notebooks",nodes:E.notebooks,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Apps",nodes:E.apps,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Charts",nodes:E.charts,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"dbt Models",nodes:E.dbtModels,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"dbt Sources",nodes:E.dbtSources,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Source Tables",nodes:E.tables,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Business Domains",nodes:E.domains,t:r,onSelect:j,secondaryFor:ut})]}):s.jsx(s.Fragment,{children:Zc.map(g=>s.jsx(ot,{title:Xc[g],nodes:A[g],t:r,onSelect:j},g))})]})]})}function u1({diff:e,diffReport:t,activeFilePath:n,diffPath:r,onScopeToFile:o,onClearScope:i,t:a}){const c=t!==null&&!t.identical,l=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:Al(r==null,a),children:"All"}),n&&s.jsx("button",{onClick:o,style:Al(r===n,a),children:"Active file"}),r&&s.jsx("span",{style:{color:a.textMuted,fontSize:10,alignSelf:"center",fontFamily:a.fontMono},children:r})]}),c&&s.jsx(p1,{report:t,t:a}),!c&&l&&s.jsx(m1,{diff:e,t:a}),!c&&!l&&s.jsx("div",{style:{color:a.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function p1({report:e,t}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>s.jsx(f1,{change:n,t},r))})}function f1({change:e,t}){const{marker:n,color:r,label:o}=g1(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((a,c)=>s.jsx(h1,{field:a,t},c))})]})}function h1({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:Tl(e.before)}),s.jsx("span",{style:{color:t.textMuted},children:" → "}),s.jsx("span",{style:{color:t.success},children:Tl(e.after)})]})}function m1({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(`
472
- `).map((n,r)=>s.jsx("div",{style:{color:y1(n,t)},children:n||" "},r))})}function g1(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 ${li(e.id,e.name)} [${e.cellType}]`};case"cell-removed":return{...n,label:`cell ${li(e.id,e.name)} [${e.cellType}]`};case"cell-changed":return{...r,label:`cell ${li(e.id,e.name)}`};case"notebook-changed":return{...r,label:"notebook"}}}function li(e,t){return t?`"${t}" (${e.slice(0,8)})`:e.slice(0,8)}function Tl(e,t=60){if(e==null)return"∅";const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}function Al(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 y1(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const b1=2e3,x1={modified:{label:"Modified",color:e=>e.warning,Icon:Uv},added:{label:"Added",color:e=>e.success,Icon:gp},deleted:{label:"Deleted",color:e=>e.error,Icon:Qv},renamed:{label:"Renamed",color:e=>e.accent,Icon:iv},untracked:{label:"Untracked",color:e=>e.textMuted,Icon:Vv}},Rl=["modified","added","renamed","deleted","untracked"];function v1(e){const t=e.trim();return t==="??"?"untracked":t.startsWith("R")?"renamed":t.includes("D")?"deleted":t.includes("A")?"added":"modified"}function S1(){var P;const{state:e}=et(),t=Qe[e.themeMode],[n,r]=p.useState("status"),[o,i]=p.useState(null),[a,c]=p.useState(null),[l,u]=p.useState(""),[h,d]=p.useState(null),[f,m]=p.useState(null),[S,v]=p.useState(!1),[b,w]=p.useState(!1),j=p.useCallback(async()=>{v(!0),w(!0);try{if(n==="status")i(await B.fetchGitStatus());else if(n==="log")c(await B.fetchGitLog(30));else{const A=await B.fetchGitDiff(f??void 0);u(A.diff),d(A.diffReport)}}finally{v(!1),window.setTimeout(()=>w(!1),400)}},[n,f]);p.useEffect(()=>{j()},[j]),p.useEffect(()=>{if(n!=="status")return;const A=window.setInterval(()=>{B.fetchGitStatus().then(g=>{i(I=>w1(I,g)?I:g)})},b1);return()=>window.clearInterval(A)},[n]);const C=((P=e.activeFile)==null?void 0:P.path)??null,x=s.jsxs("button",{onClick:()=>void j(),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(ps,{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); } }"})]}),E=s.jsxs(pp,{children:[s.jsx(di,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),s.jsx(di,{t,active:n==="log",onClick:()=>r("log"),children:"History"}),s.jsx(di,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"})]});return s.jsxs(Ta,{title:"Git",actions:x,toolbar:E,bodyPadding:12,children:[S&&!o&&!a&&s.jsx(no,{title:"Loading…"}),n==="status"&&o&&s.jsx(k1,{status:o,t}),n==="log"&&a&&s.jsx(A1,{log:a,t}),n==="diff"&&s.jsx(u1,{diff:l,diffReport:h,activeFilePath:C,diffPath:f,onScopeToFile:()=>m(C),onClearScope:()=>m(null),t})]})}function w1(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 k1({status:e,t}){const n=p.useMemo(()=>{const r={modified:[],added:[],deleted:[],renamed:[],untracked:[]};for(const o of e.changes)r[v1(o.status)].push(o);for(const o of Rl)r[o].sort((i,a)=>i.path.localeCompare(a.path));return r},[e.changes]);return e.inRepo?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[s.jsx(C1,{status:e,t}),e.changes.length===0?s.jsx(j1,{t}):Rl.map(r=>{const o=n[r];return o.length===0?null:s.jsx(E1,{group:r,items:o,t},r)})]}):s.jsx(Yp,{t})}function C1({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(Nr,{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:ui(t.success,t),children:[s.jsx(cv,{size:11,strokeWidth:2})," ",n]}),r>0&&s.jsxs("span",{title:`${r} commit(s) behind upstream`,style:ui(t.warning,t),children:[s.jsx(ov,{size:11,strokeWidth:2})," ",r]}),n===0&&r===0&&s.jsx("span",{style:{...ui(t.textMuted,t),opacity:.7},children:"up to date"})]})}function j1({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(zv,{size:14,strokeWidth:1.75,color:e.success}),"Working tree clean"]})}function Yp({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 E1({group:e,items:t,t:n}){const r=x1[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((a,c)=>s.jsx(T1,{change:a,t:n,color:o,divider:c<t.length-1},a.path))})]})}function T1({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 A1({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(iS,{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(Yp,{t})}function di({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 ui(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 R1(e){const{state:t,dispatch:n}=et(),r=Qe[t.themeMode],[o,i]=p.useState([]),[a,c]=p.useState(!0),[l,u]=p.useState(""),[h,d]=p.useState(""),[f,m]=p.useState(new Set),S=()=>{c(!0),B.listApps().then(g=>i(g)).finally(()=>c(!1))};p.useEffect(()=>{S()},[]);const v=Ao(t.authoredDomains),b=Jn(t.authoredDomains),w=o.some(g=>{var I;return!v.has(((I=g.domain)==null?void 0:I.trim())??"")}),j=o.filter(g=>{var T;const I=l.toLowerCase();return!(I&&!g.name.toLowerCase().includes(I)&&!(g.description??"").toLowerCase().includes(I)||h==="uncategorized"&&v.has(((T=g.domain)==null?void 0:T.trim())??"")||h&&h!=="uncategorized"&&(!v.has(h)||g.domain!==h))}),C=g=>{m(I=>{const T=new Set(I);return T.has(g)?T.delete(g):T.add(g),T})},x=(g,I)=>{n({type:"OPEN_APP",appId:g.id,dashboardId:I})},E={background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.font,padding:"4px 6px",outline:"none"},P=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"}),A=s.jsxs(pp,{children:[s.jsx("input",{value:l,onChange:g=>u(g.target.value),placeholder:"Search apps...",style:{...E,flex:1,minWidth:100}}),s.jsxs("select",{value:h,onChange:g=>d(g.target.value),style:E,children:[s.jsx("option",{value:"",children:"All domains"}),b.map(g=>s.jsx("option",{value:g.value,children:g.label},g.value)),w?s.jsx("option",{value:"uncategorized",children:"Unassigned"}):null]})]});return s.jsx(Ta,{title:"Apps",status:s.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:j.length}),actions:P,toolbar:A,bodyPadding:0,children:a?s.jsx(no,{title:"Loading apps…"}):j.length===0?o.length===0?s.jsx(no,{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(no,{title:"No matches",description:"No apps match your filters."}):j.map(g=>{const I=f.has(g.id);return s.jsxs("div",{style:{borderBottom:`1px solid ${r.cellBorder}`},children:[s.jsxs("button",{onClick:()=>C(g.id),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:T=>{T.currentTarget.style.background=`${r.accent}0a`},onMouseLeave:T=>{T.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:I?"▾":"▸"}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:r.textPrimary,fontFamily:r.font},children:g.name}),s.jsx(up,{tone:"accent",children:g.domain})]}),g.description&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,lineHeight:1.3,marginBottom:4,marginLeft:16},children:g.description}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:r.textMuted,fontFamily:r.font,marginLeft:16},children:[g.owners[0]&&s.jsxs("span",{children:["by ",g.owners[0]]}),s.jsxs("span",{children:[g.dashboards.length," dashboard",g.dashboards.length===1?"":"s"]}),s.jsxs("span",{children:[g.members," member",g.members===1?"":"s"]})]})]}),I&&s.jsxs("div",{style:{padding:"4px 0 10px 28px",background:`${r.accent}04`},children:[g.dashboards.length===0&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 0"},children:"(empty app scaffold)"}),g.dashboards.map(T=>s.jsx("button",{onClick:()=>x(g,T.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:T.title},T.id))]})]},g.id)})})}const O1={files:"Build",block_library:"Build",lineage:"Lineage",connection:"Connection",git:"Git",apps:"Apps"};function _1({onOpenFile:e}){const t=Ge(Lr(w=>({schemaTables:w.schemaTables,semanticLayer:w.semanticLayer,sidebarPanel:w.sidebarPanel,themeMode:w.themeMode}))),n=jn(),r=Qe[t.themeMode],[o,i]=p.useState(!1),[a,c]=p.useState(340),[l,u]=p.useState(!1),[h,d]=p.useState(""),f=p.useRef(a),m=t.sidebarPanel,S=m==="files"||m==="block_library",v=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"}`;p.useEffect(()=>{if(!S)return;let w=!0;return n({type:"SET_SEMANTIC_LOADING",loading:!0}),B.getSemanticLayer().then(j=>{w&&n({type:"SET_SEMANTIC_LAYER",layer:j})}).catch(()=>{}).finally(()=>{w&&n({type:"SET_SEMANTIC_LOADING",loading:!1})}),()=>{w=!1}},[S,n]);const b=w=>{w.preventDefault();const j=w.clientX,C=f.current;u(!0);const x=P=>{const A=Math.min(560,Math.max(180,C+(P.clientX-j)));f.current=A,c(A)},E=()=>{u(!1),window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",E)};window.addEventListener("mousemove",x),window.addEventListener("mouseup",E)};return s.jsxs("div",{style:{width:a,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:O1[m??""]??""}),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(ik,{defaultTab:m==="block_library"?"blocks":"notebooks",tabs:["notebooks","semantic","database","blocks"],onOpenFile:e,blockDomain:h,onBlockDomainChange:d,onNewBlock:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),onCollapse:()=>n({type:"TOGGLE_SIDEBAR"}),footer:v,footerStatus:t.semanticLayer.loading?"loading":"ready"}),m==="lineage"&&s.jsx(d1,{}),m==="connection"&&s.jsx(Qp,{}),m==="git"&&s.jsx(S1,{}),m==="apps"&&s.jsx(R1,{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:l?r.accent:"transparent",zIndex:10,transition:l?"none":"background 0.15s"},onMouseEnter:w=>{l||(w.currentTarget.style.background=`${r.accent}40`)},onMouseLeave:w=>{l||(w.currentTarget.style.background="transparent")}})]})}const Xp=2;function P1(e,t={}){const n=t.version??Xp,r=JSON.parse(e),{dqlnbVersion:o,...i}=r,a={dqlnbVersion:n,...i};return JSON.stringify(a,I1(),2)+`
473
- `}function I1(){return function(t,n){if(n===null||typeof n!="object"||Array.isArray(n))return n;const r=n,o=Object.keys(r);o.sort((a,c)=>{const l=Ol[a],u=Ol[c];return l!==void 0&&u!==void 0?l-u:l!==void 0?-1:u!==void 0?1:a<c?-1:a>c?1:0});const i={};for(const a of o)i[a]=r[a];return i}}const Ol={dqlnbVersion:0,version:1,title:2,metadata:3,cells:4,id:10,type:11,name:12,content:13};function D1(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 a=i[1],c=i[2].trim();r.push({id:vt(),type:"markdown",content:`# ${a}`,status:"idle"}),c&&r.push({id:vt(),type:"dql",name:a.toLowerCase().replace(/\s+/g,"_"),content:c,status:"idle"})}return r.length===0&&r.push({id:vt(),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:vt(),type:"dql",content:e.trim(),status:"idle"}]}}}const $1=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 M1(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",o=Bi((n.cells||[]).map(c=>{const l=Object.fromEntries(Object.entries(c).filter(([u])=>!$1.has(u)));return{id:c.id||vt(),type:c.type||"sql",content:c.content??c.source??"",name:c.name||c.title,status:"idle",...c.paramConfig?{paramConfig:c.paramConfig}:{},...c.paramValue!==void 0?{paramValue:c.paramValue}:{},...c.chartConfig?{chartConfig:c.chartConfig}:{},...c.filterConfig?{filterConfig:c.filterConfig}:{},...c.pivotConfig?{pivotConfig:c.pivotConfig}:{},...c.singleValueConfig?{singleValueConfig:c.singleValueConfig}:{},...c.tableConfig?{tableConfig:c.tableConfig}:{},...c.chatConfig?{chatConfig:c.chatConfig}:{},...c.upstream?{upstream:c.upstream}:{},...c.blockBinding?{blockBinding:c.blockBinding}:{},...c.dqlParameterValues?{dqlParameterValues:c.dqlParameterValues}:{},...c.dqlArtifact?{dqlArtifact:c.dqlArtifact}:{},...c.correctionProvenance?{correctionProvenance:c.correctionProvenance}:{},...c.executionTarget?{executionTarget:c.executionTarget}:{},...c.datasetRefs?{datasetRefs:c.datasetRefs}:{},...c.dependencies?{dependencies:c.dependencies}:{},...c.annotations?{annotations:c.annotations}:{},...c.mixedSourcePlan?{mixedSourcePlan:c.mixedSourcePlan}:{},...c.kernel?{kernel:c.kernel}:{},...Object.keys(l).length>0?{preservedFields:l}:{}}})),{title:i,...a}=n.metadata??{};return{title:r,cells:o,metadata:a}}catch(n){return console.warn("parse-workbook: falling back after error",n),{title:"Untitled",cells:[{id:vt(),type:"sql",content:e,status:"idle"}]}}}function L1(e,t,n){const r={dqlnbVersion:Xp,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 P1(JSON.stringify(r))}function N1(e,t){return e.endsWith(".dql")?D1(t):M1(t)}const Zp=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function Jj(e){const t=new Set;for(const n of e.matchAll(Zp))t.add(n[1]);return[...t]}function B1(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(a=>`(${n.map(l=>{const u=a[l];return u==null?"NULL":typeof u=="number"?String(u):typeof u=="boolean"?u?"TRUE":"FALSE":`'${String(u).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
471
+ `;function jl({t:e,editName:t,setEditName:n,editDriver:r,setEditDriver:o,editFields:i,setEditFields:a,onSave:c,onCancel:l,onDelete:u,saving:h,isNew:d}){const f=Na[r],m=(f==null?void 0:f.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%"},v={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:d?"New Connection":"Edit Connection"}),s.jsxs("div",{style:{marginBottom:6},children:[s.jsx("div",{style:v,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:v,children:"Driver"}),s.jsx("select",{style:{...S,fontFamily:e.font},value:r,onChange:b=>{o(b.target.value),a({})},children:$s.map(b=>s.jsx("option",{value:b.driver,children:b.label},b.driver))})]}),m.map(b=>s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("div",{style:v,children:[b.label,b.required?" *":""]}),b.type==="select"?s.jsxs("select",{style:{...S,fontFamily:e.font},value:i[b.key]??"",onChange:w=>a({...i,[b.key]:w.target.value}),children:[s.jsx("option",{value:"",children:"Default"}),(b.options??[]).map(w=>s.jsx("option",{value:w.value,children:w.label},w.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:w=>a({...i,[b.key]:w.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:w=>a({...i,[b.key]:w.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:w=>a({...i,[b.key]:w.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:c,disabled:h,style:{flex:1,padding:"5px 0",borderRadius:5,border:"none",background:e.accent,color:"#fff",fontSize:11,fontFamily:e.font,fontWeight:600,cursor:h?"not-allowed":"pointer",opacity:h?.6:1},children:h?"Saving…":"Save"}),s.jsx("button",{onClick:l,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"}),u&&!d&&s.jsx("button",{onClick:u,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 o1(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 El=new Set(["filepath","httpPath","accessUrl"]);function s1({t:e,driver:t,fields:n,onDriverChange:r,onFieldsChange:o,onSave:i,saving:a,saveMessage:c,connectorStatus:l,installing:u,onInstall:h}){const[d,f]=p.useState(!1),m=Na[t],S=(m==null?void 0:m.fields)??[],v=o1(t,n),b=new Set(v),w=S.filter(x=>b.has(x.key)),j=S.filter(x=>!b.has(x.key)),C=(x,E)=>o({...n,[x]:E});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:x=>r(x.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:$s.map(({driver:x,label:E})=>s.jsx("option",{value:x,children:E},x))})]}),s.jsx(i1,{t:e,driver:t,label:(m==null?void 0:m.label)??t,status:l,installing:u,onInstall:h}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:w.map(x=>s.jsx(Tl,{t:e,field:x,value:n[x.key]??"",onChange:E=>C(x.key,E),fullWidth:El.has(x.key)},x.key))}),j.length>0&&s.jsxs("details",{open:d,onToggle:x=>f(x.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:d?"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:[j.length," more"]})]}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginTop:12},children:j.map(x=>s.jsx(Tl,{t:e,field:x,value:n[x.key]??"",onChange:E=>C(x.key,E),fullWidth:El.has(x.key)||x.type==="textarea"},x.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:c??"Changes apply after a successful test."}),s.jsx("button",{type:"button",onClick:i,disabled:a,style:{height:30,padding:"0 15px",borderRadius:8,border:"none",background:e.accent,color:"#fff",fontSize:12,fontWeight:650,cursor:a?"not-allowed":"pointer",fontFamily:e.font,boxShadow:"0 1px 4px rgba(107,93,211,0.25)",opacity:a?.7:1},children:a?"Saving…":"Save connection"})]})]})}function i1({t:e,driver:t,label:n,status:r,installing:o,onInstall:i}){const a=(r==null?void 0:r.builtIn)??!0,c=(r==null?void 0:r.installed)??!0,l=!c&&!a,u=o||l?e.warning:e.success,h=o||l?"var(--status-warning-bg)":"var(--status-success-bg)",d=o||l?"var(--status-warning-border)":"var(--status-success-border)",f=o?"Installing connector package…":a?"Built in — no installation needed":c?"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 ${d}`,borderRadius:9,background:h,padding:"10px 12px"},children:[s.jsx(Yr,{driver:t,size:18,fallbackColor:ns[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:u,fontFamily:e.font,marginTop:1},children:f})]}),l||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:u,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"})}),a?"Ready":"Installed"]})]})}function Tl({t:e,field:t,value:n,onChange:r,fullWidth:o}){const[i,a]=p.useState(!1),l={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"},u={display:"flex",flexDirection:"column",gap:4,gridColumn:o?"1 / -1":void 0},h=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:{...u,flexDirection:"row",alignItems:"center",gap:8},children:[s.jsx("input",{type:"checkbox",checked:n==="true",onChange:d=>r(d.target.checked?"true":"false")}),h]}):s.jsxs("label",{style:u,children:[h,t.type==="select"?s.jsxs("select",{value:n,onChange:d=>r(d.target.value),onFocus:()=>a(!0),onBlur:()=>a(!1),style:{...l,fontFamily:e.font,fontSize:12.5,padding:"8px 9px"},children:[s.jsx("option",{value:"",children:"Default"}),(t.options??[]).map(d=>s.jsx("option",{value:d.value,children:d.label},d.value))]}):t.type==="textarea"?s.jsx("textarea",{value:n,placeholder:t.placeholder??"",onChange:d=>r(d.target.value),onFocus:()=>a(!0),onBlur:()=>a(!1),style:{...l,minHeight:72,resize:"vertical"}}):s.jsx("input",{type:t.type==="password"?"password":t.type==="number"?"number":"text",value:n,placeholder:t.placeholder??"",onChange:d=>r(d.target.value),onFocus:()=>a(!0),onBlur:()=>a(!1),style:l}),t.helpText&&s.jsx("span",{style:{fontSize:10,color:e.textMuted,fontFamily:e.font,lineHeight:1.35},children:t.helpText})]})}const a1=Object.freeze(Object.defineProperty({__proto__:null,ConnectionPanel:Jp},Symbol.toStringTag,{value:"Module"}));function c1({type:e}){const t=Aw[e]??"#8b949e";return s.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:Rp[e]??e,children:Rw[e]??e.slice(0,4).toUpperCase()})}function l1({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 Yp({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(c1,{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 d1=30,ai=200;function ut(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 ci({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 ot({title:e,nodes:t,t:n,onSelect:r,secondaryFor:o}){const i=t.length>d1,[a,c]=p.useState(!i),[l,u]=p.useState(ai);if(t.length===0)return null;const h=a?Math.min(l,t.length):0,d=Math.max(0,t.length-h);return s.jsxs("div",{style:{padding:"8px 0",borderTop:`1px solid ${n.headerBorder}`},children:[s.jsxs("button",{onClick:()=>c(f=>!f),"aria-expanded":a,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:a?"▾":"▸"}),s.jsx("span",{children:e}),s.jsx("span",{style:{marginLeft:"auto",fontWeight:500},children:t.length})]}),a&&t.slice(0,h).map(f=>s.jsx(Yp,{node:f,t:n,onClick:()=>r(f),secondary:o==null?void 0:o(f)},f.id)),a&&d>0&&s.jsxs("button",{onClick:()=>u(f=>f+ai),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(ai,d)," more (",d," hidden)"]})]})}function u1({variant:e="sidebar"}){const{state:t,dispatch:n}=et(),r=Qe[t.themeMode],o=e==="page",[i,a]=p.useState(()=>typeof window<"u"?window.innerWidth<700:!1),[c,l]=p.useState(!0),[u,h]=p.useState([]),[d,f]=p.useState([]),[m,S]=p.useState(""),[v,b]=p.useState([]),w=p.useCallback(async()=>{l(!0);const g=await B.fetchLineage();h(g.nodes??[]),f(g.edges??[]),l(!1)},[]);p.useEffect(()=>{w()},[w]),p.useEffect(()=>{if(!o)return;const g=()=>a(window.innerWidth<700);return g(),window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[o]),p.useEffect(()=>{let g=!1;if(m.trim().length<2){b([]);return}return B.searchLineage(m.trim()).then(I=>{g||b(I.matches??[])}),()=>{g=!0}},[m]);const j=p.useCallback(g=>{n({type:"OPEN_LINEAGE_DETAIL",nodeId:g.id})},[n]),[C,x]=p.useState("type"),E=p.useMemo(()=>({terms:u.filter(g=>g.type==="term"),businessViews:u.filter(g=>g.type==="business_view"),dashboards:u.filter(g=>g.type==="dashboard"),notebooks:u.filter(g=>g.type==="notebook"),apps:u.filter(g=>g.type==="app"),charts:u.filter(g=>g.type==="chart"),blocks:u.filter(g=>g.type==="block"),metrics:u.filter(g=>g.type==="metric"),dimensions:u.filter(g=>g.type==="dimension"),dbtModels:u.filter(g=>g.type==="dbt_model"),dbtSources:u.filter(g=>g.type==="dbt_source"),tables:u.filter(g=>g.type==="source_table"),domains:u.filter(g=>g.type==="domain")}),[u]),P=p.useMemo(()=>({businessNodes:E.terms.length+E.businessViews.length,businessEdges:d.filter(g=>g.type==="defines"||g.type==="composes").length,technicalNodes:E.tables.length+E.dbtSources.length+E.dbtModels.length+E.metrics.length+E.dimensions.length+E.blocks.length,consumptionNodes:E.charts.length+E.notebooks.length+E.dashboards.length+E.apps.length}),[d,E]),A=p.useMemo(()=>{const g={source:[],transform:[],answer:[],consumption:[]};for(const I of u){const T=Pw(I);g[T].push(I)}return g},[u]);return c?s.jsx("div",{style:{padding:16,color:r.textMuted,fontSize:12},children:"Loading lineage..."}):u.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(no,{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(l1,{value:m,onChange:S,placeholder:"Search lineage...",t:r})}),s.jsxs("div",{style:{flex:1,overflow:"auto"},children:[m.trim().length>=2&&v.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"}),v.slice(0,8).map(g=>s.jsx(Yp,{node:g.node,t:r,onClick:()=>j(g.node),secondary:g.node.domain},g.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(ci,{Icon:yv,label:"Business",value:P.businessNodes,detail:`${E.terms.length} terms · ${E.businessViews.length} views · ${P.businessEdges} edges`,t:r}),s.jsx(ci,{Icon:To,label:"Technical",value:P.technicalNodes,detail:`${E.tables.length} tables · ${E.dbtModels.length+E.dbtSources.length} dbt · ${E.blocks.length} blocks`,t:r}),s.jsx(ci,{Icon:yS,label:"Consumption",value:P.consumptionNodes,detail:`${E.dashboards.length} dashboards · ${E.notebooks.length} notebooks · ${E.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:[el.map(g=>{const I=A[g].length;return I===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:Ow[g],display:"inline-block"}}),Zc[g],": ",I]},g)}),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:()=>x("type"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",background:C==="type"?`${r.headerBorder}`:"transparent",color:C==="type"?r.textPrimary:r.textMuted},children:"Type"}),s.jsx("button",{onClick:()=>x("layer"),style:{padding:"2px 6px",fontSize:9,fontWeight:700,border:"none",cursor:"pointer",borderLeft:`1px solid ${r.headerBorder}`,background:C==="layer"?`${r.headerBorder}`:"transparent",color:C==="layer"?r.textPrimary:r.textMuted},children:"Layer"})]})]}),C==="type"?s.jsxs(s.Fragment,{children:[s.jsx(ot,{title:"Business Terms",nodes:E.terms,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Business Views",nodes:E.businessViews,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"DQL Blocks",nodes:E.blocks,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Metrics",nodes:E.metrics,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Dimensions",nodes:E.dimensions,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Dashboards",nodes:E.dashboards,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Notebooks",nodes:E.notebooks,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Apps",nodes:E.apps,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Charts",nodes:E.charts,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"dbt Models",nodes:E.dbtModels,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"dbt Sources",nodes:E.dbtSources,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Source Tables",nodes:E.tables,t:r,onSelect:j,secondaryFor:ut}),s.jsx(ot,{title:"Business Domains",nodes:E.domains,t:r,onSelect:j,secondaryFor:ut})]}):s.jsx(s.Fragment,{children:el.map(g=>s.jsx(ot,{title:Zc[g],nodes:A[g],t:r,onSelect:j},g))})]})]})}function p1({diff:e,diffReport:t,activeFilePath:n,diffPath:r,onScopeToFile:o,onClearScope:i,t:a}){const c=t!==null&&!t.identical,l=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:Rl(r==null,a),children:"All"}),n&&s.jsx("button",{onClick:o,style:Rl(r===n,a),children:"Active file"}),r&&s.jsx("span",{style:{color:a.textMuted,fontSize:10,alignSelf:"center",fontFamily:a.fontMono},children:r})]}),c&&s.jsx(f1,{report:t,t:a}),!c&&l&&s.jsx(g1,{diff:e,t:a}),!c&&!l&&s.jsx("div",{style:{color:a.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function f1({report:e,t}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>s.jsx(h1,{change:n,t},r))})}function h1({change:e,t}){const{marker:n,color:r,label:o}=y1(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((a,c)=>s.jsx(m1,{field:a,t},c))})]})}function m1({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:Al(e.before)}),s.jsx("span",{style:{color:t.textMuted},children:" → "}),s.jsx("span",{style:{color:t.success},children:Al(e.after)})]})}function g1({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(`
472
+ `).map((n,r)=>s.jsx("div",{style:{color:b1(n,t)},children:n||" "},r))})}function y1(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 ${li(e.id,e.name)} [${e.cellType}]`};case"cell-removed":return{...n,label:`cell ${li(e.id,e.name)} [${e.cellType}]`};case"cell-changed":return{...r,label:`cell ${li(e.id,e.name)}`};case"notebook-changed":return{...r,label:"notebook"}}}function li(e,t){return t?`"${t}" (${e.slice(0,8)})`:e.slice(0,8)}function Al(e,t=60){if(e==null)return"∅";const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}function Rl(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 b1(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const x1=2e3,v1={modified:{label:"Modified",color:e=>e.warning,Icon:Wv},added:{label:"Added",color:e=>e.success,Icon:yp},deleted:{label:"Deleted",color:e=>e.error,Icon:Jv},renamed:{label:"Renamed",color:e=>e.accent,Icon:av},untracked:{label:"Untracked",color:e=>e.textMuted,Icon:Hv}},Ol=["modified","added","renamed","deleted","untracked"];function S1(e){const t=e.trim();return t==="??"?"untracked":t.startsWith("R")?"renamed":t.includes("D")?"deleted":t.includes("A")?"added":"modified"}function w1(){var P;const{state:e}=et(),t=Qe[e.themeMode],[n,r]=p.useState("status"),[o,i]=p.useState(null),[a,c]=p.useState(null),[l,u]=p.useState(""),[h,d]=p.useState(null),[f,m]=p.useState(null),[S,v]=p.useState(!1),[b,w]=p.useState(!1),j=p.useCallback(async()=>{v(!0),w(!0);try{if(n==="status")i(await B.fetchGitStatus());else if(n==="log")c(await B.fetchGitLog(30));else{const A=await B.fetchGitDiff(f??void 0);u(A.diff),d(A.diffReport)}}finally{v(!1),window.setTimeout(()=>w(!1),400)}},[n,f]);p.useEffect(()=>{j()},[j]),p.useEffect(()=>{if(n!=="status")return;const A=window.setInterval(()=>{B.fetchGitStatus().then(g=>{i(I=>k1(I,g)?I:g)})},x1);return()=>window.clearInterval(A)},[n]);const C=((P=e.activeFile)==null?void 0:P.path)??null,x=s.jsxs("button",{onClick:()=>void j(),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(ps,{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); } }"})]}),E=s.jsxs(fp,{children:[s.jsx(di,{t,active:n==="status",onClick:()=>r("status"),children:"Status"}),s.jsx(di,{t,active:n==="log",onClick:()=>r("log"),children:"History"}),s.jsx(di,{t,active:n==="diff",onClick:()=>r("diff"),children:"Diff"})]});return s.jsxs(Ta,{title:"Git",actions:x,toolbar:E,bodyPadding:12,children:[S&&!o&&!a&&s.jsx(no,{title:"Loading…"}),n==="status"&&o&&s.jsx(C1,{status:o,t}),n==="log"&&a&&s.jsx(R1,{log:a,t}),n==="diff"&&s.jsx(p1,{diff:l,diffReport:h,activeFilePath:C,diffPath:f,onScopeToFile:()=>m(C),onClearScope:()=>m(null),t})]})}function k1(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 C1({status:e,t}){const n=p.useMemo(()=>{const r={modified:[],added:[],deleted:[],renamed:[],untracked:[]};for(const o of e.changes)r[S1(o.status)].push(o);for(const o of Ol)r[o].sort((i,a)=>i.path.localeCompare(a.path));return r},[e.changes]);return e.inRepo?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[s.jsx(j1,{status:e,t}),e.changes.length===0?s.jsx(E1,{t}):Ol.map(r=>{const o=n[r];return o.length===0?null:s.jsx(T1,{group:r,items:o,t},r)})]}):s.jsx(Xp,{t})}function j1({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(Nr,{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:ui(t.success,t),children:[s.jsx(lv,{size:11,strokeWidth:2})," ",n]}),r>0&&s.jsxs("span",{title:`${r} commit(s) behind upstream`,style:ui(t.warning,t),children:[s.jsx(sv,{size:11,strokeWidth:2})," ",r]}),n===0&&r===0&&s.jsx("span",{style:{...ui(t.textMuted,t),opacity:.7},children:"up to date"})]})}function E1({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(qv,{size:14,strokeWidth:1.75,color:e.success}),"Working tree clean"]})}function Xp({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 T1({group:e,items:t,t:n}){const r=v1[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((a,c)=>s.jsx(A1,{change:a,t:n,color:o,divider:c<t.length-1},a.path))})]})}function A1({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 R1({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(aS,{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(Xp,{t})}function di({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 ui(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 O1(e){const{state:t,dispatch:n}=et(),r=Qe[t.themeMode],[o,i]=p.useState([]),[a,c]=p.useState(!0),[l,u]=p.useState(""),[h,d]=p.useState(""),[f,m]=p.useState(new Set),S=()=>{c(!0),B.listApps().then(g=>i(g)).finally(()=>c(!1))};p.useEffect(()=>{S()},[]);const v=Ao(t.authoredDomains),b=Jn(t.authoredDomains),w=o.some(g=>{var I;return!v.has(((I=g.domain)==null?void 0:I.trim())??"")}),j=o.filter(g=>{var T;const I=l.toLowerCase();return!(I&&!g.name.toLowerCase().includes(I)&&!(g.description??"").toLowerCase().includes(I)||h==="uncategorized"&&v.has(((T=g.domain)==null?void 0:T.trim())??"")||h&&h!=="uncategorized"&&(!v.has(h)||g.domain!==h))}),C=g=>{m(I=>{const T=new Set(I);return T.has(g)?T.delete(g):T.add(g),T})},x=(g,I)=>{n({type:"OPEN_APP",appId:g.id,dashboardId:I})},E={background:r.inputBg,border:`1px solid ${r.inputBorder}`,borderRadius:4,color:r.textPrimary,fontSize:11,fontFamily:r.font,padding:"4px 6px",outline:"none"},P=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"}),A=s.jsxs(fp,{children:[s.jsx("input",{value:l,onChange:g=>u(g.target.value),placeholder:"Search apps...",style:{...E,flex:1,minWidth:100}}),s.jsxs("select",{value:h,onChange:g=>d(g.target.value),style:E,children:[s.jsx("option",{value:"",children:"All domains"}),b.map(g=>s.jsx("option",{value:g.value,children:g.label},g.value)),w?s.jsx("option",{value:"uncategorized",children:"Unassigned"}):null]})]});return s.jsx(Ta,{title:"Apps",status:s.jsx("span",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font},children:j.length}),actions:P,toolbar:A,bodyPadding:0,children:a?s.jsx(no,{title:"Loading apps…"}):j.length===0?o.length===0?s.jsx(no,{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(no,{title:"No matches",description:"No apps match your filters."}):j.map(g=>{const I=f.has(g.id);return s.jsxs("div",{style:{borderBottom:`1px solid ${r.cellBorder}`},children:[s.jsxs("button",{onClick:()=>C(g.id),style:{display:"block",width:"100%",textAlign:"left",background:"transparent",border:"none",cursor:"pointer",padding:"10px 12px",transition:"background 0.1s"},onMouseEnter:T=>{T.currentTarget.style.background=`${r.accent}0a`},onMouseLeave:T=>{T.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:I?"▾":"▸"}),s.jsx("span",{style:{fontSize:12,fontWeight:600,color:r.textPrimary,fontFamily:r.font},children:g.name}),s.jsx(pp,{tone:"accent",children:g.domain})]}),g.description&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,lineHeight:1.3,marginBottom:4,marginLeft:16},children:g.description}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:r.textMuted,fontFamily:r.font,marginLeft:16},children:[g.owners[0]&&s.jsxs("span",{children:["by ",g.owners[0]]}),s.jsxs("span",{children:[g.dashboards.length," dashboard",g.dashboards.length===1?"":"s"]}),s.jsxs("span",{children:[g.members," member",g.members===1?"":"s"]})]})]}),I&&s.jsxs("div",{style:{padding:"4px 0 10px 28px",background:`${r.accent}04`},children:[g.dashboards.length===0&&s.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,padding:"4px 0"},children:"(empty app scaffold)"}),g.dashboards.map(T=>s.jsx("button",{onClick:()=>x(g,T.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:T.title},T.id))]})]},g.id)})})}const _1={files:"Build",block_library:"Build",lineage:"Lineage",connection:"Connection",git:"Git",apps:"Apps"};function P1({onOpenFile:e}){const t=Ge(Lr(w=>({schemaTables:w.schemaTables,semanticLayer:w.semanticLayer,sidebarPanel:w.sidebarPanel,themeMode:w.themeMode}))),n=jn(),r=Qe[t.themeMode],[o,i]=p.useState(!1),[a,c]=p.useState(340),[l,u]=p.useState(!1),[h,d]=p.useState(""),f=p.useRef(a),m=t.sidebarPanel,S=m==="files"||m==="block_library",v=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"}`;p.useEffect(()=>{if(!S)return;let w=!0;return n({type:"SET_SEMANTIC_LOADING",loading:!0}),B.getSemanticLayer().then(j=>{w&&n({type:"SET_SEMANTIC_LAYER",layer:j})}).catch(()=>{}).finally(()=>{w&&n({type:"SET_SEMANTIC_LOADING",loading:!1})}),()=>{w=!1}},[S,n]);const b=w=>{w.preventDefault();const j=w.clientX,C=f.current;u(!0);const x=P=>{const A=Math.min(560,Math.max(180,C+(P.clientX-j)));f.current=A,c(A)},E=()=>{u(!1),window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",E)};window.addEventListener("mousemove",x),window.addEventListener("mouseup",E)};return s.jsxs("div",{style:{width:a,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:_1[m??""]??""}),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(ak,{defaultTab:m==="block_library"?"blocks":"notebooks",tabs:["notebooks","semantic","database","blocks"],onOpenFile:e,blockDomain:h,onBlockDomainChange:d,onNewBlock:()=>n({type:"OPEN_NEW_BLOCK_MODAL"}),onCollapse:()=>n({type:"TOGGLE_SIDEBAR"}),footer:v,footerStatus:t.semanticLayer.loading?"loading":"ready"}),m==="lineage"&&s.jsx(u1,{}),m==="connection"&&s.jsx(Jp,{}),m==="git"&&s.jsx(w1,{}),m==="apps"&&s.jsx(O1,{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:l?r.accent:"transparent",zIndex:10,transition:l?"none":"background 0.15s"},onMouseEnter:w=>{l||(w.currentTarget.style.background=`${r.accent}40`)},onMouseLeave:w=>{l||(w.currentTarget.style.background="transparent")}})]})}const Zp=2;function I1(e,t={}){const n=t.version??Zp,r=JSON.parse(e),{dqlnbVersion:o,...i}=r,a={dqlnbVersion:n,...i};return JSON.stringify(a,D1(),2)+`
473
+ `}function D1(){return function(t,n){if(n===null||typeof n!="object"||Array.isArray(n))return n;const r=n,o=Object.keys(r);o.sort((a,c)=>{const l=_l[a],u=_l[c];return l!==void 0&&u!==void 0?l-u:l!==void 0?-1:u!==void 0?1:a<c?-1:a>c?1:0});const i={};for(const a of o)i[a]=r[a];return i}}const _l={dqlnbVersion:0,version:1,title:2,metadata:3,cells:4,id:10,type:11,name:12,content:13};function $1(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 a=i[1],c=i[2].trim();r.push({id:vt(),type:"markdown",content:`# ${a}`,status:"idle"}),c&&r.push({id:vt(),type:"dql",name:a.toLowerCase().replace(/\s+/g,"_"),content:c,status:"idle"})}return r.length===0&&r.push({id:vt(),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:vt(),type:"dql",content:e.trim(),status:"idle"}]}}}const M1=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 L1(e){var t;try{const n=JSON.parse(e),r=n.title||((t=n.metadata)==null?void 0:t.title)||"Untitled",o=Bi((n.cells||[]).map(c=>{const l=Object.fromEntries(Object.entries(c).filter(([u])=>!M1.has(u)));return{id:c.id||vt(),type:c.type||"sql",content:c.content??c.source??"",name:c.name||c.title,status:"idle",...c.paramConfig?{paramConfig:c.paramConfig}:{},...c.paramValue!==void 0?{paramValue:c.paramValue}:{},...c.chartConfig?{chartConfig:c.chartConfig}:{},...c.filterConfig?{filterConfig:c.filterConfig}:{},...c.pivotConfig?{pivotConfig:c.pivotConfig}:{},...c.singleValueConfig?{singleValueConfig:c.singleValueConfig}:{},...c.tableConfig?{tableConfig:c.tableConfig}:{},...c.chatConfig?{chatConfig:c.chatConfig}:{},...c.upstream?{upstream:c.upstream}:{},...c.blockBinding?{blockBinding:c.blockBinding}:{},...c.dqlParameterValues?{dqlParameterValues:c.dqlParameterValues}:{},...c.dqlArtifact?{dqlArtifact:c.dqlArtifact}:{},...c.correctionProvenance?{correctionProvenance:c.correctionProvenance}:{},...c.executionTarget?{executionTarget:c.executionTarget}:{},...c.datasetRefs?{datasetRefs:c.datasetRefs}:{},...c.dependencies?{dependencies:c.dependencies}:{},...c.annotations?{annotations:c.annotations}:{},...c.mixedSourcePlan?{mixedSourcePlan:c.mixedSourcePlan}:{},...c.kernel?{kernel:c.kernel}:{},...Object.keys(l).length>0?{preservedFields:l}:{}}})),{title:i,...a}=n.metadata??{};return{title:r,cells:o,metadata:a}}catch(n){return console.warn("parse-workbook: falling back after error",n),{title:"Untitled",cells:[{id:vt(),type:"sql",content:e,status:"idle"}]}}}function N1(e,t,n){const r={dqlnbVersion:Zp,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 I1(JSON.stringify(r))}function B1(e,t){return e.endsWith(".dql")?$1(t):L1(t)}const ef=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function Yj(e){const t=new Set;for(const n of e.matchAll(ef))t.add(n[1]);return[...t]}function F1(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(a=>`(${n.map(l=>{const u=a[l];return u==null?"NULL":typeof u=="number"?String(u):typeof u=="boolean"?u?"TRUE":"FALSE":`'${String(u).replace(/'/g,"''")}'`}).join(", ")})`).join(`,
474
474
  `),i=n.map(a=>`"${a.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
475
475
  SELECT * FROM (VALUES
476
476
  ${o}
477
477
  ) AS _t(${i})
478
- )`}function F1(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function z1(e,t){var u;const n=[...e.matchAll(Zp)];if(n.length===0)return{sql:e,substituted:[],unresolved:[],ambiguous:[]};const r=new Map;for(const h of t){const d=[h.id,(u=h.name)==null?void 0:u.trim()].filter(f=>!!f);for(const f of d)r.set(f,[...r.get(f)??[],h])}const o=[],i=[],a=[],c=[];let l=e;for(const h of n){const d=h[1],f=r.get(d)??[];if(f.length===0){i.push(d);continue}if(f.length>1){a.push(d);continue}const m=f[0];if(m.type==="param"){const S=m.paramConfig,v=m.paramValue??(S==null?void 0:S.defaultValue)??"",b=(S==null?void 0:S.paramType)??"text";l=l.replace(h[0],F1(v,b)),o.push(d);continue}if(!m.result||m.error||m.stale){i.push(d);continue}c.push(B1(d,m.result)),l=l.replace(h[0],`"${d}"`),o.push(d)}if(c.length>0){const h=l.trimStart();/^WITH\s+/i.test(h)?l=l.replace(/^(\s*WITH\s+)/i,`$1${c.join(`,
478
+ )`}function z1(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function q1(e,t){var u;const n=[...e.matchAll(ef)];if(n.length===0)return{sql:e,substituted:[],unresolved:[],ambiguous:[]};const r=new Map;for(const h of t){const d=[h.id,(u=h.name)==null?void 0:u.trim()].filter(f=>!!f);for(const f of d)r.set(f,[...r.get(f)??[],h])}const o=[],i=[],a=[],c=[];let l=e;for(const h of n){const d=h[1],f=r.get(d)??[];if(f.length===0){i.push(d);continue}if(f.length>1){a.push(d);continue}const m=f[0];if(m.type==="param"){const S=m.paramConfig,v=m.paramValue??(S==null?void 0:S.defaultValue)??"",b=(S==null?void 0:S.paramType)??"text";l=l.replace(h[0],z1(v,b)),o.push(d);continue}if(!m.result||m.error||m.stale){i.push(d);continue}c.push(F1(d,m.result)),l=l.replace(h[0],`"${d}"`),o.push(d)}if(c.length>0){const h=l.trimStart();/^WITH\s+/i.test(h)?l=l.replace(/^(\s*WITH\s+)/i,`$1${c.join(`,
479
479
  `)},
480
480
  `):l=`WITH ${c.join(`,
481
481
  `)}
482
- ${l}`}return{sql:l,substituted:Array.from(new Set(o)),unresolved:Array.from(new Set(i)),ambiguous:Array.from(new Set(a))}}function Yj(e){if(!/^\s*block\s+"[^"]+"\s*\{/i.test(e))return!1;let t=0,n=!1,r=!1,o=!1,i=!1;for(let a=0;a<e.length;a+=1){if(e.slice(a,a+3)==='"""'&&!i){o=!o,a+=2,r=!1;continue}if(o)continue;const c=e[a];if(c==='"'&&!i&&(r=!r),!r){if(c==="{")t+=1,n=!0;else if(c==="}"&&(t-=1,t<0))return!1}i=c==="\\"&&!i,c!=="\\"&&(i=!1)}return n&&t===0&&!r&&!o}function ef(e){const t=i=>{var a;return((a=e.match(new RegExp(`\\b${i}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:a[1])??""},n=i=>{const a=e.match(new RegExp(`\\b${i}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i"));return((a==null?void 0:a[1].match(/"([^"]*)"/g))??[]).map(c=>c.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 Xj(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 Fa(n,` metrics = [${r.map(o=>`"${Sn(o)}"`).join(", ")}]`)}function tf(e,t,n){const r=Array.from(new Set(n.filter(Boolean))),o=`${t} = [${r.map(a=>`"${Sn(a)}"`).join(", ")}]`,i=new RegExp(`\\b${t}\\s*=\\s*\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,o):Fa(e,` ${o}`)}function nf(e){const t=Pl(e,"parameterPolicy"),n=Pl(e,"filterBindings"),r=new Set(Array.from(e.matchAll(/\$\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/g)).map(a=>a[1])),o=/\btype\s*=\s*"semantic"/i.test(e);return Ba(e,"params").split(/\r?\n/).flatMap(a=>{const c=a.trim();if(!c||c.startsWith("//")||c.startsWith("#"))return[];const l=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(string|number|boolean|date)(\[\])?)?\s*(?:=\s*(.+))?$/.exec(c);if(!l)return[];const u=l[1],h=l[4]===void 0?void 0:cf(l[4]),d=l[2]?`${l[2]}${l[3]??""}`:q1(lf(h),u),f=n.get(u),m=r.has(u)?{kind:"sql_value"}:u==="top_n"||u==="limit"?{kind:"limit"}:o&&f?{kind:"semantic_filter",field:f,operator:u.endsWith("_set")?"in":"equals"}:void 0;return[{name:u,type:d,required:l[4]===void 0,...l[4]===void 0?{}:{default:h},policy:W1(t.get(u)),...m?{binding:m}:{}}]})}function q1(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=>_l(i))?"date[]":o.length>0&&o.every(i=>gs(i))?"number[]":"string[]"}return n==="true"||n==="false"?"boolean":_l(n)?"date":gs(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 rf(e){return e.default===void 0?"":lf(e.default)}function Zj(e){if(/^\s*block\s+"/i.test(e))return e;const t=e.trim();return`block "notebook_query" {
482
+ ${l}`}return{sql:l,substituted:Array.from(new Set(o)),unresolved:Array.from(new Set(i)),ambiguous:Array.from(new Set(a))}}function Xj(e){if(!/^\s*block\s+"[^"]+"\s*\{/i.test(e))return!1;let t=0,n=!1,r=!1,o=!1,i=!1;for(let a=0;a<e.length;a+=1){if(e.slice(a,a+3)==='"""'&&!i){o=!o,a+=2,r=!1;continue}if(o)continue;const c=e[a];if(c==='"'&&!i&&(r=!r),!r){if(c==="{")t+=1,n=!0;else if(c==="}"&&(t-=1,t<0))return!1}i=c==="\\"&&!i,c!=="\\"&&(i=!1)}return n&&t===0&&!r&&!o}function tf(e){const t=i=>{var a;return((a=e.match(new RegExp(`\\b${i}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:a[1])??""},n=i=>{const a=e.match(new RegExp(`\\b${i}\\s*=\\s*\\[([\\s\\S]*?)\\]`,"i"));return((a==null?void 0:a[1].match(/"([^"]*)"/g))??[]).map(c=>c.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 Zj(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 Fa(n,` metrics = [${r.map(o=>`"${Sn(o)}"`).join(", ")}]`)}function nf(e,t,n){const r=Array.from(new Set(n.filter(Boolean))),o=`${t} = [${r.map(a=>`"${Sn(a)}"`).join(", ")}]`,i=new RegExp(`\\b${t}\\s*=\\s*\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,o):Fa(e,` ${o}`)}function rf(e){const t=Il(e,"parameterPolicy"),n=Il(e,"filterBindings"),r=new Set(Array.from(e.matchAll(/\$\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/g)).map(a=>a[1])),o=/\btype\s*=\s*"semantic"/i.test(e);return Ba(e,"params").split(/\r?\n/).flatMap(a=>{const c=a.trim();if(!c||c.startsWith("//")||c.startsWith("#"))return[];const l=/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(string|number|boolean|date)(\[\])?)?\s*(?:=\s*(.+))?$/.exec(c);if(!l)return[];const u=l[1],h=l[4]===void 0?void 0:lf(l[4]),d=l[2]?`${l[2]}${l[3]??""}`:U1(df(h),u),f=n.get(u),m=r.has(u)?{kind:"sql_value"}:u==="top_n"||u==="limit"?{kind:"limit"}:o&&f?{kind:"semantic_filter",field:f,operator:u.endsWith("_set")?"in":"equals"}:void 0;return[{name:u,type:d,required:l[4]===void 0,...l[4]===void 0?{}:{default:h},policy:K1(t.get(u)),...m?{binding:m}:{}}]})}function U1(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=>Pl(i))?"date[]":o.length>0&&o.every(i=>gs(i))?"number[]":"string[]"}return n==="true"||n==="false"?"boolean":Pl(n)?"date":gs(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 of(e){return e.default===void 0?"":df(e.default)}function eE(e){if(/^\s*block\s+"/i.test(e))return e;const t=e.trim();return`block "notebook_query" {
483
483
  status = "draft"
484
484
  domain = "uncategorized"
485
485
  type = "custom"
@@ -490,20 +490,20 @@ ${t?t.split(/\r?\n/).map(r=>` ${r}`).join(`
490
490
  `):" -- Write query"}
491
491
  """
492
492
  }
493
- `}function eE(e,t){const n=af(t.name);if(!n)return e;const r=nf(e).filter(o=>o.name!==t.previousName&&o.name!==n).map(o=>({name:o.name,type:o.type,required:o.required,defaultText:rf(o),policy:o.policy}));return r.push({name:n,type:t.type,required:t.required,defaultText:t.defaultText??"",policy:t.policy}),of(e,r)}function tE(e,t){const n=nf(e).filter(r=>r.name!==t).map(r=>({name:r.name,type:r.type,required:r.required,defaultText:rf(r),policy:r.policy}));return of(e,n)}function nE(e,t,n){const r=af(t),o=n.trim();if(!r||!o)return e;const a=Ba(e,"filterBindings").split(/\r?\n/).filter(c=>c.trim()&&!new RegExp(`^${r}\\s*=`).test(c.trim()));return a.push(`${r} = "${Sn(o)}"`),ys(e,"filterBindings",a.join(`
494
- `))}function of(e,t){const n=t.map(i=>{const a=`${i.name}: ${i.type}`;return i.required?a:`${a} = ${sf(i.defaultText,i.type)}`}).join(`
493
+ `}function tE(e,t){const n=cf(t.name);if(!n)return e;const r=rf(e).filter(o=>o.name!==t.previousName&&o.name!==n).map(o=>({name:o.name,type:o.type,required:o.required,defaultText:of(o),policy:o.policy}));return r.push({name:n,type:t.type,required:t.required,defaultText:t.defaultText??"",policy:t.policy}),sf(e,r)}function nE(e,t){const n=rf(e).filter(r=>r.name!==t).map(r=>({name:r.name,type:r.type,required:r.required,defaultText:of(r),policy:r.policy}));return sf(e,n)}function rE(e,t,n){const r=cf(t),o=n.trim();if(!r||!o)return e;const a=Ba(e,"filterBindings").split(/\r?\n/).filter(c=>c.trim()&&!new RegExp(`^${r}\\s*=`).test(c.trim()));return a.push(`${r} = "${Sn(o)}"`),ys(e,"filterBindings",a.join(`
494
+ `))}function sf(e,t){const n=t.map(i=>{const a=`${i.name}: ${i.type}`;return i.required?a:`${a} = ${af(i.defaultText,i.type)}`}).join(`
495
495
  `),r=t.map(i=>`${i.name} = "${i.policy}"`).join(`
496
- `);let o=ys(e,"params",n);return o=ys(o,"parameterPolicy",r),o}function sf(e,t){const n=e.trim();if(t==="boolean")return n==="true"?"true":"false";if(t==="number")return gs(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=>sf(i,r)).join(", ")}]`}return`"${Sn(n)}"`}function af(e){const t=e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return/^[a-z_][a-z0-9_]*$/.test(t)?t:""}function gs(e){return e!==""&&Number.isFinite(Number(e))}function _l(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)}function Ba(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 Pl(e,t){const n=new Map;for(const r of Ba(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 cf(e){const t=e.trim();return t==="true"?!0:t==="false"?!1:gs(t)?Number(t):t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.startsWith("[")&&t.endsWith("]")?U1(t.slice(1,-1)).map(cf):t}function U1(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 lf(e){return Array.isArray(e)?e.join(", "):String(e??"")}function W1(e){return e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:"dynamic"}function K1(e,t){const n=new Set(ef(e).requestedFilters),r=Array.from(new Set(t.filter(Boolean)));let o=tf(e,"requested_filters",r);return o=pi(o,"params",n,r,i=>`${i}: string`),o=pi(o,"parameterPolicy",n,r,i=>`${i} = "dynamic"`),o=pi(o,"filterBindings",n,r,i=>`${i} = "${Sn(i)}"`),o}function pi(e,t,n,r,o){const c=[...Y1(e,t).split(/\r?\n/).filter(l=>{var h;const u=(h=l.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::|=)/))==null?void 0:h[1];return!u||!n.has(u)}).filter(l=>l.trim()),...r.map(o)].join(`
497
- `);return ys(e,t,c)}function Il(e,t,n){const r=Sn(n),o=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return o.test(e)?e.replace(o,`$1"${r}"`):Fa(e,` ${t} = "${r}"`)}function rE(e,t){const n=new Set(t.filter(Boolean)),r=ef(e);let o=tf(e,"dimensions",r.dimensions.filter(i=>n.has(i)));return o=K1(o,r.requestedFilters.filter(i=>n.has(i))),r.timeDimension&&!n.has(r.timeDimension)&&(o=Il(o,"time_dimension",""),o=Il(o,"granularity","")),o}function Sn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Fa(e,t){return/visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
496
+ `);let o=ys(e,"params",n);return o=ys(o,"parameterPolicy",r),o}function af(e,t){const n=e.trim();if(t==="boolean")return n==="true"?"true":"false";if(t==="number")return gs(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=>af(i,r)).join(", ")}]`}return`"${Sn(n)}"`}function cf(e){const t=e.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return/^[a-z_][a-z0-9_]*$/.test(t)?t:""}function gs(e){return e!==""&&Number.isFinite(Number(e))}function Pl(e){return/^\d{4}-\d{2}-\d{2}$/.test(e)}function Ba(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 Il(e,t){const n=new Map;for(const r of Ba(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 lf(e){const t=e.trim();return t==="true"?!0:t==="false"?!1:gs(t)?Number(t):t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.startsWith("[")&&t.endsWith("]")?W1(t.slice(1,-1)).map(lf):t}function W1(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 df(e){return Array.isArray(e)?e.join(", "):String(e??"")}function K1(e){return e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:"dynamic"}function V1(e,t){const n=new Set(tf(e).requestedFilters),r=Array.from(new Set(t.filter(Boolean)));let o=nf(e,"requested_filters",r);return o=pi(o,"params",n,r,i=>`${i}: string`),o=pi(o,"parameterPolicy",n,r,i=>`${i} = "dynamic"`),o=pi(o,"filterBindings",n,r,i=>`${i} = "${Sn(i)}"`),o}function pi(e,t,n,r,o){const c=[...X1(e,t).split(/\r?\n/).filter(l=>{var h;const u=(h=l.trim().match(/^([A-Za-z_][A-Za-z0-9_]*)\s*(?::|=)/))==null?void 0:h[1];return!u||!n.has(u)}).filter(l=>l.trim()),...r.map(o)].join(`
497
+ `);return ys(e,t,c)}function Dl(e,t,n){const r=Sn(n),o=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return o.test(e)?e.replace(o,`$1"${r}"`):Fa(e,` ${t} = "${r}"`)}function oE(e,t){const n=new Set(t.filter(Boolean)),r=tf(e);let o=nf(e,"dimensions",r.dimensions.filter(i=>n.has(i)));return o=V1(o,r.requestedFilters.filter(i=>n.has(i))),r.timeDimension&&!n.has(r.timeDimension)&&(o=Dl(o,"time_dimension",""),o=Dl(o,"granularity","")),o}function Sn(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Fa(e,t){return/visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
498
498
  ${t}
499
499
 
500
500
  visualization {`):e.replace(/\n\}\s*$/,`
501
501
  ${t}
502
502
  }
503
- `)}function V1(e){var i;const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=a=>{var c;return(c=n.match(new RegExp(`\\b${a}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:c[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 H1(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 a=i.search(/\b(visualization|tests|block)\s*\{/i);return a>0&&(i=i.slice(0,a)),i=G1(i),i.trim()||null}return null}function G1(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 oE(e){const t=za(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 Q1(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}"`):Br(e,` ${t} = "${r}"`)}function J1(e,t){const n=t.replace(/"/g,'\\"');return/^\s*block\s+"/i.test(e)?e.replace(/^(\s*block\s+)"[^"]+"/i,`$1"${n}"`):e}function sE(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}]`):Br(e,` tags = [${n}]`)}function iE(e,t,n){const r=Array.from(new Set(n.map(a=>a.trim()).filter(Boolean))),o=`${t} = [${r.map(a=>`"${Sn(a)}"`).join(", ")}]`,i=new RegExp(`(\\b${t}\\s*=\\s*)\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,`$1[${r.map(a=>`"${Sn(a)}"`).join(", ")}]`):Br(e,` ${o}`)}function aE(e,t){const n=/visualization\s*\{[\s\S]*?\n\s*\}/i;if(!n.test(e)){const r=Z1(t);return Br(e,` ${r.replace(/\n/g,`
503
+ `)}function H1(e){var i;const t=e.match(/visualization\s*\{([^}]+)\}/is);if(!t)return;const n=t[1],r=a=>{var c;return(c=n.match(new RegExp(`\\b${a}\\s*=\\s*["']?([\\w-]+)["']?`,"i")))==null?void 0:c[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 G1(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 a=i.search(/\b(visualization|tests|block)\s*\{/i);return a>0&&(i=i.slice(0,a)),i=Q1(i),i.trim()||null}return null}function Q1(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 sE(e){const t=za(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 J1(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}"`):Br(e,` ${t} = "${r}"`)}function Y1(e,t){const n=t.replace(/"/g,'\\"');return/^\s*block\s+"/i.test(e)?e.replace(/^(\s*block\s+)"[^"]+"/i,`$1"${n}"`):e}function iE(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}]`):Br(e,` tags = [${n}]`)}function aE(e,t,n){const r=Array.from(new Set(n.map(a=>a.trim()).filter(Boolean))),o=`${t} = [${r.map(a=>`"${Sn(a)}"`).join(", ")}]`,i=new RegExp(`(\\b${t}\\s*=\\s*)\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,`$1[${r.map(a=>`"${Sn(a)}"`).join(", ")}]`):Br(e,` ${o}`)}function cE(e,t){const n=/visualization\s*\{[\s\S]*?\n\s*\}/i;if(!n.test(e)){const r=eC(t);return Br(e,` ${r.replace(/\n/g,`
504
504
  `)}`,!0)}return e.replace(n,r=>{let o=r;for(const[i,a]of Object.entries(t)){if(a==null||a==="")continue;const c=String(a).replace(/"/g,'\\"'),l=new RegExp(`(\\b${i}\\s*=\\s*)"[^"]*"`,"i");l.test(o)?o=o.replace(l,`$1"${c}"`):o=o.replace(/\n(\s*)\}$/,`
505
505
  $1 ${i} = "${c}"
506
- $1}`)}return o})}function Y1(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(`
506
+ $1}`)}return o})}function X1(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(`
507
507
  `).trim())??""}function ys(e,t,n){const r=n.trim(),o=r?` ${t} {
508
508
  ${r.split(/\r?\n/).map(a=>` ${a.trimEnd()}`).join(`
509
509
  `)}
@@ -511,35 +511,35 @@ ${r.split(/\r?\n/).map(a=>` ${a.trimEnd()}`).join(`
511
511
  ${o}`:""):o?/\n\s*visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
512
512
  ${o}
513
513
 
514
- visualization {`):Br(e,o,!0):e}function cE(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function lE(e,t){const n=za(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
514
+ visualization {`):Br(e,o,!0):e}function lE(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function dE(e,t){const n=za(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
515
515
  ${t}
516
516
  `;const r=n.query.trimEnd(),o=r?`${r}
517
- ${t}`:t;return X1(e,o)}function X1(e,t){if(!za(e))return e;const r=Q1(e,"type","custom"),o=` query = """
517
+ ${t}`:t;return Z1(e,o)}function Z1(e,t){if(!za(e))return e;const r=J1(e,"type","custom"),o=` query = """
518
518
  ${t.trimEnd()}
519
519
  """`,i=/\n\s*query\s*=\s*"""[\s\S]*?"""/i;return i.test(r)?r.replace(i,`
520
- ${o}`):Br(r,o,!0)}function za(e){var i,a;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=c=>{var l;return((l=e.match(new RegExp(`\\b${c}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:l[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(c=>c.slice(1,-1)):[],metric:t("metric"),metrics:Wr(e,"metrics"),dimensions:Wr(e,"dimensions"),requestedFilters:Wr(e,"requested_filters"),sourceDqlKind:t("source_dql_kind"),sourceDqlName:t("source_dql_name"),sourceDqlPath:t("source_dql_path"),sourceDqlHash:t("source_dql_hash"),sourceDqlMetrics:Wr(e,"source_dql_metrics"),sourceDqlDimensions:Wr(e,"source_dql_dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((a=o==null?void 0:o[1])==null?void 0:a.trim())??"",visualization:Dl(e,"visualization"),tests:Dl(e,"tests")}}function Wr(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 Dl(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 a=e[i];if(a==="{")r===0&&(o=i),r++;else if(a==="}"&&(r--,r===0&&o>=0))return e.slice(n.index,i+1).trim()}return""}function Z1(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 = "${eC(e.title)}"`),t.push("}"),t.join(`
521
- `)}function eC(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Br(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
520
+ ${o}`):Br(r,o,!0)}function za(e){var i,a;if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=c=>{var l;return((l=e.match(new RegExp(`\\b${c}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:l[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(c=>c.slice(1,-1)):[],metric:t("metric"),metrics:Wr(e,"metrics"),dimensions:Wr(e,"dimensions"),requestedFilters:Wr(e,"requested_filters"),sourceDqlKind:t("source_dql_kind"),sourceDqlName:t("source_dql_name"),sourceDqlPath:t("source_dql_path"),sourceDqlHash:t("source_dql_hash"),sourceDqlMetrics:Wr(e,"source_dql_metrics"),sourceDqlDimensions:Wr(e,"source_dql_dimensions"),timeDimension:t("time_dimension"),granularity:t("granularity"),query:((a=o==null?void 0:o[1])==null?void 0:a.trim())??"",visualization:$l(e,"visualization"),tests:$l(e,"tests")}}function Wr(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 $l(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 a=e[i];if(a==="{")r===0&&(o=i),r++;else if(a==="}"&&(r--,r===0&&o>=0))return e.slice(n.index,i+1).trim()}return""}function eC(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 = "${tC(e.title)}"`),t.push("}"),t.join(`
521
+ `)}function tC(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Br(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
522
522
  ${t}
523
523
  `;const o=n?`
524
524
 
525
525
  ${t}
526
526
  `:`
527
527
  ${t}`;return r.replace(/\n\}\s*$/,`${o}
528
- }`)}function $l(e,t){return t.filter(n=>n.datasetId&&(n.objectType==="dataset"||n.objectType==="staged_dataset")).filter(n=>df(n.name).test(e)).map(n=>({id:n.datasetId,alias:n.name,role:n.objectType==="staged_dataset"?"staged":"source",fingerprint:n.fileFingerprint}))}function tC(e,t){return t.filter(n=>n.source==="database").filter(n=>df(n.name).test(e)).map(n=>n.name)}function dE(e,t){const n=[];for(const r of e)for(const o of t){const i=nC(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 uE(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(oC)).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 pE(e){const t=new Set(e.staged.columns??[]),r=[" warehouse.*",...(e.local.columns??[]).filter(i=>i!==e.localKey).map(i=>{const a=t.has(i)?`local_${i}`:i;return` local_data.${sr(i)} AS ${sr(a)}`})];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(`,
528
+ }`)}function Ml(e,t){return t.filter(n=>n.datasetId&&(n.objectType==="dataset"||n.objectType==="staged_dataset")).filter(n=>uf(n.name).test(e)).map(n=>({id:n.datasetId,alias:n.name,role:n.objectType==="staged_dataset"?"staged":"source",fingerprint:n.fileFingerprint}))}function nC(e,t){return t.filter(n=>n.source==="database").filter(n=>uf(n.name).test(e)).map(n=>n.name)}function uE(e,t){const n=[];for(const r of e)for(const o of t){const i=rC(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 pE(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(sC)).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 fE(e){const t=new Set(e.staged.columns??[]),r=[" warehouse.*",...(e.local.columns??[]).filter(i=>i!==e.localKey).map(i=>{const a=t.has(i)?`local_${i}`:i;return` local_data.${sr(i)} AS ${sr(a)}`})];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(`,
529
529
  `),`FROM ${sr(e.staged.alias)} AS warehouse`,`${e.joinType.toUpperCase()} JOIN ${sr(e.local.alias)} AS local_data`,` ON warehouse.${sr(e.warehouseKey)} = local_data.${sr(e.localKey)}`,"LIMIT 1000"].join(`
530
- `),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 nC(e,t,n){const r=e.toLowerCase(),o=t.toLowerCase();if(r===o)return{score:100,reason:"Same column name"};const i=Ml(r),a=Ml(o);return i===a?{score:90,reason:"Same normalized name"}:(i.endsWith(a)||a.endsWith(i))&&(i.endsWith("id")||a.endsWith("id"))?{score:n.includes("identifier")?78:70,reason:"Related identifier names"}:Ll(r).filter(l=>Ll(o).includes(l)).length>0&&(r.includes("id")||o.includes("id"))?{score:n.includes("identifier")?62:55,reason:"Shared entity identifier"}:{score:0,reason:""}}function Ml(e){return e.replace(/[^a-z0-9]/g,"").replace(/identifier$/,"id")}function Ll(e){return e.split(/[^a-z0-9]+/).filter(t=>t.length>1)}function df(e){return new RegExp(`(?:^|[^a-zA-Z0-9_])(?:["\`])?${rC(e)}(?:["\`])?(?=$|[^a-zA-Z0-9_])`,"i")}function sr(e){return`"${e.replace(/"/g,'""')}"`}function rC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oC(e){return typeof e=="string"?e:JSON.stringify(e)}const _n=new Map,rn=new Map;function fi(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 sC(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?H1(t):null}function iC(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 Zr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function aC(e){const t=Zr(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 Kr(e,t,n){return new St({status:400,code:e,message:t,recoverable:!0,details:{phase:"preflight",...n}})}function Jo(e){const t=e.error instanceof St?e.error:void 0,n=Zr(t==null?void 0:t.details),r=Zr(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??aC(n==null?void 0:n.executionTarget),compiledSql:e.attemptedSql,semanticTrace:r,targetBinding:Zr(n==null?void 0:n.targetBinding),executionReceipt:Zr(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 Yo(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 uf(){const e=jn(),t=p.useCallback(async(i,a)=>{var P,A,g,I;const c=In.getState(),l=a??c.cells,u=l.find(T=>T.id===i);if(!u)return{cellId:i,status:"skipped"};const h=u.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",d=u.type==="dql"?null:sC(u);if(u.type!=="dql"&&!d)return{cellId:i,status:"skipped"};const f=_n.get(i);f&&f.controller.abort();const m=fi(i),S=new Date().toISOString(),v=Date.now(),b=new AbortController,w={controller:b,runId:m,startedAt:S,route:h,executionTarget:u.executionTarget};_n.set(i,w),rn.set(i,m);const j=()=>{var T;return((T=_n.get(i))==null?void 0:T.runId)===m&&rn.get(i)===m},C=(u.executionCount??0)+1;let x=d??void 0;e({type:"UPDATE_CELL",id:i,updates:{status:"running",error:void 0,result:void 0,execution:void 0,fromSnapshot:!1}});const E=(T,O,_="error")=>{const M=new Date().toISOString(),q=Jo({cell:u,runId:m,route:h,startedAt:S,completedAt:M,durationMs:Date.now()-v,message:T,error:O,status:_,attemptedSql:x});return j()&&(e({type:"UPDATE_CELL",id:i,updates:{status:_==="cancelled"?"idle":"error",error:_==="cancelled"?void 0:T,result:void 0,execution:q,executionCount:C,stale:!1}}),e({type:"APPEND_QUERY_LOG",entry:{id:vt(),cellName:u.name??u.id,rows:0,time:q.durationMs,ts:new Date,..._==="cancelled"?{}:{error:T}}})),{cellId:i,runId:m,status:_,error:_==="cancelled"?void 0:T,execution:q}};try{if(u.type==="dql"){const ee=await B.executeNotebookCell(u,b.signal,{notebookPath:(P=c.activeFile)==null?void 0:P.path,cellId:u.id,cellName:u.name,source:h,runId:m});if(!ee.result)throw new Error("DQL cell produced no executable result.");if(!j())return{cellId:i,runId:m,status:"cancelled"};const ce=new Date().toISOString(),ke=Date.now()-v,xe={...ee.result,executionTime:ee.result.executionTime??ke,rowCount:ee.result.rowCount??ee.result.rows.length},De=iC(ee.chartConfig)??V1(u.content),We={version:1,runId:m,cellId:i,route:h,status:"success",startedAt:S,completedAt:ce,durationMs:ke,executionTarget:ee.executionTarget??u.executionTarget,engine:ee.engine,compiledSql:ee.compiledSql,executedSql:ee.executedSql,semanticTrace:ee.semanticTrace,targetBinding:ee.targetBinding,executionReceipt:ee.executionReceipt};return e({type:"UPDATE_CELL",id:i,updates:{status:"success",result:xe,error:void 0,execution:We,executionTarget:ee.executionTarget??u.executionTarget,...De?{chartConfig:De}:{},executionCount:C,stale:!1}}),e({type:"APPEND_QUERY_LOG",entry:{id:vt(),cellName:ee.blockName??u.name??u.id,rows:xe.rowCount??xe.rows.length,time:xe.executionTime??ke,ts:new Date}}),setTimeout(()=>{rn.get(i)===m&&(e({type:"UPDATE_CELL",id:i,updates:{status:"idle"}}),rn.delete(i))},2e3),{cellId:i,runId:m,status:"success",result:xe,execution:We}}const T=$l(d,c.schemaTables),O=tC(d,c.schemaTables);if(T.length>0&&O.length>0){const ee=[`Mixed-source query detected: ${O.join(", ")} runs in the warehouse, while ${T.map(ce=>ce.alias??ce.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 E(ee,Kr("CROSS_ENGINE_JOIN_REQUIRED",ee,{warehouseTables:O,datasets:T.map(ce=>ce.alias??ce.id)}))}const _=T.length>0?{target:"local"}:u.executionTarget;T.length>0&&((A=u.executionTarget)==null?void 0:A.target)!=="local"&&e({type:"UPDATE_CELL",id:i,updates:{executionTarget:_,datasetRefs:T}});const M=z1(d,l);if(M.ambiguous.length>0){const ee=`Ambiguous notebook dependency: ${M.ambiguous.join(", ")} matches more than one cell. Rename the duplicate cells or reference a stable cell ID.`;return E(ee,Kr("AMBIGUOUS_NOTEBOOK_DEPENDENCY",ee,{ambiguousReferences:M.ambiguous}))}if(M.unresolved.length>0){const ee=`Notebook dependency result is unavailable: ${M.unresolved.join(", ")}. Run or repair the upstream cell before retrying this cell.`;return E(ee,Kr("UPSTREAM_RESULT_UNAVAILABLE",ee,{unresolvedReferences:M.unresolved}))}x=M.sql;const q=await B.executeQuery(M.sql,b.signal,{notebookPath:(g=c.activeFile)==null?void 0:g.path,cellId:u.id,cellName:u.name,source:h,runId:m},_);if(!j())return{cellId:i,runId:m,status:"cancelled"};const G=new Date().toISOString(),J=Date.now()-v,{executionTarget:H,compiledSql:L,executedSql:$,targetBinding:X,executionReceipt:W,...te}=q,F={...te,executionTime:te.executionTime??J,rowCount:te.rowCount??te.rows.length},K=(_==null?void 0:_.target)==="local"?$l(M.sql,c.schemaTables):u.datasetRefs,oe={version:1,runId:m,cellId:i,route:h,status:"success",startedAt:S,completedAt:G,durationMs:J,executionTarget:H??_,compiledSql:L??M.sql,executedSql:$??M.sql,targetBinding:X,executionReceipt:W};return e({type:"UPDATE_CELL",id:i,updates:{status:"success",result:F,error:void 0,execution:oe,executionCount:C,stale:!1,datasetRefs:K,executionTarget:H??_}}),e({type:"APPEND_QUERY_LOG",entry:{id:vt(),cellName:u.name??u.id,rows:F.rowCount??F.rows.length,time:F.executionTime??J,ts:new Date}}),setTimeout(()=>{rn.get(i)===m&&(e({type:"UPDATE_CELL",id:i,updates:{status:"idle"}}),rn.delete(i))},2e3),{cellId:i,runId:m,status:"success",result:F,execution:oe}}catch(T){if(b.signal.aborted||!j())return E("Cell execution was cancelled.",T,"cancelled");const O=T instanceof Error?T.message:String(T);return E(O,T)}finally{((I=_n.get(i))==null?void 0:I.runId)===m&&_n.delete(i)}},[e]),n=p.useCallback(async()=>{const i=In.getState().cells,a=zx(i);let c=i.map(h=>({...h}));const l=new Map,u=new Map;for(const h of a.missing)u.set(h.cellId,[...u.get(h.cellId)??[],h.dependency]);for(const h of a.cycleCellIds){const d=c.find(w=>w.id===h);if(!d)continue;const f=fi(h),m=new Date().toISOString(),S="Dependency cycle detected. Update the cell dependencies before running all.",v=Jo({cell:d,runId:f,route:d.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",startedAt:m,completedAt:m,durationMs:0,message:S,error:Kr("DEPENDENCY_CYCLE",S,{cycleCellIds:a.cycleCellIds}),status:"blocked"}),b={cellId:h,runId:f,status:"blocked",error:S,execution:v};l.set(h,b),c=Yo(c,b),e({type:"UPDATE_CELL",id:h,updates:{status:"error",error:S,result:void 0,execution:v,executionCount:(d.executionCount??0)+1,stale:!1}})}for(const h of a.ordered){const d=c.find(v=>v.id===h.id)??h,f=u.get(d.id)??[],m=Aa(d,c).filter(v=>{const b=l.get(v.cellId);return b&&b.status!=="success"});if(f.length>0||m.length>0){const v=[...f,...m.map(E=>{var P;return((P=c.find(A=>A.id===E.cellId))==null?void 0:P.name)??E.cellId})],b=fi(d.id),w=new Date().toISOString(),j=`Not executed because ${v.join(", ")} did not produce a valid upstream result.`,C=Jo({cell:d,runId:b,route:d.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",startedAt:w,completedAt:w,durationMs:0,message:j,error:Kr("UPSTREAM_EXECUTION_FAILED",j,{blockedBy:v}),status:"blocked"}),x={cellId:d.id,runId:b,status:"blocked",error:j,execution:C};l.set(d.id,x),c=Yo(c,x),e({type:"UPDATE_CELL",id:d.id,updates:{status:"error",error:j,result:void 0,execution:C,executionCount:(d.executionCount??0)+1,stale:!1}});continue}const S=await t(d.id,c);l.set(d.id,S),c=Yo(c,S)}},[e,t]),r=p.useCallback(async i=>{if(!i)return;const a=`{{${i}}}`;let c=In.getState().cells.map(l=>({...l}));for(const l of c){if(l.type==="markdown"||l.type==="param"||!l.content.includes(a))continue;const u=await t(l.id,c);c=Yo(c,u)}},[t]),o=p.useCallback(i=>{const a=_n.get(i);if(!a)return;a.controller.abort(),_n.delete(i),rn.get(i)===a.runId&&rn.delete(i);const c=new Date().toISOString(),l=In.getState().cells.find(u=>u.id===i);e({type:"UPDATE_CELL",id:i,updates:{status:"idle",error:void 0,result:void 0,...l?{execution:Jo({cell:l,runId:a.runId,route:a.route,startedAt:a.startedAt,completedAt:c,durationMs:Date.parse(c)-Date.parse(a.startedAt),message:"Cell execution was cancelled.",status:"cancelled"}),executionCount:(l.executionCount??0)+1}:{}}})},[e]);return{executeCell:t,executeAll:n,executeDependents:r,cancelCell:o}}function lt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function cC(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 lC(e){const t=e.split(`
531
- `),n=[];let r=!1,o=!1;for(const i of t){const a=i;if(a.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(lt(a));continue}if(a.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${lt(a.slice(4))}</h3>`);continue}if(a.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${lt(a.slice(3))}</h2>`);continue}if(a.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${lt(a.slice(2))}</h1>`);continue}if(a.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${lt(a.slice(2))}</p></blockquote>`);continue}if(a.startsWith("- ")||a.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${Nl(a.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),a.trim()===""){n.push("<br>");continue}n.push(`<p>${Nl(a)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
532
- `)}function Nl(e){return lt(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function dC(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,i=t.map(c=>`<th>${lt(c)}</th>`).join(""),a=r.map(c=>`<tr>${t.map(u=>{const h=c[u],d=typeof h=="number",f=h==null?"—":String(h);return`<td${d?' class="num"':""}>${lt(f)}</td>`}).join("")}</tr>`).join("");return`
530
+ `),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 rC(e,t,n){const r=e.toLowerCase(),o=t.toLowerCase();if(r===o)return{score:100,reason:"Same column name"};const i=Ll(r),a=Ll(o);return i===a?{score:90,reason:"Same normalized name"}:(i.endsWith(a)||a.endsWith(i))&&(i.endsWith("id")||a.endsWith("id"))?{score:n.includes("identifier")?78:70,reason:"Related identifier names"}:Nl(r).filter(l=>Nl(o).includes(l)).length>0&&(r.includes("id")||o.includes("id"))?{score:n.includes("identifier")?62:55,reason:"Shared entity identifier"}:{score:0,reason:""}}function Ll(e){return e.replace(/[^a-z0-9]/g,"").replace(/identifier$/,"id")}function Nl(e){return e.split(/[^a-z0-9]+/).filter(t=>t.length>1)}function uf(e){return new RegExp(`(?:^|[^a-zA-Z0-9_])(?:["\`])?${oC(e)}(?:["\`])?(?=$|[^a-zA-Z0-9_])`,"i")}function sr(e){return`"${e.replace(/"/g,'""')}"`}function oC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sC(e){return typeof e=="string"?e:JSON.stringify(e)}const _n=new Map,rn=new Map;function fi(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 iC(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?G1(t):null}function aC(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 Zr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function cC(e){const t=Zr(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 Kr(e,t,n){return new St({status:400,code:e,message:t,recoverable:!0,details:{phase:"preflight",...n}})}function Jo(e){const t=e.error instanceof St?e.error:void 0,n=Zr(t==null?void 0:t.details),r=Zr(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??cC(n==null?void 0:n.executionTarget),compiledSql:e.attemptedSql,semanticTrace:r,targetBinding:Zr(n==null?void 0:n.targetBinding),executionReceipt:Zr(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 Yo(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 pf(){const e=jn(),t=p.useCallback(async(i,a)=>{var P,A,g,I;const c=In.getState(),l=a??c.cells,u=l.find(T=>T.id===i);if(!u)return{cellId:i,status:"skipped"};const h=u.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",d=u.type==="dql"?null:iC(u);if(u.type!=="dql"&&!d)return{cellId:i,status:"skipped"};const f=_n.get(i);f&&f.controller.abort();const m=fi(i),S=new Date().toISOString(),v=Date.now(),b=new AbortController,w={controller:b,runId:m,startedAt:S,route:h,executionTarget:u.executionTarget};_n.set(i,w),rn.set(i,m);const j=()=>{var T;return((T=_n.get(i))==null?void 0:T.runId)===m&&rn.get(i)===m},C=(u.executionCount??0)+1;let x=d??void 0;e({type:"UPDATE_CELL",id:i,updates:{status:"running",error:void 0,result:void 0,execution:void 0,fromSnapshot:!1}});const E=(T,O,_="error")=>{const M=new Date().toISOString(),q=Jo({cell:u,runId:m,route:h,startedAt:S,completedAt:M,durationMs:Date.now()-v,message:T,error:O,status:_,attemptedSql:x});return j()&&(e({type:"UPDATE_CELL",id:i,updates:{status:_==="cancelled"?"idle":"error",error:_==="cancelled"?void 0:T,result:void 0,execution:q,executionCount:C,stale:!1}}),e({type:"APPEND_QUERY_LOG",entry:{id:vt(),cellName:u.name??u.id,rows:0,time:q.durationMs,ts:new Date,..._==="cancelled"?{}:{error:T}}})),{cellId:i,runId:m,status:_,error:_==="cancelled"?void 0:T,execution:q}};try{if(u.type==="dql"){const ee=await B.executeNotebookCell(u,b.signal,{notebookPath:(P=c.activeFile)==null?void 0:P.path,cellId:u.id,cellName:u.name,source:h,runId:m});if(!ee.result)throw new Error("DQL cell produced no executable result.");if(!j())return{cellId:i,runId:m,status:"cancelled"};const ce=new Date().toISOString(),ke=Date.now()-v,xe={...ee.result,executionTime:ee.result.executionTime??ke,rowCount:ee.result.rowCount??ee.result.rows.length},De=aC(ee.chartConfig)??H1(u.content),We={version:1,runId:m,cellId:i,route:h,status:"success",startedAt:S,completedAt:ce,durationMs:ke,executionTarget:ee.executionTarget??u.executionTarget,engine:ee.engine,compiledSql:ee.compiledSql,executedSql:ee.executedSql,semanticTrace:ee.semanticTrace,targetBinding:ee.targetBinding,executionReceipt:ee.executionReceipt};return e({type:"UPDATE_CELL",id:i,updates:{status:"success",result:xe,error:void 0,execution:We,executionTarget:ee.executionTarget??u.executionTarget,...De?{chartConfig:De}:{},executionCount:C,stale:!1}}),e({type:"APPEND_QUERY_LOG",entry:{id:vt(),cellName:ee.blockName??u.name??u.id,rows:xe.rowCount??xe.rows.length,time:xe.executionTime??ke,ts:new Date}}),setTimeout(()=>{rn.get(i)===m&&(e({type:"UPDATE_CELL",id:i,updates:{status:"idle"}}),rn.delete(i))},2e3),{cellId:i,runId:m,status:"success",result:xe,execution:We}}const T=Ml(d,c.schemaTables),O=nC(d,c.schemaTables);if(T.length>0&&O.length>0){const ee=[`Mixed-source query detected: ${O.join(", ")} runs in the warehouse, while ${T.map(ce=>ce.alias??ce.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 E(ee,Kr("CROSS_ENGINE_JOIN_REQUIRED",ee,{warehouseTables:O,datasets:T.map(ce=>ce.alias??ce.id)}))}const _=T.length>0?{target:"local"}:u.executionTarget;T.length>0&&((A=u.executionTarget)==null?void 0:A.target)!=="local"&&e({type:"UPDATE_CELL",id:i,updates:{executionTarget:_,datasetRefs:T}});const M=q1(d,l);if(M.ambiguous.length>0){const ee=`Ambiguous notebook dependency: ${M.ambiguous.join(", ")} matches more than one cell. Rename the duplicate cells or reference a stable cell ID.`;return E(ee,Kr("AMBIGUOUS_NOTEBOOK_DEPENDENCY",ee,{ambiguousReferences:M.ambiguous}))}if(M.unresolved.length>0){const ee=`Notebook dependency result is unavailable: ${M.unresolved.join(", ")}. Run or repair the upstream cell before retrying this cell.`;return E(ee,Kr("UPSTREAM_RESULT_UNAVAILABLE",ee,{unresolvedReferences:M.unresolved}))}x=M.sql;const q=await B.executeQuery(M.sql,b.signal,{notebookPath:(g=c.activeFile)==null?void 0:g.path,cellId:u.id,cellName:u.name,source:h,runId:m},_);if(!j())return{cellId:i,runId:m,status:"cancelled"};const G=new Date().toISOString(),J=Date.now()-v,{executionTarget:H,compiledSql:L,executedSql:$,targetBinding:X,executionReceipt:W,...te}=q,F={...te,executionTime:te.executionTime??J,rowCount:te.rowCount??te.rows.length},K=(_==null?void 0:_.target)==="local"?Ml(M.sql,c.schemaTables):u.datasetRefs,oe={version:1,runId:m,cellId:i,route:h,status:"success",startedAt:S,completedAt:G,durationMs:J,executionTarget:H??_,compiledSql:L??M.sql,executedSql:$??M.sql,targetBinding:X,executionReceipt:W};return e({type:"UPDATE_CELL",id:i,updates:{status:"success",result:F,error:void 0,execution:oe,executionCount:C,stale:!1,datasetRefs:K,executionTarget:H??_}}),e({type:"APPEND_QUERY_LOG",entry:{id:vt(),cellName:u.name??u.id,rows:F.rowCount??F.rows.length,time:F.executionTime??J,ts:new Date}}),setTimeout(()=>{rn.get(i)===m&&(e({type:"UPDATE_CELL",id:i,updates:{status:"idle"}}),rn.delete(i))},2e3),{cellId:i,runId:m,status:"success",result:F,execution:oe}}catch(T){if(b.signal.aborted||!j())return E("Cell execution was cancelled.",T,"cancelled");const O=T instanceof Error?T.message:String(T);return E(O,T)}finally{((I=_n.get(i))==null?void 0:I.runId)===m&&_n.delete(i)}},[e]),n=p.useCallback(async()=>{const i=In.getState().cells,a=qx(i);let c=i.map(h=>({...h}));const l=new Map,u=new Map;for(const h of a.missing)u.set(h.cellId,[...u.get(h.cellId)??[],h.dependency]);for(const h of a.cycleCellIds){const d=c.find(w=>w.id===h);if(!d)continue;const f=fi(h),m=new Date().toISOString(),S="Dependency cycle detected. Update the cell dependencies before running all.",v=Jo({cell:d,runId:f,route:d.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",startedAt:m,completedAt:m,durationMs:0,message:S,error:Kr("DEPENDENCY_CYCLE",S,{cycleCellIds:a.cycleCellIds}),status:"blocked"}),b={cellId:h,runId:f,status:"blocked",error:S,execution:v};l.set(h,b),c=Yo(c,b),e({type:"UPDATE_CELL",id:h,updates:{status:"error",error:S,result:void 0,execution:v,executionCount:(d.executionCount??0)+1,stale:!1}})}for(const h of a.ordered){const d=c.find(v=>v.id===h.id)??h,f=u.get(d.id)??[],m=Aa(d,c).filter(v=>{const b=l.get(v.cellId);return b&&b.status!=="success"});if(f.length>0||m.length>0){const v=[...f,...m.map(E=>{var P;return((P=c.find(A=>A.id===E.cellId))==null?void 0:P.name)??E.cellId})],b=fi(d.id),w=new Date().toISOString(),j=`Not executed because ${v.join(", ")} did not produce a valid upstream result.`,C=Jo({cell:d,runId:b,route:d.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",startedAt:w,completedAt:w,durationMs:0,message:j,error:Kr("UPSTREAM_EXECUTION_FAILED",j,{blockedBy:v}),status:"blocked"}),x={cellId:d.id,runId:b,status:"blocked",error:j,execution:C};l.set(d.id,x),c=Yo(c,x),e({type:"UPDATE_CELL",id:d.id,updates:{status:"error",error:j,result:void 0,execution:C,executionCount:(d.executionCount??0)+1,stale:!1}});continue}const S=await t(d.id,c);l.set(d.id,S),c=Yo(c,S)}},[e,t]),r=p.useCallback(async i=>{if(!i)return;const a=`{{${i}}}`;let c=In.getState().cells.map(l=>({...l}));for(const l of c){if(l.type==="markdown"||l.type==="param"||!l.content.includes(a))continue;const u=await t(l.id,c);c=Yo(c,u)}},[t]),o=p.useCallback(i=>{const a=_n.get(i);if(!a)return;a.controller.abort(),_n.delete(i),rn.get(i)===a.runId&&rn.delete(i);const c=new Date().toISOString(),l=In.getState().cells.find(u=>u.id===i);e({type:"UPDATE_CELL",id:i,updates:{status:"idle",error:void 0,result:void 0,...l?{execution:Jo({cell:l,runId:a.runId,route:a.route,startedAt:a.startedAt,completedAt:c,durationMs:Date.parse(c)-Date.parse(a.startedAt),message:"Cell execution was cancelled.",status:"cancelled"}),executionCount:(l.executionCount??0)+1}:{}}})},[e]);return{executeCell:t,executeAll:n,executeDependents:r,cancelCell:o}}function lt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function lC(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 dC(e){const t=e.split(`
531
+ `),n=[];let r=!1,o=!1;for(const i of t){const a=i;if(a.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(lt(a));continue}if(a.startsWith("### ")){o&&(n.push("</ul>"),o=!1),n.push(`<h3>${lt(a.slice(4))}</h3>`);continue}if(a.startsWith("## ")){o&&(n.push("</ul>"),o=!1),n.push(`<h2>${lt(a.slice(3))}</h2>`);continue}if(a.startsWith("# ")){o&&(n.push("</ul>"),o=!1),n.push(`<h1>${lt(a.slice(2))}</h1>`);continue}if(a.startsWith("> ")){o&&(n.push("</ul>"),o=!1),n.push(`<blockquote><p>${lt(a.slice(2))}</p></blockquote>`);continue}if(a.startsWith("- ")||a.startsWith("* ")){o||(n.push("<ul>"),o=!0),n.push(`<li>${Bl(a.slice(2))}</li>`);continue}if(o&&(n.push("</ul>"),o=!1),a.trim()===""){n.push("<br>");continue}n.push(`<p>${Bl(a)}</p>`)}return o&&n.push("</ul>"),r&&n.push("</code></pre>"),n.join(`
532
+ `)}function Bl(e){return lt(e).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/`(.+?)`/g,"<code>$1</code>")}function uC(e){const{columns:t,rows:n}=e,r=n.slice(0,200),o=n.length>200,i=t.map(c=>`<th>${lt(c)}</th>`).join(""),a=r.map(c=>`<tr>${t.map(u=>{const h=c[u],d=typeof h=="number",f=h==null?"—":String(h);return`<td${d?' class="num"':""}>${lt(f)}</td>`}).join("")}</tr>`).join("");return`
533
533
  <div class="table-wrap">
534
534
  <table>
535
535
  <thead><tr>${i}</tr></thead>
536
536
  <tbody>${a}</tbody>
537
537
  </table>
538
538
  ${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
539
- </div>`}function uC(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 pC(e){const t=uC(e);if(!t)return null;const n=e.rows.slice(0,20).map(h=>({label:String(h[t.labelCol]??""),value:Number(h[t.valueCol]??0)})),r=Math.max(...n.map(h=>h.value),1),o=28,i=6,a=140,c=440,l=n.length*(o+i)+40,u=n.map((h,d)=>{const f=d*(o+i)+20,m=Math.max(h.value/r*c,2);return`
539
+ </div>`}function pC(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 fC(e){const t=pC(e);if(!t)return null;const n=e.rows.slice(0,20).map(h=>({label:String(h[t.labelCol]??""),value:Number(h[t.valueCol]??0)})),r=Math.max(...n.map(h=>h.value),1),o=28,i=6,a=140,c=440,l=n.length*(o+i)+40,u=n.map((h,d)=>{const f=d*(o+i)+20,m=Math.max(h.value/r*c,2);return`
540
540
  <text x="${a-6}" y="${f+o/2+4}" text-anchor="end" font-size="11" fill="#8b949e">${lt(h.label.slice(0,20))}</text>
541
541
  <rect x="${a}" y="${f}" width="${m}" height="${o}" rx="3" fill="#388bfd" />
542
- <text x="${a+m+5}" y="${f+o/2+4}" font-size="11" fill="#e6edf3">${cC(h.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${a+c+80}" height="${l}" style="max-width:100%">${u}</svg>`}function fC(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${lC(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${lt(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,i=`<pre class="cell-code"><code>${lt(r.content)}</code></pre>`;let a="";if(r.result&&r.result.rows.length>0){const c=pC(r.result),l=dC(r.result);a=`<div class="cell-output">${`<div class="output-meta">${r.result.rows.length.toLocaleString()} rows${r.result.executionTime?` · ${r.result.executionTime}ms`:""}</div>`}${c??""}${c?"":l}</div>`}else r.error&&(a=`<div class="cell-error">⚠ ${lt(r.error)}</div>`);return`<section class="cell sql-cell">${o}${i}${a}</section>`}).join(`
542
+ <text x="${a+m+5}" y="${f+o/2+4}" font-size="11" fill="#e6edf3">${lC(h.value)}</text>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" width="${a+c+80}" height="${l}" style="max-width:100%">${u}</svg>`}function hC(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${dC(r.content)}</section>`;const o=r.name?`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span><span class="cell-name">${lt(r.name)}</span></div>`:`<div class="cell-header"><span class="cell-type">${r.type.toUpperCase()}</span></div>`,i=`<pre class="cell-code"><code>${lt(r.content)}</code></pre>`;let a="";if(r.result&&r.result.rows.length>0){const c=fC(r.result),l=uC(r.result);a=`<div class="cell-output">${`<div class="output-meta">${r.result.rows.length.toLocaleString()} rows${r.result.executionTime?` · ${r.result.executionTime}ms`:""}</div>`}${c??""}${c?"":l}</div>`}else r.error&&(a=`<div class="cell-error">⚠ ${lt(r.error)}</div>`);return`<section class="cell sql-cell">${o}${i}${a}</section>`}).join(`
543
543
  `);return`<!DOCTYPE html>
544
544
  <html lang="en">
545
545
  <head>
@@ -607,7 +607,7 @@ ${t}`;return r.replace(/\n\}\s*$/,`${o}
607
607
  </div>
608
608
  <p class="exported-by">Built with DQL Workbench</p>
609
609
  </body>
610
- </html>`}function hC(e,t){const n=fC(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)}const mC=new Set(["succeeded","failed","cancelled","interrupted"]);function Ir(e){return mC.has(e.status)}function gC(e,t){if(e.id!==t.id)return t;const n=Ir(e),r=Ir(t);return n&&!r||t.updatedAt<e.updatedAt?e:t.updatedAt>e.updatedAt?t:n!==r?r?t:e:t.progress!==e.progress?t.progress>e.progress?t:e:t}function eo(e,t){const n=e.find(o=>o.id===t.id),r=n?gC(n,t):t;return kC([...e.filter(o=>o.id!==t.id),r])}function yC(e,t){return t.reduce(eo,e)}function bC(e){return e.filter(t=>!Ir(t)).map(t=>t.id)}function xC(e,t){for(const n of bC(t))e.add(n)}async function vC(e,t,n){await Promise.all([...e].map(async r=>{try{const o=await t(r);if(n(o)===!1)return;Ir(o)&&e.delete(r)}catch{}}))}function SC(e,t=new Set){return e.filter(n=>n.type==="block_certification"&&n.status==="succeeded").filter(n=>!t.has(n.id)).filter(n=>{const r=n.result;return!!(r!=null&&r.block&&r.outcome)}).sort((n,r)=>n.updatedAt.localeCompare(r.updatedAt)||n.createdAt.localeCompare(r.createdAt)||n.id.localeCompare(r.id))}function fE(e,t){var o;if(t.operationId){const i=e.find(a=>a.type==="block_certification"&&a.id===t.operationId);if(i)return i}const n=Vr(t.activePath),r=(o=t.sourceFingerprint)==null?void 0:o.trim();return e.filter(i=>i.type==="block_certification").filter(i=>{const a=wC(i),c=[Vr(i.scope.startsWith("block:")?i.scope.slice(6):void 0),Vr(a==null?void 0:a.oldPath),Vr(a==null?void 0:a.draftPath),Vr(a==null?void 0:a.newPath)].filter(h=>!!h),l=!!(n&&c.includes(n)),u=!!(r&&i.resourceRevision&&(i.resourceRevision===r||i.resourceRevision.startsWith(`${r}:`)));return l||u}).sort((i,a)=>a.updatedAt.localeCompare(i.updatedAt)||a.createdAt.localeCompare(i.createdAt))[0]}function wC(e){return e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:void 0}function Vr(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function kC(e,t=50){let n=0;return[...e].sort((r,o)=>o.updatedAt.localeCompare(r.updatedAt)||o.createdAt.localeCompare(r.createdAt)||o.id.localeCompare(r.id)).filter(r=>Ir(r)?(n+=1,n<=t):!0)}const ir=["local-operations"],pf=p.createContext(null);function CC({children:e}){const t=Yi(),n=p.useRef(new Set),r=p.useRef(new Set),o=Ge(l=>l.dispatch),i=Ri({queryKey:ir,queryFn:async()=>{const l=(await B.listOperations(50)).operations,u=t.getQueryData(ir)??[];return yC(u,l)},staleTime:15e3,refetchOnWindowFocus:!1,refetchInterval:1500}),a=i.data??[];p.useEffect(()=>{let l=!0,u,h;const d=()=>{h=new AbortController,Ep("/api/operations/events",f=>{if(f.event==="operation")try{const m=JSON.parse(f.data);t.setQueryData(ir,(S=[])=>eo(S,m))}catch{}},h.signal).catch(()=>{!l||h!=null&&h.signal.aborted||(u=setTimeout(d,5e3))})};return d(),()=>{l=!1,u&&clearTimeout(u),h==null||h.abort()}},[t]),p.useEffect(()=>{xC(r.current,a)},[a]),p.useEffect(()=>{let l=!0,u=!1;const h=async()=>{if(!(u||r.current.size===0)){u=!0;try{await vC(r.current,f=>B.getOperation(f),f=>{if(!l)return!1;t.setQueryData(ir,(m=[])=>eo(m,f))})}finally{u=!1}}};h();const d=window.setInterval(()=>void h(),1e3);return()=>{l=!1,window.clearInterval(d)}},[t]),p.useEffect(()=>{for(const l of SC(a,n.current)){const u=l.result;n.current.add(l.id),o({type:"RECONCILE_BLOCK_CERTIFICATION",outcome:u.outcome,oldPath:u.oldPath,draftPath:u.draftPath,newPath:u.newPath,payload:u.block}),window.dispatchEvent(new CustomEvent("dql:block-library-invalidated",{detail:{operationId:l.id,outcome:u.outcome}}))}},[o,a]);const c=p.useMemo(()=>({operations:a,activeCount:a.filter(l=>l.status==="queued"||l.status==="running").length,loading:i.isLoading,cancel:async l=>{const u=await B.cancelOperation(l);r.current.delete(l),t.setQueryData(ir,(h=[])=>eo(h,u))},track:l=>{Ir(l)?r.current.delete(l.id):r.current.add(l.id),t.setQueryData(ir,(u=[])=>eo(u,l))}}),[a,i.isLoading,t]);return s.jsx(pf.Provider,{value:c,children:e})}function jC(){const e=p.useContext(pf);if(!e)throw new Error("useOperations must be used inside OperationsProvider.");return e}const EC=new Set(["succeeded","failed","cancelled","interrupted"]);function TC(e,t=8){const n=AC(e).filter(o=>!EC.has(o.status)||o.type!=="project_refresh"),r=n.map(ff);return{operations:n.slice(0,t),activeCount:r.filter(o=>o.active).length,attentionCount:r.filter(o=>o.tone==="attention").length}}function AC(e){const t=e.filter(l=>l.type==="block_certification"),n=t.map((l,u)=>u),r=new Map,o=l=>{let u=l;for(;n[u]!==u;)n[u]=n[n[u]],u=n[u];return u},i=(l,u)=>{const h=o(l),d=o(u);h!==d&&(n[d]=h)};t.forEach((l,u)=>{for(const h of RC(l)){const d=r.get(h);d===void 0?r.set(h,u):i(u,d)}});const a=new Map;t.forEach((l,u)=>{const h=o(u),d=a.get(h);(!d||OC(l,d)<0)&&a.set(h,l)});const c=new Set([...a.values()].map(l=>l.id));return e.filter(l=>l.type!=="block_certification"||c.has(l.id))}function ff(e){var n,r,o,i,a,c;if(e.status==="queued"||e.status==="running")return{active:!0,tone:"active",statusLabel:e.status,message:e.message,guidance:e.type==="block_certification"?"You can change pages while certification continues.":void 0};if(e.type==="block_certification"&&e.status==="succeeded"){const l=e.result;if((l==null?void 0:l.outcome)==="draft_saved_with_blockers"){const u=((r=(n=l.checklist)==null?void 0:n.issues)==null?void 0:r.length)??((o=l.blockers)==null?void 0:o.length)??((i=l.checklist)==null?void 0:i.blockers.length)??0;return{active:!1,tone:"attention",statusLabel:"needs attention",message:u>0?`Draft saved with ${u} certification blocker${u===1?"":"s"}.`:"Draft saved, but certification requirements are not ready.",guidance:"Open Block Studio to review the exact fixes and retry."}}if((l==null?void 0:l.outcome)==="certified")return{active:!1,tone:"success",statusLabel:"certified",message:"The block passed its required gates and was certified."}}return e.status==="failed"||e.status==="interrupted"?{active:!1,tone:"failure",statusLabel:e.status,message:((a=e.error)==null?void 0:a.message)??e.message,guidance:e.type==="block_certification"?"The saved draft is preserved for review or retry.":void 0}:e.status==="cancelled"?{active:!1,tone:"neutral",statusLabel:"cancelled",message:e.message}:{active:!1,tone:e.status==="succeeded"?"success":"neutral",statusLabel:e.status,message:((c=e.error)==null?void 0:c.message)??e.message}}function RC(e){const t=hi(e.result),n=hi(t==null?void 0:t.block),r=hi(n==null?void 0:n.metadata),o=e.scope.startsWith("block:")?e.scope.slice(6):void 0;return Array.from(new Set([ar(n==null?void 0:n.path),ar(r==null?void 0:r.path),ar(t==null?void 0:t.oldPath),ar(t==null?void 0:t.draftPath),ar(t==null?void 0:t.newPath),ar(o)].filter(i=>!!i)))}function hi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ar(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function OC(e,t){return t.createdAt.localeCompare(e.createdAt)||t.updatedAt.localeCompare(e.updatedAt)||t.id.localeCompare(e.id)}function _C(){const e=Ge(d=>d.themeMode),t=Qe[e],{operations:n,loading:r,cancel:o}=jC(),[i,a]=p.useState(!1),c=p.useRef(null),{operations:l,activeCount:u,attentionCount:h}=TC(n);return p.useEffect(()=>{if(!i)return;const d=m=>{c.current&&!c.current.contains(m.target)&&a(!1)},f=m=>{m.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",d),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",f)}},[i]),!r&&l.length===0?null:s.jsxs("div",{ref:c,style:{position:"relative"},children:[s.jsxs("button",{type:"button","aria-label":"Background tasks","aria-expanded":i,onClick:()=>a(d=>!d),style:{height:28,padding:"0 9px",borderRadius:6,border:`1px solid ${u>0?t.accent:h>0?t.warning:t.btnBorder}`,background:i?t.btnHover:t.btnBg,color:t.textSecondary,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:6,fontFamily:t.font,fontSize:11,fontWeight:600},children:[s.jsx("span",{"aria-hidden":"true",style:{width:7,height:7,borderRadius:999,background:u>0?t.accent:h>0?t.warning:t.success,boxShadow:u>0?`0 0 0 3px ${t.accent}20`:"none"}}),u>0?`${u} running`:h>0?`${h} needs attention`:"Tasks"]}),i&&s.jsxs("div",{role:"dialog","aria-label":"Background tasks",style:{position:"absolute",top:34,right:0,zIndex:1200,width:340,maxHeight:420,overflowY:"auto",background:t.modalBg,border:`1px solid ${t.cellBorder}`,borderRadius:9,boxShadow:"0 14px 36px rgba(0,0,0,0.28)",padding:8},children:[s.jsx("div",{style:{padding:"4px 6px 8px",color:t.textPrimary,fontSize:12,fontWeight:700},children:"Background tasks"}),l.map(d=>{const f=ff(d),m=f.active,S=f.tone==="failure"?t.error:f.tone==="attention"?t.warning:f.tone==="success"?t.success:t.textMuted;return s.jsxs("div",{style:{padding:"9px 8px",borderTop:`1px solid ${t.headerBorder}`,display:"flex",flexDirection:"column",gap:6},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{style:{flex:1,color:t.textPrimary,fontSize:11.5,fontWeight:650},children:PC(d.type)}),s.jsx("span",{style:{color:S,fontSize:10},children:f.statusLabel})]}),s.jsx("div",{style:{color:f.tone==="failure"?t.error:f.tone==="attention"?t.warning:t.textSecondary,fontSize:10.5,lineHeight:1.4},children:f.message}),m&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("div",{style:{flex:1,height:3,borderRadius:99,overflow:"hidden",background:t.headerBorder},children:s.jsx("div",{style:{width:`${Math.max(3,d.progress)}%`,height:"100%",background:t.accent,transition:"width 180ms ease"}})}),d.cancellable&&s.jsx("button",{type:"button",onClick:()=>void o(d.id),style:{border:0,background:"transparent",color:t.textMuted,cursor:"pointer",fontSize:10,padding:0},children:"Cancel"})]}),d.type==="block_certification"&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:f.guidance??(f.tone==="success"?"Certification is complete.":"The saved draft is preserved for review or retry.")}),(d.type==="agent_run"||d.type==="app_ai_build")&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:m?"This continues while you work on another page.":d.status==="succeeded"?"Completed in the background.":"Open the original surface to review or retry."})]},d.id)})]})]})}function PC(e){return e==="block_certification"?"Block certification":e==="project_refresh"?"Project metadata refresh":e==="agent_run"?"AI request":e==="app_ai_build"?"App proposal":e.replace(/_/g," ")}const rs=new Map;function IC(e,t){let n=rs.get(e);n||(n={running:!1},rs.set(e,n));const r=n,o=new Promise((i,a)=>{r.pending?(r.pending.content=t,r.pending.waiters.push({resolve:i,reject:a})):r.pending={content:t,waiters:[{resolve:i,reject:a}]}});return r.running||(r.running=!0,(async()=>{for(;r.pending;){const i=r.pending;r.pending=void 0;try{await B.saveNotebook(e,i.content);for(const a of i.waiters)a.resolve()}catch(a){for(const c of i.waiters)c.reject(a)}}})().finally(()=>{r.running=!1,r.pending||rs.delete(e)})),o}function DC(e){const t=rs.get(e);return!!(t!=null&&t.running||t!=null&&t.pending)}function $C({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 MC(){var te;const e=Ge(Lr(F=>({activeBlockPath:F.activeBlockPath,activeFile:F.activeFile,appMode:F.appMode,autoSave:F.autoSave,blockStudioDirty:F.blockStudioDirty,blockStudioDraft:F.blockStudioDraft,blockStudioMetadata:F.blockStudioMetadata,cells:F.cells,files:F.files,mainView:F.mainView,notebookDirty:F.notebookDirty,notebookMetadata:F.notebookMetadata,notebookTitle:F.notebookTitle,savingFile:F.savingFile,themeMode:F.themeMode}))),t=jn(),n=Qe[e.themeMode],{executeAll:r}=uf(),[o,i]=p.useState(!1),[a,c]=p.useState(""),[l,u]=p.useState(!1),[h,d]=p.useState(!1),[f,m]=p.useState(!1),[S,v]=p.useState(!1),[b,w]=p.useState(!1),j=p.useRef(null),[C,x]=p.useState(!1),[E,P]=p.useState(!1),A=p.useRef(null),g=p.useRef(null),I=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,T=e.mainView==="notebook",O=e.mainView==="notebook"||e.mainView==="block_studio",_=O&&!!e.activeFile,M={home:"Home",business_artifact:((te=e.activeFile)==null?void 0:te.name.replace(/\.(dqlnb|dql)$/i,""))??"Business Definition",lineage:"Lineage",lineage_detail:"Lineage",connection:"Settings",apps:"Apps",git:"Source control",settings:"Settings",imports:"Import SQL",domains:"Modeling",modeling:"Modeling"},q=O?e.activeFile?e.notebookTitle||"Untitled":e.mainView==="block_studio"?"Blocks":"Notebooks":M[e.mainView]??"DQL Workbench";p.useEffect(()=>{o&&g.current&&(g.current.focus(),g.current.select())},[o]),p.useEffect(()=>{if(!E)return;function F(K){A.current&&!A.current.contains(K.target)&&P(!1)}return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[E]);const G=()=>{c(e.notebookTitle),i(!0)},J=()=>{i(!1),a.trim()&&a!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:a.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:J1(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},H=p.useCallback(async()=>{var K,oe,ee;const F=In.getState();if(F.activeFile){t({type:"SET_SAVING",saving:!0});try{if(F.mainView==="block_studio"){if(!F.blockStudioMetadata)return;const ce=await B.saveBlockStudio({path:F.activeBlockPath,source:F.blockStudioDraft,metadata:{name:F.blockStudioMetadata.name,domain:F.blockStudioMetadata.domain,folderPath:F.blockStudioMetadata.folderPath,description:F.blockStudioMetadata.description,owner:F.blockStudioMetadata.owner,tags:F.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"},payload:ce}),F.files.some(ke=>ke.path===ce.path)||t({type:"FILE_ADDED",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"}})}else{const ce=F.activeFile,ke=F.cells,xe=F.notebookTitle,De=F.notebookMetadata,We=ce.type==="block"?((K=ke[0])==null?void 0:K.content)??"":L1(xe,ke,De);await IC(ce.path,We);const Be=In.getState();((oe=Be.activeFile)==null?void 0:oe.path)===ce.path&&Be.cells===ke&&Be.notebookTitle===xe&&Be.notebookMetadata===De&&t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}u(!0),setTimeout(()=>u(!1),2e3)}catch(ce){console.error("Save failed:",ce)}finally{const ce=(ee=In.getState().activeFile)==null?void 0:ee.path;(!ce||!DC(ce))&&t({type:"SET_SAVING",saving:!1})}}},[t]);p.useEffect(()=>{const F=K=>{(K.metaKey||K.ctrlKey)&&K.key==="s"&&(K.preventDefault(),H())};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[H]),p.useEffect(()=>{if(!e.autoSave||!I||!e.activeFile||e.mainView==="block_studio")return;const F=setTimeout(()=>{H()},750);return()=>clearTimeout(F)},[e.autoSave,I,e.activeFile,e.cells,e.blockStudioDraft,H]);const L=[{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,X=L.find(F=>F.mode===$)??L[0];p.useEffect(()=>{if(!b)return;const F=oe=>{j.current&&!j.current.contains(oe.target)&&w(!1)},K=oe=>{oe.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",F),document.addEventListener("keydown",K),()=>{document.removeEventListener("mousedown",F),document.removeEventListener("keydown",K)}},[b]);const W={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($C,{t:n}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&O&&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&&O?o?s.jsx("input",{ref:g,value:a,onChange:F=>c(F.target.value),onBlur:J,onKeyDown:F=>{F.key==="Enter"&&J(),F.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:G,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:[q,I&&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:q||"DQL Workbench"})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx(_C,{}),e.appMode==="studio"&&_&&e.mainView!=="block_studio"&&s.jsx(s.Fragment,{children:s.jsxs("button",{onClick:T?r:void 0,disabled:!e.activeFile||!T,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{...W,height:30,padding:"0 14px",borderRadius:999,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!T?.4:h?.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:j,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>w(F=>!F),onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),title:`Theme: ${X.label}`,"aria-haspopup":"true","aria-expanded":b,style:{...W,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:X.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:X.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:L.map(F=>{const K=F.mode===$;return s.jsxs("button",{role:"menuitemradio","aria-checked":K,onClick:()=>{t({type:"SET_THEME",mode:F.mode}),w(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",background:K?n.btnHover:"transparent",color:n.textPrimary,cursor:"pointer",borderRadius:4,fontSize:12,fontFamily:n.font,textAlign:"left"},onMouseEnter:oe=>{K||(oe.currentTarget.style.background=n.btnHover)},onMouseLeave:oe=>{K||(oe.currentTarget.style.background="transparent")},children:[s.jsx("span",{style:{width:14,height:14,borderRadius:3,background:F.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{flex:1},children:F.label}),K&&s.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},F.mode)})})]}),e.appMode==="studio"&&_&&e.mainView!=="block_studio"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:H,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),title:"Save (Cmd+S)",style:{...W,background:f&&e.activeFile?n.btnHover:n.btnBg,color:l?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?s.jsxs(s.Fragment,{children:[s.jsx(NC,{}),"Saving…"]}):l?s.jsx(s.Fragment,{children:"✓ Saved"}):s.jsx(s.Fragment,{children:"Save"})}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),_&&e.mainView!=="block_studio"&&s.jsxs("div",{ref:A,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>{e.activeFile&&P(F=>!F)},disabled:!e.activeFile,onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),title:"Share / export",style:{...W,height:30,padding:"0 14px",borderRadius:999,background:(C||E)&&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"})})]}),E&&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(LC,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{hC(e.notebookTitle||"dashboard",e.cells),P(!1)}})})]})]})]})}function LC({label:e,description:t,t:n,onClick:r}){const[o,i]=p.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 NC(){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 BC(e){return e.toTimeString().slice(0,8)}function FC(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function zC(){const{state:e,dispatch:t}=et(),n=Qe[e.themeMode],[r,o]=p.useState(!1),i=e.queryLog.filter(c=>c.error),a=c=>t({type:"SET_DEV_PANEL_TAB",tab:c});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(c=>s.jsx(qC,{label:c==="errors"?`Errors${i.length>0?` (${i.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===c,onClick:()=>a(c),t:n},c)),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(Bl,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(c=>s.jsx(Fl,{entry:c,t:n},c.id))),e.devPanelTab==="errors"&&(i.length===0?s.jsx(Bl,{t:n,message:"No errors."}):[...i].reverse().map(c=>s.jsx(Fl,{entry:c,t:n},c.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 qC({label:e,active:t,onClick:n,t:r}){const[o,i]=p.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 Bl({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 Fl({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:BC(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:FC(e.time)})]})]})}function UC(){const{state:e,dispatch:t}=et(),{executeAll:n}=uf();p.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 WC=600;function KC(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 zl(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 VC(){var o;const{state:e}=et(),t=p.useRef(null),n=p.useRef(""),r=p.useRef(null);p.useEffect(()=>{var c;const i=((c=e.activeFile)==null?void 0:c.path)??null;if(!i)return;if(i!==r.current){r.current=i,n.current=zl(e.cells);return}const a=zl(e.cells);return a!==n.current&&(n.current=a,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const l=KC(i,e.cells);B.saveRunSnapshot(i,l).catch(()=>{})},WC)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}const hE="core";function HC(e){var n;const t=e==null?void 0:e.trim();if(t)return((n=t.split("::").at(-1))==null?void 0:n.trim())||void 0}const GC=[{items:[{id:"diagram",label:"Modeling"},{id:"skills",label:"Skills"},{id:"blocks",label:"Blocks"},{id:"notebooks",label:"Notebooks"},{id:"apps",label:"Apps"}]}],QC=new Set(GC.flatMap(e=>e.items.map(t=>t.id)));function hf(e){return e!==null&&QC.has(e)}function mE(e,t){const n=new URL(e);return t.domain?n.searchParams.set("domain",t.domain):n.searchParams.delete("domain"),n.searchParams.set("domainSection",t.section),t.modelAreaId?n.searchParams.set("modelArea",t.modelAreaId):n.searchParams.delete("modelArea"),t.selectedId?n.searchParams.set("domainObject",t.selectedId):n.searchParams.delete("domainObject"),`${n.pathname}${n.search}${n.hash}`}function JC(e){const t=new URL(e);for(const n of mf)t.searchParams.delete(n);return`${t.pathname}${t.search}${t.hash}`}const mf=["domain","domainSection","modelArea","domainObject"],gE="dql.domain-studio.location";function yE(e,t){const n=new URL(e).searchParams;if(mf.some(r=>n.has(r))){const r=n.get("domainSection"),o=hf(r)?r:"diagram";return{domain:n.get("domain"),section:o,modelAreaId:n.get("modelArea"),selectedId:r==="diagram"?n.get("domainObject"):null}}return YC(t)}function YC(e){const t={domain:null,section:"diagram",modelAreaId:null,selectedId:null};if(!e)return t;try{const n=JSON.parse(e),r=typeof n.section=="string"&&hf(n.section)?n.section:"diagram",o=i=>typeof i=="string"&&i.trim()?i:null;return{domain:o(n.domain),section:r,modelAreaId:o(n.modelAreaId),selectedId:o(n.selectedId)}}catch{return t}}function bE(e){return`modeling:${e??"all"}`}function xE(e){const t=Object.values(e),n=new Map;for(const a of t){const c=a.parent&&e[a.parent]?a.parent:void 0;n.set(c,[...n.get(c)??[],a])}for(const a of n.values())a.sort((c,l)=>c.id.localeCompare(l.id));const r=[],o=new Set,i=(a,c)=>{for(const l of n.get(a)??[])o.has(l.id)||(o.add(l.id),r.push({id:l.id,parent:l.parent,depth:c,label:c===0?l.id:`${"— ".repeat(c)}${l.id.split(".").at(-1)??l.id}`}),i(l.id,c+1))};i(void 0,0);for(const a of t.sort((c,l)=>c.id.localeCompare(l.id)))o.has(a.id)||r.push({id:a.id,parent:a.parent,depth:0,label:a.id});return r}function vE(e){const t=(e??"").toLowerCase();return t==="dimension"?"var(--status-success)":t==="bridge"?"var(--status-warning)":t==="event"||t==="snapshot"?"var(--accent)":"var(--text-tertiary)"}function gf(e){return Object.entries(e.entities).map(([t,n])=>({recordKey:t,entity:n}))}function SE(e,t){if(e.entities[t])return t;const n=gf(e).filter(({entity:r})=>r.id===t||r.qualifiedId===t);return n.length===1?n[0].recordKey:void 0}function wE(e,t){return gf(e).filter(({entity:n})=>!t||n.domain===t)}function kE(e,t,n){if(e.operation==="upsert_entity"){if(!t)return!1;const r=e.value;return r.dbtModel===t.dbtUniqueId&&(r.grain??void 0)===(t.grain??void 0)&&JSON.stringify(r.keys??[])===JSON.stringify(t.keys??[])&&(r.status??t.status)===t.status&&(r.areaId??void 0)===HC(t.areaId)&&r.domain===t.domain}return e.operation==="upsert_area"?!!n&&e.value.domain===n.domain&&e.value.id===n.localId:!1}const XC=p.lazy(()=>_e(()=>import("./HomePage-eIkfBIep.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.HomePage}))),ZC=p.lazy(()=>_e(()=>import("./AnalyticsHome-D5P6Ujwi.js"),__vite__mapDeps([7,8,9,10,1,11,12,3,13,14,15,16,17,2,18,6])).then(e=>({default:e.AnalyticsHome}))),ej=p.lazy(()=>_e(()=>import("./GlobalAiRail-CVECf6Xj.js"),__vite__mapDeps([19,9,10,1,11,12,3,13,14,15,16,17,2,20,6])).then(e=>({default:e.GlobalAiRail}))),tj=p.lazy(()=>_e(()=>import("./NotebookEditor-DjqJS44s.js"),__vite__mapDeps([21,4,2,5,22,23,24,10,1,11,12,3,13,14,9,15,16,17,8,25,26,6,27,28,20,29])).then(e=>({default:e.NotebookEditor}))),nj=p.lazy(()=>_e(()=>import("./NewNotebookModal-5Vp6XiuK.js"),__vite__mapDeps([30,4,15,6])).then(e=>({default:e.NewNotebookModal}))),rj=p.lazy(()=>_e(()=>import("./NewBlockModal-DbCQg-pj.js"),__vite__mapDeps([31,6])).then(e=>({default:e.NewBlockModal}))),oj=p.lazy(()=>_e(()=>import("./SetupOnboarding-BfS9Tdx-.js"),__vite__mapDeps([32,33,2,6])).then(e=>({default:e.SetupOnboarding}))),sj=p.lazy(()=>_e(()=>import("./BlockStudio-B4ap0GdY.js"),__vite__mapDeps([34,22,23,10,1,11,12,3,13,14,25,26,6,27,9,15,16,17,2,20,35,36])).then(e=>({default:e.BlockStudio}))),ij=p.lazy(()=>_e(()=>import("./BusinessArtifactView-BIfNI-0S.js"),__vite__mapDeps([37,25,26,6,27])).then(e=>({default:e.BusinessArtifactView}))),aj=p.lazy(()=>_e(()=>import("./LineageDetailView-DJZZjZu-.js"),__vite__mapDeps([38,25,26,6,27,39,33,16])).then(e=>({default:e.LineageDetailView}))),cj=p.lazy(()=>_e(()=>import("./LineageDAG-CSqcbDrE.js"),__vite__mapDeps([39,26,6,27])).then(e=>({default:e.LineageDAG}))),lj=p.lazy(()=>_e(()=>import("./HelpDocsPage-D8hLS5lE.js"),__vite__mapDeps([40,6])).then(e=>({default:e.HelpDocsPage}))),dj=p.lazy(()=>_e(()=>Promise.resolve().then(()=>i1),void 0).then(e=>({default:e.ConnectionPanel}))),uj=p.lazy(()=>_e(()=>import("./GitPage-lQb1uXH2.js"),__vite__mapDeps([41,42,15,6])).then(e=>({default:e.GitPage}))),pj=p.lazy(()=>_e(()=>import("./ReadinessPage-BHGrC5ho.js"),__vite__mapDeps([43,1,44,45,12,3,2,6])).then(e=>({default:e.ReadinessPage}))),fj=p.lazy(()=>_e(()=>import("./AgentLogPage-BPz-UWFh.js"),__vite__mapDeps([46,33,14,47,6])).then(e=>({default:e.AgentLogPage}))),hj=p.lazy(()=>_e(()=>import("./GovernedContextPage-trOyMCY6.js"),__vite__mapDeps([48,3,12,9,10,1,11,13,14,15,16,17,2,49,6])).then(e=>({default:e.GovernedContextPage}))),mj=p.lazy(()=>_e(()=>import("./DbtFirstModelingPage-D72byb2g.js"),__vite__mapDeps([50,49,9,10,1,11,12,3,13,14,15,16,17,2,26,6,27,28,29,36,51,47])).then(e=>({default:e.DbtFirstModelingPage}))),gj=p.lazy(()=>_e(()=>import("./AppsView-DQOwU9Cg.js"),__vite__mapDeps([52,20,17,10,1,11,12,3,13,14,15,33,35,29,4,5,24,8,45,53,51,2,18,6])).then(e=>({default:e.AppsView}))),yj=p.lazy(()=>_e(()=>import("./LineageDrawer-BcIipIc3.js"),__vite__mapDeps([54,25,26,6,27,36,15,17,13,53,42])).then(e=>({default:e.LineageDrawer}))),bj=p.lazy(()=>_e(()=>import("./AiBuildDialog-BEl53WA_.js"),__vite__mapDeps([55,44,11,12,3,13,15,6])).then(e=>({default:e.AiBuildDialog})));function xj(){const e=Ge(Lr(d=>({appMode:d.appMode,dashboardMode:d.dashboardMode,globalAi:d.globalAi,inspectorOpen:d.inspectorOpen,lineageDrawerOpen:d.lineageDrawerOpen,lineageFullscreen:d.lineageFullscreen,mainView:d.mainView,newBlockModalOpen:d.newBlockModalOpen,newNotebookModalOpen:d.newNotebookModalOpen,setupOpen:d.setupOpen,sidebarOpen:d.sidebarOpen,sidebarPanel:d.sidebarPanel,themeMode:d.themeMode}))),t=jn(),n=Qe[e.themeMode],r=p.useRef({}),o=e.mainView==="block_studio"||e.mainView==="imports",[i,a]=p.useState(!1),[c,l]=p.useState(null);p.useEffect(()=>{let d=!0;return B.getSetupLaunch().then(f=>{d&&(l(f),f.shouldOpen&&t({type:"OPEN_SETUP"}))}).catch(()=>{}),()=>{d=!1}},[t]),p.useEffect(()=>{const d=()=>t({type:"SET_MAIN_VIEW",view:"modeling"});return window.addEventListener("dql:open-context-proposal",d),()=>window.removeEventListener("dql:open-context-proposal",d)},[t]),p.useEffect(()=>{if(e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills")return;const d=JC(window.location.href),f=`${window.location.pathname}${window.location.search}${window.location.hash}`;d!==f&&window.history.replaceState(window.history.state,"",d)},[e.mainView]),UC(),VC(),p.useEffect(()=>{const d=f=>{(f.metaKey||f.ctrlKey)&&f.key.toLowerCase()==="k"&&!f.shiftKey&&(f.preventDefault(),a(m=>!m)),(f.metaKey||f.ctrlKey)&&f.shiftKey&&f.key.toLowerCase()==="i"&&(f.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);const u=p.useCallback(async d=>{try{if(d.type==="term"||d.type==="business_view"){e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"}),t({type:"OPEN_BUSINESS_ARTIFACT",file:d});return}if(d.type==="block"){const j=await B.openBlockStudio(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:j});return}const{content:f}=await B.readNotebook(d.path),{title:m,cells:S,metadata:v}=N1(d.path,f),b=d.path.endsWith(".dqlnb")?await B.fetchRunSnapshot(d.path):null;let w=S;if(b!=null&&b.found&&b.snapshot){const j=new Map(b.snapshot.cells.map(C=>[C.cellId,C]));w=S.map(C=>{const x=j.get(C.id);return x?{...C,status:x.status??C.status,result:x.result??C.result,error:x.error??C.error,executionCount:x.executionCount??C.executionCount,execution:x.execution??C.execution,fromSnapshot:x.result!=null}:C})}t({type:"OPEN_FILE",file:d,cells:w,title:m,metadata:v}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(f){if(console.error("Failed to open file:",f),d.type==="block")try{const{content:m}=await B.readNotebook(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:{path:d.path,source:m,companionPath:null,metadata:{name:d.name.replace(/\.dql$/i,""),path:d.path,domain:d.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(m){console.error("Failed to open block fallback:",m)}else t({type:"OPEN_FILE",file:d,cells:[Ra("sql")],title:d.name})}},[t,e.sidebarPanel]);p.useCallback(d=>{const f=r.current[d];f&&f.scrollIntoView({behavior:"smooth",block:"start"})},[]);const h=p.useCallback((d,f)=>{f?r.current[d]=f:delete r.current[d]},[]);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(MC,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(Ww,{}),e.appMode==="studio"&&e.sidebarOpen&&!o&&s.jsx(_1,{onOpenFile:u}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:s.jsx(p.Suspense,{fallback:s.jsx(vj,{t:n}),children:e.mainView==="home"?s.jsx(XC,{}):e.mainView==="ask"?s.jsx(ZC,{}):e.mainView==="business_artifact"?s.jsx(ij,{}):e.mainView==="lineage"?s.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s.jsx(cj,{})}):e.mainView==="lineage_detail"?s.jsx(aj,{}):e.mainView==="help"?s.jsx(lj,{}):e.mainView==="connection"||e.mainView==="settings"?s.jsx(wj,{children:s.jsx(dj,{variant:"page"})}):e.mainView==="git"?s.jsx(uj,{}):e.mainView==="readiness"?s.jsx(pj,{}):e.mainView==="skills"?s.jsx(hj,{initialTab:"skills"}):e.mainView==="domains"||e.mainView==="modeling"?s.jsx(mj,{}):e.mainView==="apps"?s.jsx(gj,{}):e.mainView==="agent_log"?s.jsx(kj,{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(fj,{})}):s.jsx(s.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?s.jsx(sj,{},"block-editor"):s.jsxs(s.Fragment,{children:[s.jsx(tj,{onOpenFile:u,registerCellRef:h}),e.appMode==="studio"&&s.jsx(zC,{})]})})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(yj,{})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(Pw,{}),e.globalAi.open&&e.mainView==="apps"&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(ej,{})})]}),e.newNotebookModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(nj,{onFileOpened:u})}),e.newBlockModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(rj,{onFileOpened:u})}),s.jsx(ZS,{open:i,onClose:()=>a(!1)}),s.jsx(p.Suspense,{fallback:null,children:s.jsx(bj,{})}),e.setupOpen&&s.jsx(p.Suspense,{fallback:s.jsx(Sj,{t:n}),children:s.jsx(oj,{launch:c!=null&&c.shouldOpen?c:void 0,onAcknowledged:()=>l(d=>d&&{...d,shouldOpen:!1,reason:null})})})]})}function vj({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 Sj({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 wj({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 kj({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 Cj(){const e=jn(),t=Yi(),n=p.useRef(null);p.useEffect(()=>{let r=!0,o=null,i=null,a=null,c=null;const l=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,B.listNotebooks().then(f=>{r&&(t.setQueryData(["notebooks"],f),e({type:"SET_FILES",files:f}))}).catch(()=>{})},150)},u=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,B.getDomains().then(({domains:f})=>{r&&(t.setQueryData(["authored-domains"],{domains:f}),e({type:"SET_AUTHORED_DOMAINS",domains:f}))}).catch(()=>{})},150)},h=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null,e({type:"SET_SEMANTIC_LOADING",loading:!0}),B.getSemanticLayer().then(f=>{r&&(t.setQueryData(["semantic-layer"],f),e({type:"SET_SEMANTIC_LAYER",layer:f}))}).catch(()=>{})},100)},d=()=>{if(!r)return;const f=new AbortController;n.current=f,Ep("/api/watch",m=>{if(m.event==="change")try{const S=JSON.parse(m.data);if(S.type==="file-added"||S.type==="file-deleted"||S.type==="file-changed"){const v=S.path??"";/^(?:notebooks|workbooks|blocks|skills|apps|dashboards)\//.test(v)&&l(),v.startsWith("domains/")&&(l(),u())}S.type==="semantic-reload"&&h()}catch{}},f.signal).catch(()=>{!r||f.signal.aborted||(o&&clearTimeout(o),o=setTimeout(d,5e3))})};return d(),()=>{var f;r=!1,o&&clearTimeout(o),i&&clearTimeout(i),a&&clearTimeout(a),c&&clearTimeout(c),(f=n.current)==null||f.abort(),n.current=null}},[e,t])}const jj=new ah({defaultOptions:{queries:{staleTime:15e3,gcTime:5*6e4,retry:1,refetchOnWindowFocus:!1}}});function Ej(){const e=Ge(i=>i.themeMode),t=Ge(i=>i.dispatch),n=Qe[e];p.useEffect(()=>{const i="dql-global-styles";let a=document.getElementById(i);a||(a=document.createElement("style"),a.id=i,document.head.appendChild(a)),a.textContent=`
610
+ </html>`}function mC(e,t){const n=hC(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)}const gC=new Set(["succeeded","failed","cancelled","interrupted"]);function Ir(e){return gC.has(e.status)}function yC(e,t){if(e.id!==t.id)return t;const n=Ir(e),r=Ir(t);return n&&!r||t.updatedAt<e.updatedAt?e:t.updatedAt>e.updatedAt?t:n!==r?r?t:e:t.progress!==e.progress?t.progress>e.progress?t:e:t}function eo(e,t){const n=e.find(o=>o.id===t.id),r=n?yC(n,t):t;return CC([...e.filter(o=>o.id!==t.id),r])}function bC(e,t){return t.reduce(eo,e)}function xC(e){return e.filter(t=>!Ir(t)).map(t=>t.id)}function vC(e,t){for(const n of xC(t))e.add(n)}async function SC(e,t,n){await Promise.all([...e].map(async r=>{try{const o=await t(r);if(n(o)===!1)return;Ir(o)&&e.delete(r)}catch{}}))}function wC(e,t=new Set){return e.filter(n=>n.type==="block_certification"&&n.status==="succeeded").filter(n=>!t.has(n.id)).filter(n=>{const r=n.result;return!!(r!=null&&r.block&&r.outcome)}).sort((n,r)=>n.updatedAt.localeCompare(r.updatedAt)||n.createdAt.localeCompare(r.createdAt)||n.id.localeCompare(r.id))}function hE(e,t){var o;if(t.operationId){const i=e.find(a=>a.type==="block_certification"&&a.id===t.operationId);if(i)return i}const n=Vr(t.activePath),r=(o=t.sourceFingerprint)==null?void 0:o.trim();return e.filter(i=>i.type==="block_certification").filter(i=>{const a=kC(i),c=[Vr(i.scope.startsWith("block:")?i.scope.slice(6):void 0),Vr(a==null?void 0:a.oldPath),Vr(a==null?void 0:a.draftPath),Vr(a==null?void 0:a.newPath)].filter(h=>!!h),l=!!(n&&c.includes(n)),u=!!(r&&i.resourceRevision&&(i.resourceRevision===r||i.resourceRevision.startsWith(`${r}:`)));return l||u}).sort((i,a)=>a.updatedAt.localeCompare(i.updatedAt)||a.createdAt.localeCompare(i.createdAt))[0]}function kC(e){return e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:void 0}function Vr(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function CC(e,t=50){let n=0;return[...e].sort((r,o)=>o.updatedAt.localeCompare(r.updatedAt)||o.createdAt.localeCompare(r.createdAt)||o.id.localeCompare(r.id)).filter(r=>Ir(r)?(n+=1,n<=t):!0)}const ir=["local-operations"],ff=p.createContext(null);function jC({children:e}){const t=Yi(),n=p.useRef(new Set),r=p.useRef(new Set),o=Ge(l=>l.dispatch),i=Ri({queryKey:ir,queryFn:async()=>{const l=(await B.listOperations(50)).operations,u=t.getQueryData(ir)??[];return bC(u,l)},staleTime:15e3,refetchOnWindowFocus:!1,refetchInterval:1500}),a=i.data??[];p.useEffect(()=>{let l=!0,u,h;const d=()=>{h=new AbortController,Tp("/api/operations/events",f=>{if(f.event==="operation")try{const m=JSON.parse(f.data);t.setQueryData(ir,(S=[])=>eo(S,m))}catch{}},h.signal).catch(()=>{!l||h!=null&&h.signal.aborted||(u=setTimeout(d,5e3))})};return d(),()=>{l=!1,u&&clearTimeout(u),h==null||h.abort()}},[t]),p.useEffect(()=>{vC(r.current,a)},[a]),p.useEffect(()=>{let l=!0,u=!1;const h=async()=>{if(!(u||r.current.size===0)){u=!0;try{await SC(r.current,f=>B.getOperation(f),f=>{if(!l)return!1;t.setQueryData(ir,(m=[])=>eo(m,f))})}finally{u=!1}}};h();const d=window.setInterval(()=>void h(),1e3);return()=>{l=!1,window.clearInterval(d)}},[t]),p.useEffect(()=>{for(const l of wC(a,n.current)){const u=l.result;n.current.add(l.id),o({type:"RECONCILE_BLOCK_CERTIFICATION",outcome:u.outcome,oldPath:u.oldPath,draftPath:u.draftPath,newPath:u.newPath,payload:u.block}),window.dispatchEvent(new CustomEvent("dql:block-library-invalidated",{detail:{operationId:l.id,outcome:u.outcome}}))}},[o,a]);const c=p.useMemo(()=>({operations:a,activeCount:a.filter(l=>l.status==="queued"||l.status==="running").length,loading:i.isLoading,cancel:async l=>{const u=await B.cancelOperation(l);r.current.delete(l),t.setQueryData(ir,(h=[])=>eo(h,u))},track:l=>{Ir(l)?r.current.delete(l.id):r.current.add(l.id),t.setQueryData(ir,(u=[])=>eo(u,l))}}),[a,i.isLoading,t]);return s.jsx(ff.Provider,{value:c,children:e})}function EC(){const e=p.useContext(ff);if(!e)throw new Error("useOperations must be used inside OperationsProvider.");return e}const TC=new Set(["succeeded","failed","cancelled","interrupted"]);function AC(e,t=8){const n=RC(e).filter(o=>!TC.has(o.status)||o.type!=="project_refresh"),r=n.map(hf);return{operations:n.slice(0,t),activeCount:r.filter(o=>o.active).length,attentionCount:r.filter(o=>o.tone==="attention").length}}function RC(e){const t=e.filter(l=>l.type==="block_certification"),n=t.map((l,u)=>u),r=new Map,o=l=>{let u=l;for(;n[u]!==u;)n[u]=n[n[u]],u=n[u];return u},i=(l,u)=>{const h=o(l),d=o(u);h!==d&&(n[d]=h)};t.forEach((l,u)=>{for(const h of OC(l)){const d=r.get(h);d===void 0?r.set(h,u):i(u,d)}});const a=new Map;t.forEach((l,u)=>{const h=o(u),d=a.get(h);(!d||_C(l,d)<0)&&a.set(h,l)});const c=new Set([...a.values()].map(l=>l.id));return e.filter(l=>l.type!=="block_certification"||c.has(l.id))}function hf(e){var n,r,o,i,a,c;if(e.status==="queued"||e.status==="running")return{active:!0,tone:"active",statusLabel:e.status,message:e.message,guidance:e.type==="block_certification"?"You can change pages while certification continues.":void 0};if(e.type==="block_certification"&&e.status==="succeeded"){const l=e.result;if((l==null?void 0:l.outcome)==="draft_saved_with_blockers"){const u=((r=(n=l.checklist)==null?void 0:n.issues)==null?void 0:r.length)??((o=l.blockers)==null?void 0:o.length)??((i=l.checklist)==null?void 0:i.blockers.length)??0;return{active:!1,tone:"attention",statusLabel:"needs attention",message:u>0?`Draft saved with ${u} certification blocker${u===1?"":"s"}.`:"Draft saved, but certification requirements are not ready.",guidance:"Open Block Studio to review the exact fixes and retry."}}if((l==null?void 0:l.outcome)==="certified")return{active:!1,tone:"success",statusLabel:"certified",message:"The block passed its required gates and was certified."}}return e.status==="failed"||e.status==="interrupted"?{active:!1,tone:"failure",statusLabel:e.status,message:((a=e.error)==null?void 0:a.message)??e.message,guidance:e.type==="block_certification"?"The saved draft is preserved for review or retry.":void 0}:e.status==="cancelled"?{active:!1,tone:"neutral",statusLabel:"cancelled",message:e.message}:{active:!1,tone:e.status==="succeeded"?"success":"neutral",statusLabel:e.status,message:((c=e.error)==null?void 0:c.message)??e.message}}function OC(e){const t=hi(e.result),n=hi(t==null?void 0:t.block),r=hi(n==null?void 0:n.metadata),o=e.scope.startsWith("block:")?e.scope.slice(6):void 0;return Array.from(new Set([ar(n==null?void 0:n.path),ar(r==null?void 0:r.path),ar(t==null?void 0:t.oldPath),ar(t==null?void 0:t.draftPath),ar(t==null?void 0:t.newPath),ar(o)].filter(i=>!!i)))}function hi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ar(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function _C(e,t){return t.createdAt.localeCompare(e.createdAt)||t.updatedAt.localeCompare(e.updatedAt)||t.id.localeCompare(e.id)}function PC(){const e=Ge(d=>d.themeMode),t=Qe[e],{operations:n,loading:r,cancel:o}=EC(),[i,a]=p.useState(!1),c=p.useRef(null),{operations:l,activeCount:u,attentionCount:h}=AC(n);return p.useEffect(()=>{if(!i)return;const d=m=>{c.current&&!c.current.contains(m.target)&&a(!1)},f=m=>{m.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",d),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",f)}},[i]),!r&&l.length===0?null:s.jsxs("div",{ref:c,style:{position:"relative"},children:[s.jsxs("button",{type:"button","aria-label":"Background tasks","aria-expanded":i,onClick:()=>a(d=>!d),style:{height:28,padding:"0 9px",borderRadius:6,border:`1px solid ${u>0?t.accent:h>0?t.warning:t.btnBorder}`,background:i?t.btnHover:t.btnBg,color:t.textSecondary,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:6,fontFamily:t.font,fontSize:11,fontWeight:600},children:[s.jsx("span",{"aria-hidden":"true",style:{width:7,height:7,borderRadius:999,background:u>0?t.accent:h>0?t.warning:t.success,boxShadow:u>0?`0 0 0 3px ${t.accent}20`:"none"}}),u>0?`${u} running`:h>0?`${h} needs attention`:"Tasks"]}),i&&s.jsxs("div",{role:"dialog","aria-label":"Background tasks",style:{position:"absolute",top:34,right:0,zIndex:1200,width:340,maxHeight:420,overflowY:"auto",background:t.modalBg,border:`1px solid ${t.cellBorder}`,borderRadius:9,boxShadow:"0 14px 36px rgba(0,0,0,0.28)",padding:8},children:[s.jsx("div",{style:{padding:"4px 6px 8px",color:t.textPrimary,fontSize:12,fontWeight:700},children:"Background tasks"}),l.map(d=>{const f=hf(d),m=f.active,S=f.tone==="failure"?t.error:f.tone==="attention"?t.warning:f.tone==="success"?t.success:t.textMuted;return s.jsxs("div",{style:{padding:"9px 8px",borderTop:`1px solid ${t.headerBorder}`,display:"flex",flexDirection:"column",gap:6},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{style:{flex:1,color:t.textPrimary,fontSize:11.5,fontWeight:650},children:IC(d.type)}),s.jsx("span",{style:{color:S,fontSize:10},children:f.statusLabel})]}),s.jsx("div",{style:{color:f.tone==="failure"?t.error:f.tone==="attention"?t.warning:t.textSecondary,fontSize:10.5,lineHeight:1.4},children:f.message}),m&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("div",{style:{flex:1,height:3,borderRadius:99,overflow:"hidden",background:t.headerBorder},children:s.jsx("div",{style:{width:`${Math.max(3,d.progress)}%`,height:"100%",background:t.accent,transition:"width 180ms ease"}})}),d.cancellable&&s.jsx("button",{type:"button",onClick:()=>void o(d.id),style:{border:0,background:"transparent",color:t.textMuted,cursor:"pointer",fontSize:10,padding:0},children:"Cancel"})]}),d.type==="block_certification"&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:f.guidance??(f.tone==="success"?"Certification is complete.":"The saved draft is preserved for review or retry.")}),(d.type==="agent_run"||d.type==="app_ai_build")&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:m?"This continues while you work on another page.":d.status==="succeeded"?"Completed in the background.":"Open the original surface to review or retry."})]},d.id)})]})]})}function IC(e){return e==="block_certification"?"Block certification":e==="project_refresh"?"Project metadata refresh":e==="agent_run"?"AI request":e==="app_ai_build"?"App proposal":e.replace(/_/g," ")}const rs=new Map;function DC(e,t){let n=rs.get(e);n||(n={running:!1},rs.set(e,n));const r=n,o=new Promise((i,a)=>{r.pending?(r.pending.content=t,r.pending.waiters.push({resolve:i,reject:a})):r.pending={content:t,waiters:[{resolve:i,reject:a}]}});return r.running||(r.running=!0,(async()=>{for(;r.pending;){const i=r.pending;r.pending=void 0;try{await B.saveNotebook(e,i.content);for(const a of i.waiters)a.resolve()}catch(a){for(const c of i.waiters)c.reject(a)}}})().finally(()=>{r.running=!1,r.pending||rs.delete(e)})),o}function $C(e){const t=rs.get(e);return!!(t!=null&&t.running||t!=null&&t.pending)}function MC({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 LC(){var te;const e=Ge(Lr(F=>({activeBlockPath:F.activeBlockPath,activeFile:F.activeFile,appMode:F.appMode,autoSave:F.autoSave,blockStudioDirty:F.blockStudioDirty,blockStudioDraft:F.blockStudioDraft,blockStudioMetadata:F.blockStudioMetadata,cells:F.cells,files:F.files,mainView:F.mainView,notebookDirty:F.notebookDirty,notebookMetadata:F.notebookMetadata,notebookTitle:F.notebookTitle,savingFile:F.savingFile,themeMode:F.themeMode}))),t=jn(),n=Qe[e.themeMode],{executeAll:r}=pf(),[o,i]=p.useState(!1),[a,c]=p.useState(""),[l,u]=p.useState(!1),[h,d]=p.useState(!1),[f,m]=p.useState(!1),[S,v]=p.useState(!1),[b,w]=p.useState(!1),j=p.useRef(null),[C,x]=p.useState(!1),[E,P]=p.useState(!1),A=p.useRef(null),g=p.useRef(null),I=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,T=e.mainView==="notebook",O=e.mainView==="notebook"||e.mainView==="block_studio",_=O&&!!e.activeFile,M={home:"Home",business_artifact:((te=e.activeFile)==null?void 0:te.name.replace(/\.(dqlnb|dql)$/i,""))??"Business Definition",lineage:"Lineage",lineage_detail:"Lineage",connection:"Settings",apps:"Apps",git:"Source control",settings:"Settings",imports:"Import SQL",domains:"Modeling",modeling:"Modeling"},q=O?e.activeFile?e.notebookTitle||"Untitled":e.mainView==="block_studio"?"Blocks":"Notebooks":M[e.mainView]??"DQL Workbench";p.useEffect(()=>{o&&g.current&&(g.current.focus(),g.current.select())},[o]),p.useEffect(()=>{if(!E)return;function F(K){A.current&&!A.current.contains(K.target)&&P(!1)}return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[E]);const G=()=>{c(e.notebookTitle),i(!0)},J=()=>{i(!1),a.trim()&&a!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:a.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:Y1(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},H=p.useCallback(async()=>{var K,oe,ee;const F=In.getState();if(F.activeFile){t({type:"SET_SAVING",saving:!0});try{if(F.mainView==="block_studio"){if(!F.blockStudioMetadata)return;const ce=await B.saveBlockStudio({path:F.activeBlockPath,source:F.blockStudioDraft,metadata:{name:F.blockStudioMetadata.name,domain:F.blockStudioMetadata.domain,folderPath:F.blockStudioMetadata.folderPath,description:F.blockStudioMetadata.description,owner:F.blockStudioMetadata.owner,tags:F.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"},payload:ce}),F.files.some(ke=>ke.path===ce.path)||t({type:"FILE_ADDED",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"}})}else{const ce=F.activeFile,ke=F.cells,xe=F.notebookTitle,De=F.notebookMetadata,We=ce.type==="block"?((K=ke[0])==null?void 0:K.content)??"":N1(xe,ke,De);await DC(ce.path,We);const Be=In.getState();((oe=Be.activeFile)==null?void 0:oe.path)===ce.path&&Be.cells===ke&&Be.notebookTitle===xe&&Be.notebookMetadata===De&&t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}u(!0),setTimeout(()=>u(!1),2e3)}catch(ce){console.error("Save failed:",ce)}finally{const ce=(ee=In.getState().activeFile)==null?void 0:ee.path;(!ce||!$C(ce))&&t({type:"SET_SAVING",saving:!1})}}},[t]);p.useEffect(()=>{const F=K=>{(K.metaKey||K.ctrlKey)&&K.key==="s"&&(K.preventDefault(),H())};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[H]),p.useEffect(()=>{if(!e.autoSave||!I||!e.activeFile||e.mainView==="block_studio")return;const F=setTimeout(()=>{H()},750);return()=>clearTimeout(F)},[e.autoSave,I,e.activeFile,e.cells,e.blockStudioDraft,H]);const L=[{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,X=L.find(F=>F.mode===$)??L[0];p.useEffect(()=>{if(!b)return;const F=oe=>{j.current&&!j.current.contains(oe.target)&&w(!1)},K=oe=>{oe.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",F),document.addEventListener("keydown",K),()=>{document.removeEventListener("mousedown",F),document.removeEventListener("keydown",K)}},[b]);const W={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(MC,{t:n}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&O&&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&&O?o?s.jsx("input",{ref:g,value:a,onChange:F=>c(F.target.value),onBlur:J,onKeyDown:F=>{F.key==="Enter"&&J(),F.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:G,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:[q,I&&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:q||"DQL Workbench"})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx(PC,{}),e.appMode==="studio"&&_&&e.mainView!=="block_studio"&&s.jsx(s.Fragment,{children:s.jsxs("button",{onClick:T?r:void 0,disabled:!e.activeFile||!T,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{...W,height:30,padding:"0 14px",borderRadius:999,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!T?.4:h?.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:j,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>w(F=>!F),onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),title:`Theme: ${X.label}`,"aria-haspopup":"true","aria-expanded":b,style:{...W,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:X.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:X.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:L.map(F=>{const K=F.mode===$;return s.jsxs("button",{role:"menuitemradio","aria-checked":K,onClick:()=>{t({type:"SET_THEME",mode:F.mode}),w(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",background:K?n.btnHover:"transparent",color:n.textPrimary,cursor:"pointer",borderRadius:4,fontSize:12,fontFamily:n.font,textAlign:"left"},onMouseEnter:oe=>{K||(oe.currentTarget.style.background=n.btnHover)},onMouseLeave:oe=>{K||(oe.currentTarget.style.background="transparent")},children:[s.jsx("span",{style:{width:14,height:14,borderRadius:3,background:F.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{flex:1},children:F.label}),K&&s.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},F.mode)})})]}),e.appMode==="studio"&&_&&e.mainView!=="block_studio"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:H,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),title:"Save (Cmd+S)",style:{...W,background:f&&e.activeFile?n.btnHover:n.btnBg,color:l?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?s.jsxs(s.Fragment,{children:[s.jsx(BC,{}),"Saving…"]}):l?s.jsx(s.Fragment,{children:"✓ Saved"}):s.jsx(s.Fragment,{children:"Save"})}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),_&&e.mainView!=="block_studio"&&s.jsxs("div",{ref:A,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>{e.activeFile&&P(F=>!F)},disabled:!e.activeFile,onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),title:"Share / export",style:{...W,height:30,padding:"0 14px",borderRadius:999,background:(C||E)&&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"})})]}),E&&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(NC,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{mC(e.notebookTitle||"dashboard",e.cells),P(!1)}})})]})]})]})}function NC({label:e,description:t,t:n,onClick:r}){const[o,i]=p.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 BC(){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 FC(e){return e.toTimeString().slice(0,8)}function zC(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function qC(){const{state:e,dispatch:t}=et(),n=Qe[e.themeMode],[r,o]=p.useState(!1),i=e.queryLog.filter(c=>c.error),a=c=>t({type:"SET_DEV_PANEL_TAB",tab:c});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(c=>s.jsx(UC,{label:c==="errors"?`Errors${i.length>0?` (${i.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===c,onClick:()=>a(c),t:n},c)),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(Fl,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(c=>s.jsx(zl,{entry:c,t:n},c.id))),e.devPanelTab==="errors"&&(i.length===0?s.jsx(Fl,{t:n,message:"No errors."}):[...i].reverse().map(c=>s.jsx(zl,{entry:c,t:n},c.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 UC({label:e,active:t,onClick:n,t:r}){const[o,i]=p.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 Fl({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 zl({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:FC(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:zC(e.time)})]})]})}function WC(){const{state:e,dispatch:t}=et(),{executeAll:n}=pf();p.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 KC=600;function VC(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 ql(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 HC(){var o;const{state:e}=et(),t=p.useRef(null),n=p.useRef(""),r=p.useRef(null);p.useEffect(()=>{var c;const i=((c=e.activeFile)==null?void 0:c.path)??null;if(!i)return;if(i!==r.current){r.current=i,n.current=ql(e.cells);return}const a=ql(e.cells);return a!==n.current&&(n.current=a,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const l=VC(i,e.cells);B.saveRunSnapshot(i,l).catch(()=>{})},KC)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}const mE="core";function GC(e){var n;const t=e==null?void 0:e.trim();if(t)return((n=t.split("::").at(-1))==null?void 0:n.trim())||void 0}const QC=[{items:[{id:"diagram",label:"Modeling"},{id:"skills",label:"Skills"},{id:"blocks",label:"Blocks"},{id:"notebooks",label:"Notebooks"},{id:"apps",label:"Apps"}]}],JC=new Set(QC.flatMap(e=>e.items.map(t=>t.id)));function mf(e){return e!==null&&JC.has(e)}function gE(e,t){const n=new URL(e);return t.domain?n.searchParams.set("domain",t.domain):n.searchParams.delete("domain"),n.searchParams.set("domainSection",t.section),t.modelAreaId?n.searchParams.set("modelArea",t.modelAreaId):n.searchParams.delete("modelArea"),t.selectedId?n.searchParams.set("domainObject",t.selectedId):n.searchParams.delete("domainObject"),`${n.pathname}${n.search}${n.hash}`}function YC(e){const t=new URL(e);for(const n of gf)t.searchParams.delete(n);return`${t.pathname}${t.search}${t.hash}`}const gf=["domain","domainSection","modelArea","domainObject"],yE="dql.domain-studio.location";function bE(e,t){const n=new URL(e).searchParams;if(gf.some(r=>n.has(r))){const r=n.get("domainSection"),o=mf(r)?r:"diagram";return{domain:n.get("domain"),section:o,modelAreaId:n.get("modelArea"),selectedId:r==="diagram"?n.get("domainObject"):null}}return XC(t)}function XC(e){const t={domain:null,section:"diagram",modelAreaId:null,selectedId:null};if(!e)return t;try{const n=JSON.parse(e),r=typeof n.section=="string"&&mf(n.section)?n.section:"diagram",o=i=>typeof i=="string"&&i.trim()?i:null;return{domain:o(n.domain),section:r,modelAreaId:o(n.modelAreaId),selectedId:o(n.selectedId)}}catch{return t}}function xE(e){return`modeling:${e??"all"}`}function vE(e){const t=Object.values(e),n=new Map;for(const a of t){const c=a.parent&&e[a.parent]?a.parent:void 0;n.set(c,[...n.get(c)??[],a])}for(const a of n.values())a.sort((c,l)=>c.id.localeCompare(l.id));const r=[],o=new Set,i=(a,c)=>{for(const l of n.get(a)??[])o.has(l.id)||(o.add(l.id),r.push({id:l.id,parent:l.parent,depth:c,label:c===0?l.id:`${"— ".repeat(c)}${l.id.split(".").at(-1)??l.id}`}),i(l.id,c+1))};i(void 0,0);for(const a of t.sort((c,l)=>c.id.localeCompare(l.id)))o.has(a.id)||r.push({id:a.id,parent:a.parent,depth:0,label:a.id});return r}function SE(e){const t=(e??"").toLowerCase();return t==="dimension"?"var(--status-success)":t==="bridge"?"var(--status-warning)":t==="event"||t==="snapshot"?"var(--accent)":"var(--text-tertiary)"}function yf(e){return Object.entries(e.entities).map(([t,n])=>({recordKey:t,entity:n}))}function wE(e,t){if(e.entities[t])return t;const n=yf(e).filter(({entity:r})=>r.id===t||r.qualifiedId===t);return n.length===1?n[0].recordKey:void 0}function kE(e,t){return yf(e).filter(({entity:n})=>!t||n.domain===t)}function CE(e,t,n){if(e.operation==="upsert_entity"){if(!t)return!1;const r=e.value;return r.dbtModel===t.dbtUniqueId&&(r.grain??void 0)===(t.grain??void 0)&&JSON.stringify(r.keys??[])===JSON.stringify(t.keys??[])&&(r.status??t.status)===t.status&&(r.areaId??void 0)===GC(t.areaId)&&r.domain===t.domain}return e.operation==="upsert_area"?!!n&&e.value.domain===n.domain&&e.value.id===n.localId:!1}const ZC=p.lazy(()=>_e(()=>import("./HomePage-CmSxapR3.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.HomePage}))),ej=p.lazy(()=>_e(()=>import("./AnalyticsHome-BGfey_ve.js"),__vite__mapDeps([7,8,9,10,1,11,12,3,13,14,15,16,17,2,18,6])).then(e=>({default:e.AnalyticsHome}))),tj=p.lazy(()=>_e(()=>import("./GlobalAiRail-CSKW-5eD.js"),__vite__mapDeps([19,9,10,1,11,12,3,13,14,15,16,17,2,20,6])).then(e=>({default:e.GlobalAiRail}))),nj=p.lazy(()=>_e(()=>import("./NotebookEditor-hs-kw8v9.js"),__vite__mapDeps([21,4,2,5,22,23,24,10,1,11,12,3,13,14,9,15,16,17,8,25,26,6,27,28,20,29])).then(e=>({default:e.NotebookEditor}))),rj=p.lazy(()=>_e(()=>import("./NewNotebookModal-DsC9CWlW.js"),__vite__mapDeps([30,4,15,6])).then(e=>({default:e.NewNotebookModal}))),oj=p.lazy(()=>_e(()=>import("./NewBlockModal-DMBFB7nE.js"),__vite__mapDeps([31,6])).then(e=>({default:e.NewBlockModal}))),sj=p.lazy(()=>_e(()=>import("./SetupOnboarding-B1Pu_Bvv.js"),__vite__mapDeps([32,33,2,6])).then(e=>({default:e.SetupOnboarding}))),ij=p.lazy(()=>_e(()=>import("./BlockStudio--S6WFVO4.js"),__vite__mapDeps([34,22,23,10,1,11,12,3,13,14,25,26,6,27,9,15,16,17,2,20,35,36])).then(e=>({default:e.BlockStudio}))),aj=p.lazy(()=>_e(()=>import("./BusinessArtifactView-BEAJ-yNW.js"),__vite__mapDeps([37,25,26,6,27])).then(e=>({default:e.BusinessArtifactView}))),cj=p.lazy(()=>_e(()=>import("./LineageDetailView-Dx48Zfzb.js"),__vite__mapDeps([38,25,26,6,27,39,33,16])).then(e=>({default:e.LineageDetailView}))),lj=p.lazy(()=>_e(()=>import("./LineageDAG-BGUcIt1B.js"),__vite__mapDeps([39,26,6,27])).then(e=>({default:e.LineageDAG}))),dj=p.lazy(()=>_e(()=>import("./HelpDocsPage-D0D9UCIz.js"),__vite__mapDeps([40,6])).then(e=>({default:e.HelpDocsPage}))),uj=p.lazy(()=>_e(()=>Promise.resolve().then(()=>a1),void 0).then(e=>({default:e.ConnectionPanel}))),pj=p.lazy(()=>_e(()=>import("./GitPage-IcydAai3.js"),__vite__mapDeps([41,42,15,6])).then(e=>({default:e.GitPage}))),fj=p.lazy(()=>_e(()=>import("./ReadinessPage-DJ83cMik.js"),__vite__mapDeps([43,1,44,45,12,3,2,6])).then(e=>({default:e.ReadinessPage}))),hj=p.lazy(()=>_e(()=>import("./AgentLogPage-DKbGpRQS.js"),__vite__mapDeps([46,33,14,47,6])).then(e=>({default:e.AgentLogPage}))),mj=p.lazy(()=>_e(()=>import("./GovernedContextPage-CFen0eFT.js"),__vite__mapDeps([48,3,12,9,10,1,11,13,14,15,16,17,2,49,6])).then(e=>({default:e.GovernedContextPage}))),gj=p.lazy(()=>_e(()=>import("./DbtFirstModelingPage-CNyU5MBX.js"),__vite__mapDeps([50,49,9,10,1,11,12,3,13,14,15,16,17,2,26,6,27,28,29,36,51,47])).then(e=>({default:e.DbtFirstModelingPage}))),yj=p.lazy(()=>_e(()=>import("./AppsView-CM1tPywy.js"),__vite__mapDeps([52,20,17,10,1,11,12,3,13,14,15,33,35,29,4,5,24,8,45,53,51,2,18,6])).then(e=>({default:e.AppsView}))),bj=p.lazy(()=>_e(()=>import("./LineageDrawer-zaBfSLZO.js"),__vite__mapDeps([54,25,26,6,27,36,15,17,13,53,42])).then(e=>({default:e.LineageDrawer}))),xj=p.lazy(()=>_e(()=>import("./AiBuildDialog-DPSu0Mly.js"),__vite__mapDeps([55,44,11,12,3,13,15,6])).then(e=>({default:e.AiBuildDialog})));function vj(){const e=Ge(Lr(d=>({appMode:d.appMode,dashboardMode:d.dashboardMode,globalAi:d.globalAi,inspectorOpen:d.inspectorOpen,lineageDrawerOpen:d.lineageDrawerOpen,lineageFullscreen:d.lineageFullscreen,mainView:d.mainView,newBlockModalOpen:d.newBlockModalOpen,newNotebookModalOpen:d.newNotebookModalOpen,setupOpen:d.setupOpen,sidebarOpen:d.sidebarOpen,sidebarPanel:d.sidebarPanel,themeMode:d.themeMode}))),t=jn(),n=Qe[e.themeMode],r=p.useRef({}),o=e.mainView==="block_studio"||e.mainView==="imports",[i,a]=p.useState(!1),[c,l]=p.useState(null);p.useEffect(()=>{let d=!0;return B.getSetupLaunch().then(f=>{d&&(l(f),f.shouldOpen&&t({type:"OPEN_SETUP"}))}).catch(()=>{}),()=>{d=!1}},[t]),p.useEffect(()=>{const d=()=>t({type:"SET_MAIN_VIEW",view:"modeling"});return window.addEventListener("dql:open-context-proposal",d),()=>window.removeEventListener("dql:open-context-proposal",d)},[t]),p.useEffect(()=>{if(e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills")return;const d=YC(window.location.href),f=`${window.location.pathname}${window.location.search}${window.location.hash}`;d!==f&&window.history.replaceState(window.history.state,"",d)},[e.mainView]),WC(),HC(),p.useEffect(()=>{const d=f=>{(f.metaKey||f.ctrlKey)&&f.key.toLowerCase()==="k"&&!f.shiftKey&&(f.preventDefault(),a(m=>!m)),(f.metaKey||f.ctrlKey)&&f.shiftKey&&f.key.toLowerCase()==="i"&&(f.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);const u=p.useCallback(async d=>{try{if(d.type==="term"||d.type==="business_view"){e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"}),t({type:"OPEN_BUSINESS_ARTIFACT",file:d});return}if(d.type==="block"){const j=await B.openBlockStudio(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:j});return}const{content:f}=await B.readNotebook(d.path),{title:m,cells:S,metadata:v}=B1(d.path,f),b=d.path.endsWith(".dqlnb")?await B.fetchRunSnapshot(d.path):null;let w=S;if(b!=null&&b.found&&b.snapshot){const j=new Map(b.snapshot.cells.map(C=>[C.cellId,C]));w=S.map(C=>{const x=j.get(C.id);return x?{...C,status:x.status??C.status,result:x.result??C.result,error:x.error??C.error,executionCount:x.executionCount??C.executionCount,execution:x.execution??C.execution,fromSnapshot:x.result!=null}:C})}t({type:"OPEN_FILE",file:d,cells:w,title:m,metadata:v}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(f){if(console.error("Failed to open file:",f),d.type==="block")try{const{content:m}=await B.readNotebook(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:{path:d.path,source:m,companionPath:null,metadata:{name:d.name.replace(/\.dql$/i,""),path:d.path,domain:d.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(m){console.error("Failed to open block fallback:",m)}else t({type:"OPEN_FILE",file:d,cells:[Ra("sql")],title:d.name})}},[t,e.sidebarPanel]);p.useCallback(d=>{const f=r.current[d];f&&f.scrollIntoView({behavior:"smooth",block:"start"})},[]);const h=p.useCallback((d,f)=>{f?r.current[d]=f:delete r.current[d]},[]);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(LC,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(Kw,{}),e.appMode==="studio"&&e.sidebarOpen&&!o&&s.jsx(P1,{onOpenFile:u}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:s.jsx(p.Suspense,{fallback:s.jsx(Sj,{t:n}),children:e.mainView==="home"?s.jsx(ZC,{}):e.mainView==="ask"?s.jsx(ej,{}):e.mainView==="business_artifact"?s.jsx(aj,{}):e.mainView==="lineage"?s.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s.jsx(lj,{})}):e.mainView==="lineage_detail"?s.jsx(cj,{}):e.mainView==="help"?s.jsx(dj,{}):e.mainView==="connection"||e.mainView==="settings"?s.jsx(kj,{children:s.jsx(uj,{variant:"page"})}):e.mainView==="git"?s.jsx(pj,{}):e.mainView==="readiness"?s.jsx(fj,{}):e.mainView==="skills"?s.jsx(mj,{initialTab:"skills"}):e.mainView==="domains"||e.mainView==="modeling"?s.jsx(gj,{}):e.mainView==="apps"?s.jsx(yj,{}):e.mainView==="agent_log"?s.jsx(Cj,{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(hj,{})}):s.jsx(s.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?s.jsx(ij,{},"block-editor"):s.jsxs(s.Fragment,{children:[s.jsx(nj,{onOpenFile:u,registerCellRef:h}),e.appMode==="studio"&&s.jsx(qC,{})]})})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(bj,{})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(Iw,{}),e.globalAi.open&&e.mainView==="apps"&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(tj,{})})]}),e.newNotebookModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(rj,{onFileOpened:u})}),e.newBlockModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(oj,{onFileOpened:u})}),s.jsx(ew,{open:i,onClose:()=>a(!1)}),s.jsx(p.Suspense,{fallback:null,children:s.jsx(xj,{})}),e.setupOpen&&s.jsx(p.Suspense,{fallback:s.jsx(wj,{t:n}),children:s.jsx(sj,{launch:c!=null&&c.shouldOpen?c:void 0,onAcknowledged:()=>l(d=>d&&{...d,shouldOpen:!1,reason:null})})})]})}function Sj({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 wj({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 kj({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 Cj({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 jj(){const e=jn(),t=Yi(),n=p.useRef(null);p.useEffect(()=>{let r=!0,o=null,i=null,a=null,c=null;const l=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,B.listNotebooks().then(f=>{r&&(t.setQueryData(["notebooks"],f),e({type:"SET_FILES",files:f}))}).catch(()=>{})},150)},u=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,B.getDomains().then(({domains:f})=>{r&&(t.setQueryData(["authored-domains"],{domains:f}),e({type:"SET_AUTHORED_DOMAINS",domains:f}))}).catch(()=>{})},150)},h=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null,e({type:"SET_SEMANTIC_LOADING",loading:!0}),B.getSemanticLayer().then(f=>{r&&(t.setQueryData(["semantic-layer"],f),e({type:"SET_SEMANTIC_LAYER",layer:f}))}).catch(()=>{})},100)},d=()=>{if(!r)return;const f=new AbortController;n.current=f,Tp("/api/watch",m=>{if(m.event==="change")try{const S=JSON.parse(m.data);if(S.type==="file-added"||S.type==="file-deleted"||S.type==="file-changed"){const v=S.path??"";/^(?:notebooks|workbooks|blocks|skills|apps|dashboards)\//.test(v)&&l(),v.startsWith("domains/")&&(l(),u())}S.type==="semantic-reload"&&h()}catch{}},f.signal).catch(()=>{!r||f.signal.aborted||(o&&clearTimeout(o),o=setTimeout(d,5e3))})};return d(),()=>{var f;r=!1,o&&clearTimeout(o),i&&clearTimeout(i),a&&clearTimeout(a),c&&clearTimeout(c),(f=n.current)==null||f.abort(),n.current=null}},[e,t])}const Ej=new ch({defaultOptions:{queries:{staleTime:15e3,gcTime:5*6e4,retry:1,refetchOnWindowFocus:!1}}});function Tj(){const e=Ge(i=>i.themeMode),t=Ge(i=>i.dispatch),n=Qe[e];p.useEffect(()=>{const i="dql-global-styles";let a=document.getElementById(i);a||(a=document.createElement("style"),a.id=i,document.head.appendChild(a)),a.textContent=`
611
611
  * { margin: 0; padding: 0; box-sizing: border-box; }
612
612
  body {
613
613
  font-family: var(--font-ui, ${n.font});
@@ -632,4 +632,4 @@ ${t}`;return r.replace(/\n\}\s*$/,`${o}
632
632
  background: var(--dql-pill-hover-bg) !important;
633
633
  border-color: var(--dql-pill-hover-border) !important;
634
634
  }
635
- `},[n]),p.useEffect(()=>{const i=e==="dark"||e==="midnight"?"obsidian":e==="light"?"paper":e==="arctic"?"white":e;document.documentElement.setAttribute("data-theme",i)},[e]);const r=Ri({queryKey:["notebooks"],queryFn:()=>B.listNotebooks()}),o=Ri({queryKey:["authored-domains"],queryFn:()=>B.getDomains()});return p.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:r.isLoading}),r.data&&t({type:"SET_FILES",files:r.data})},[t,r.data,r.isLoading]),p.useEffect(()=>{o.data&&t({type:"SET_AUTHORED_DOMAINS",domains:o.data.domains})},[t,o.data]),Cj(),s.jsx(wh,{theme:e,applyGlobal:!0,children:s.jsx(Ig,{delayDuration:200,skipDelayDuration:400,children:s.jsx(xj,{})})})}function Tj(){return s.jsx(ch,{client:jj,children:s.jsx(Qx,{children:s.jsx(CC,{children:s.jsx(Ej,{})})})})}$f.createRoot(document.getElementById("root")).render(s.jsx(Tj,{}));export{yp as $,ef as A,Oa as B,Rv as C,To as D,q1 as E,Pa as F,Nr as G,eE as H,Zj as I,In as J,uf as K,Un as L,vt as M,bS as N,pE as O,OS as P,xk as Q,qe as R,xp as S,vp as T,Ao as U,Jn as V,Fw as W,Fj as X,zj as Y,Hj as Z,qj as _,B as a,N1 as a$,ps as a0,Uk as a1,Qp as a2,ti as a3,Fi as a4,Gj as a5,jC as a6,Ri as a7,fE as a8,oE as a9,Bj as aA,Ow as aB,_w as aC,Mj as aD,Zc as aE,hS as aF,ov as aG,cv as aH,iS as aI,tS as aJ,_v as aK,Ev as aL,SE as aM,gf as aN,vE as aO,hE as aP,wE as aQ,gE as aR,yE as aS,mE as aT,xE as aU,Fp as aV,GC as aW,Lv as aX,mp as aY,bE as aZ,kE as a_,ik as aa,cE as ab,lE as ac,Q1 as ad,J1 as ae,sE as af,Xj as ag,tf as ah,Yj as ai,iE as aj,X1 as ak,Y1 as al,rE as am,Il as an,aE as ao,ys as ap,M0 as aq,St as ar,Hc as as,Kj as at,Vj as au,Wj as av,Uj as aw,Ap as ax,Lj as ay,Nj as az,Re as b,uS as b0,gS as b1,DS as b2,rS as b3,_e as b4,Yi as b5,Qj as b6,Bv as b7,up as b8,NS as b9,Uv as ba,zi as bb,nE as bc,an as bd,Zi as be,ne as c,_a as d,Is as e,hp as f,bv as g,Ge as h,Lr as i,s as j,jn as k,FS as l,Ra as m,H1 as n,Jj as o,Tw as p,Aw as q,p as r,dE as s,Qe as t,et as u,uE as v,nf as w,rf as x,tE as y,K1 as z};
635
+ `},[n]),p.useEffect(()=>{const i=e==="dark"||e==="midnight"?"obsidian":e==="light"?"paper":e==="arctic"?"white":e;document.documentElement.setAttribute("data-theme",i)},[e]);const r=Ri({queryKey:["notebooks"],queryFn:()=>B.listNotebooks()}),o=Ri({queryKey:["authored-domains"],queryFn:()=>B.getDomains()});return p.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:r.isLoading}),r.data&&t({type:"SET_FILES",files:r.data})},[t,r.data,r.isLoading]),p.useEffect(()=>{o.data&&t({type:"SET_AUTHORED_DOMAINS",domains:o.data.domains})},[t,o.data]),jj(),s.jsx(kh,{theme:e,applyGlobal:!0,children:s.jsx(Dg,{delayDuration:200,skipDelayDuration:400,children:s.jsx(vj,{})})})}function Aj(){return s.jsx(lh,{client:Ej,children:s.jsx(Jx,{children:s.jsx(jC,{children:s.jsx(Tj,{})})})})}Mf.createRoot(document.getElementById("root")).render(s.jsx(Aj,{}));export{bp as $,tf as A,Oa as B,Ov as C,To as D,U1 as E,Pa as F,Nr as G,tE as H,eE as I,In as J,pf as K,Un as L,vt as M,xS as N,fE as O,_S as P,vk as Q,qe as R,vp as S,Sp as T,Ao as U,Jn as V,zw as W,zj as X,qj as Y,Gj as Z,Uj as _,B as a,B1 as a$,ps as a0,Wk as a1,Jp as a2,ti as a3,Fi as a4,Qj as a5,EC as a6,Ri as a7,hE as a8,sE as a9,Fj as aA,_w as aB,Pw as aC,Lj as aD,el as aE,mS as aF,sv as aG,lv as aH,aS as aI,nS as aJ,Pv as aK,Tv as aL,wE as aM,yf as aN,SE as aO,mE as aP,kE as aQ,yE as aR,bE as aS,gE as aT,vE as aU,zp as aV,QC as aW,Nv as aX,gp as aY,xE as aZ,CE as a_,ak as aa,lE as ab,dE as ac,J1 as ad,Y1 as ae,iE as af,Zj as ag,nf as ah,Xj as ai,aE as aj,Z1 as ak,X1 as al,oE as am,Dl as an,cE as ao,ys as ap,L0 as aq,St as ar,Hc as as,Vj as at,Hj as au,Kj as av,Wj as aw,Rp as ax,Nj as ay,Bj as az,Re as b,pS as b0,yS as b1,$S as b2,oS as b3,_e as b4,Yi as b5,Jj as b6,Fv as b7,pp as b8,BS as b9,Wv as ba,zi as bb,rE as bc,an as bd,Zi as be,ne as c,_a as d,Is as e,mp as f,xv as g,Ge as h,Lr as i,s as j,jn as k,zS as l,Ra as m,G1 as n,Yj as o,Aw as p,Rw as q,p as r,uE as s,Qe as t,et as u,pE as v,rf as w,of as x,nE as y,V1 as z};