@duckcodeailabs/dql-cli 1.13.2 → 1.13.4

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 (70) hide show
  1. package/dist/apps-api.d.ts +26 -3
  2. package/dist/apps-api.d.ts.map +1 -1
  3. package/dist/apps-api.js +1045 -175
  4. package/dist/apps-api.js.map +1 -1
  5. package/dist/assets/dql-notebook/assets/{AgentLogPage-BlUE3qsX.js → AgentLogPage-DYmHO6_i.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AiBuildDialog-O88iK6UW.js → AiBuildDialog-BfhaOd1h.js} +1 -1
  7. package/dist/assets/dql-notebook/assets/{AiBuildResult-D-6G4Sh3.js → AiBuildResult-DLKFAe6R.js} +3 -3
  8. package/dist/assets/dql-notebook/assets/{AiSidePanel-MRSGtQDV.js → AiSidePanel-C6Z3URGr.js} +1 -1
  9. package/dist/assets/dql-notebook/assets/{AnalyticsHome-CcRVO6zN.js → AnalyticsHome-uG3xCP_s.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/AppsView-DfieNjkh.js +5595 -0
  11. package/dist/assets/dql-notebook/assets/BlockStudio-90J_wvWL.js +55 -0
  12. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-itEIUrYy.js → BusinessArtifactView-_zSMae5q.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-CbAqOpNc.js → DbtFirstModelingPage-DoXiPssu.js} +4 -4
  14. package/dist/assets/dql-notebook/assets/{GitPage-BxOqRYu2.js → GitPage-CUfAhS67.js} +3 -3
  15. package/dist/assets/dql-notebook/assets/{GlobalAiRail-Tfkx76CI.js → GlobalAiRail-ovtL7nQu.js} +1 -1
  16. package/dist/assets/dql-notebook/assets/{GovernedContextPage-CeaDbepP.js → GovernedContextPage-CaMiKAzA.js} +3 -3
  17. package/dist/assets/dql-notebook/assets/{HelpDocsPage-D1lAryYv.js → HelpDocsPage-CEGUx28b.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{HomePage-GB6se6xW.js → HomePage-2v3SRf8V.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{LineageDAG-zCyN-hdg.js → LineageDAG-AaqLEiBN.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/{LineageDetailView-Cg0TgG2Y.js → LineageDetailView-CFc8pm91.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/{LineageDrawer-DwMcenDf.js → LineageDrawer-DOkFjPq-.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-DUZx3ksU.js → LineagePathBreadcrumb-BrDwCuMs.js} +3 -3
  23. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-DT_ycl6s.js → MiniLineageGraph-CiHtQs3y.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{NewBlockModal-qdhzeJPF.js → NewBlockModal-DAgJZbws.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{NewNotebookModal-BnaDzs1A.js → NewNotebookModal-xjG7nZ3O.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{NotebookEditor-CouPFzdo.js → NotebookEditor-CXZaKfYT.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/{ReadinessPage-DB_KbH9Y.js → ReadinessPage-MuJBFwwg.js} +1 -1
  28. package/dist/assets/dql-notebook/assets/{SetupOnboarding-CamQq_N2.js → SetupOnboarding-vKFtKtjh.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{SkillsPage--mYkOAK2.js → SkillsPage-DCFVOV5f.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{TrustBadge-ClEYiYeA.js → TrustBadge-TcwXFFHK.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/{UnifiedAgentRunPanel-DBfsmXes.js → UnifiedAgentRunPanel-Cu-YgIe4.js} +1 -1
  32. package/dist/assets/dql-notebook/assets/{answer-to-notebook-Cg3UyGwh.js → answer-to-notebook-DCFWlHB7.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{arrow-left-DnYPGqlr.js → arrow-left-BLnlJAtp.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{arrow-right-Ct_YGrmU.js → arrow-right-BmUAb1aW.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{book-open-text-DULlwbj6.js → book-open-text-bdSChSag.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{circle-x-ByYxoiS9.js → circle-x-Cc6dEaf4.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{dagre.esm-BjYSO53F.js → dagre.esm-CPebQKQ9.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/{external-link-DprWh9Yf.js → external-link-rmXvubf3.js} +1 -1
  39. package/dist/assets/dql-notebook/assets/{grip-vertical-CrEEYkXN.js → grip-vertical-Sg4zd5-Q.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/index-mQd_pC-P.js +635 -0
  41. package/dist/assets/dql-notebook/assets/{link-2-BkW-rkEC.js → link-2-BLaPoFxW.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{list-tree-BipBLmIE.js → list-tree-j0s4asFK.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{minimize-2-BhXsglrO.js → minimize-2-Cl4pef4s.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{panel-right-open-BoCSilYB.js → panel-right-open-Clz-FtWi.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{play-mdoZawPu.js → play-DFdazMg7.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{rotate-ccw-ELiDRUmj.js → rotate-ccw-C3tTaR7s.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{semantic-fields-DVNRLfeU.js → semantic-fields-DIAhTlfy.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/{sliders-horizontal-GeUzpmKz.js → sliders-horizontal-BUiu2tfY.js} +1 -1
  49. package/dist/assets/dql-notebook/assets/{star-D63O81Wp.js → star--Yq77aH4.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{triangle-alert-BWrCxQVE.js → triangle-alert-D5Ng-xZO.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{upload-CI-ldXhC.js → upload-L8BKQAxP.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-Cv7Yq2hK.js → usePersistedAgentThreadId-DBu97YaM.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/{user-round-Do21aFGo.js → user-round-BK5N1cJW.js} +1 -1
  54. package/dist/assets/dql-notebook/assets/{wand-sparkles-DT7u7F_x.js → wand-sparkles-D8XDQD9z.js} +1 -1
  55. package/dist/assets/dql-notebook/assets/{workflow-DHh2mMbn.js → workflow-Bl9zwG0q.js} +1 -1
  56. package/dist/assets/dql-notebook/assets/{wrench-7tYr_GKb.js → wrench-C-zLCMbW.js} +1 -1
  57. package/dist/assets/dql-notebook/assets/{x-CcYceFMz.js → x-stiJ-sP7.js} +1 -1
  58. package/dist/assets/dql-notebook/index.html +1 -1
  59. package/dist/local-operation-coordinator.d.ts.map +1 -1
  60. package/dist/local-operation-coordinator.js +16 -2
  61. package/dist/local-operation-coordinator.js.map +1 -1
  62. package/dist/local-runtime.d.ts +55 -19
  63. package/dist/local-runtime.d.ts.map +1 -1
  64. package/dist/local-runtime.js +1098 -581
  65. package/dist/local-runtime.js.map +1 -1
  66. package/dist/package.json +10 -10
  67. package/package.json +10 -10
  68. package/dist/assets/dql-notebook/assets/AppsView-BTkGC-wl.js +0 -5588
  69. package/dist/assets/dql-notebook/assets/BlockStudio-BrTNaDpb.js +0 -55
  70. package/dist/assets/dql-notebook/assets/index-9w93YPF9.js +0 -635
@@ -0,0 +1,635 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/HomePage-2v3SRf8V.js","assets/TrustBadge-TcwXFFHK.js","assets/arrow-right-BmUAb1aW.js","assets/triangle-alert-D5Ng-xZO.js","assets/book-open-text-bdSChSag.js","assets/workflow-Bl9zwG0q.js","assets/react-CRB3T2We.js","assets/AnalyticsHome-uG3xCP_s.js","assets/answer-to-notebook-DCFWlHB7.js","assets/UnifiedAgentRunPanel-Cu-YgIe4.js","assets/usePersistedAgentThreadId-DBu97YaM.js","assets/AiBuildResult-DLKFAe6R.js","assets/user-round-BK5N1cJW.js","assets/rotate-ccw-C3tTaR7s.js","assets/wrench-C-zLCMbW.js","assets/x-stiJ-sP7.js","assets/list-tree-j0s4asFK.js","assets/minimize-2-Cl4pef4s.js","assets/star--Yq77aH4.js","assets/GlobalAiRail-ovtL7nQu.js","assets/AiSidePanel-C6Z3URGr.js","assets/NotebookEditor-CXZaKfYT.js","assets/LineagePathBreadcrumb-BrDwCuMs.js","assets/codemirror-DXt7RW72.js","assets/semantic-fields-DIAhTlfy.js","assets/MiniLineageGraph-CiHtQs3y.js","assets/dagre.esm-CPebQKQ9.js","assets/dagre-BZV40eAE.css","assets/link-2-BLaPoFxW.js","assets/upload-L8BKQAxP.js","assets/NewNotebookModal-xjG7nZ3O.js","assets/NewBlockModal-DAgJZbws.js","assets/SetupOnboarding-vKFtKtjh.js","assets/arrow-left-BLnlJAtp.js","assets/BlockStudio-90J_wvWL.js","assets/play-DFdazMg7.js","assets/panel-right-open-Clz-FtWi.js","assets/BusinessArtifactView-_zSMae5q.js","assets/LineageDetailView-CFc8pm91.js","assets/LineageDAG-AaqLEiBN.js","assets/HelpDocsPage-CEGUx28b.js","assets/GitPage-CUfAhS67.js","assets/external-link-rmXvubf3.js","assets/ReadinessPage-MuJBFwwg.js","assets/ai-build-bus-1BR770pY.js","assets/wand-sparkles-D8XDQD9z.js","assets/AgentLogPage-DYmHO6_i.js","assets/circle-x-Cc6dEaf4.js","assets/GovernedContextPage-CaMiKAzA.js","assets/SkillsPage-DCFVOV5f.js","assets/DbtFirstModelingPage-DoXiPssu.js","assets/sliders-horizontal-BUiu2tfY.js","assets/AppsView-DfieNjkh.js","assets/grip-vertical-Sg4zd5-Q.js","assets/LineageDrawer-DOkFjPq-.js","assets/AiBuildDialog-BfhaOd1h.js"])))=>i.map(i=>d[i]);
2
+ var jf=Object.defineProperty;var ec=e=>{throw TypeError(e)};var Ef=(e,t,n)=>t in e?jf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pe=(e,t,n)=>Ef(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 Do=(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 Tf(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:{}},Br={};/**
3
+ * @license React
4
+ * react-jsx-runtime.production.min.js
5
+ *
6
+ * Copyright (c) Facebook, Inc. and its affiliates.
7
+ *
8
+ * This source code is licensed under the MIT license found in the
9
+ * LICENSE file in the root directory of this source tree.
10
+ */var tc;function Af(){if(tc)return Br;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 Br.Fragment=n,Br.jsx=a,Br.jsxs=a,Br}var nc;function Rf(){return nc||(nc=1,Ls.exports=Af()),Ls.exports}var s=Rf(),$o={},rc;function Of(){if(rc)return $o;rc=1;var e=Zl();return $o.createRoot=e.createRoot,$o.hydrateRoot=e.hydrateRoot,$o}var _f=Of(),p=Xl();const qe=ed(p),td=Tf({__proto__:null,default:qe},[p]);var xo=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(){}},In,an,hr,ql,Pf=(ql=class extends xo{constructor(){super();le(this,In);le(this,an);le(this,hr);Z(this,hr,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){R(this,an)||this.setEventListener(R(this,hr))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,an))==null||t.call(this),Z(this,an,void 0))}setEventListener(t){var n;Z(this,hr,t),(n=R(this,an))==null||n.call(this),Z(this,an,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){R(this,In)!==t&&(Z(this,In,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof R(this,In)=="boolean"?R(this,In):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},In=new WeakMap,an=new WeakMap,hr=new WeakMap,ql),Hi=new Pf,If={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},cn,Vi,Ul,Df=(Ul=class{constructor(){le(this,cn,If);le(this,Vi,!1)}setTimeoutProvider(e){Z(this,cn,e)}setTimeout(e,t){return R(this,cn).setTimeout(e,t)}clearTimeout(e){R(this,cn).clearTimeout(e)}setInterval(e,t){return R(this,cn).setInterval(e,t)}clearInterval(e){R(this,cn).clearInterval(e)}},cn=new WeakMap,Vi=new WeakMap,Ul),_n=new Df;function $f(e){setTimeout(e,0)}var Mf=typeof window>"u"||"Deno"in globalThis;function at(){}function Lf(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 mn(e,t){return typeof e=="function"?e(t):e}function ft(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(!Tr(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(ro(t.options.mutationKey)!==ro(i))return!1}else if(!Tr(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)||ro)(e)}function ro(e){return JSON.stringify(e,(t,n)=>yi(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Tr(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(!Tr(e[r],t[r]))return!1;return!0}const n=Object.keys(t);for(const r of n)if(!Tr(e[r],t[r]))return!1;return!0}return!1}var Nf=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:Nf.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 Bf(e){return new Promise(t=>{_n.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 Ff(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function zf(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 qf(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 oo=(()=>{let e=()=>Mf;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 Uf=$f;function Wf(){let e=[],t=0,n=c=>{c()},r=c=>{c()},o=Uf;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=Wf(),mr,ln,gr,Wl,Kf=(Wl=class extends xo{constructor(){super();le(this,mr,!0);le(this,ln);le(this,gr);Z(this,gr,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,ln)||this.setEventListener(R(this,gr))}onUnsubscribe(){var t;this.hasListeners()||((t=R(this,ln))==null||t.call(this),Z(this,ln,void 0))}setEventListener(t){var n;Z(this,gr,t),(n=R(this,ln))==null||n.call(this),Z(this,ln,t(this.setOnline.bind(this)))}setOnline(t){R(this,mr)!==t&&(Z(this,mr,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return R(this,mr)}},mr=new WeakMap,ln=new WeakMap,gr=new WeakMap,Wl),os=new Kf;function Vf(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??(oo.isServer()?0:3),C=e.retryDelay??Vf,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),Bf(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 Dn,Kl,cd=(Kl=class{constructor(){le(this,Dn)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),mi(this.gcTime)&&Z(this,Dn,_n.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oo.isServer()?1/0:300*1e3))}clearGcTimeout(){R(this,Dn)!==void 0&&(_n.clearTimeout(R(this,Dn)),Z(this,Dn,void 0))}},Dn=new WeakMap,Kl);function Hf(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=>{qf(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?zf:Ff;return{pages:T(C.pages,g,I),pageParams:T(C.pageParams,x,I)}};if(o&&i.length){const C=o==="backward",x=C?Gf: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 Gf(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 yr,$n,br,yt,Mn,Le,ho,Ln,pt,ld,Vt,Vl,Qf=(Vl=class extends cd{constructor(t){super();le(this,pt);le(this,yr);le(this,$n);le(this,br);le(this,yt);le(this,Mn);le(this,Le);le(this,ho);le(this,Ln);Z(this,Ln,!1),Z(this,ho,t.defaultOptions),this.setOptions(t.options),this.observers=[],Z(this,Mn,t.client),Z(this,yt,R(this,Mn).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Z(this,$n,dc(this.options)),this.state=t.state??R(this,$n),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return R(this,yr)}get promise(){var t;return(t=R(this,Le))==null?void 0:t.promise}setOptions(t){if(this.options={...R(this,ho),...t},t!=null&&t._type&&Z(this,yr,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,$n,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&R(this,yt).remove(this)}setData(t,n){const r=bi(this.state.data,t,this.options);return fe(this,pt,Vt).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,pt,Vt).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,$n)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ft(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=>mn(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,yt).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,Ln)||fe(this,pt,ld).call(this)?R(this,Le).cancel({revert:!0}):R(this,Le).cancelRetry()),this.scheduleGc()),R(this,yt).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||fe(this,pt,Vt).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,Ln,!0),r.signal)})},i=()=>{const x=od(this.options,n),P=(()=>{const A={client:R(this,Mn),queryKey:this.queryKey,meta:this.meta};return o(A),A})();return Z(this,Ln,!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,Mn),state:this.state,fetchFn:i};return o(x),x})(),l=R(this,yr)==="infinite"?Hf(this.options.pages):this.options.behavior;l==null||l.onFetch(c,this),Z(this,br,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=c.fetchOptions)==null?void 0:h.meta))&&fe(this,pt,Vt).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,br),fetchStatus:"idle"}),r.abort()},onFail:(x,E)=>{fe(this,pt,Vt).call(this,{type:"failed",failureCount:x,error:E})},onPause:()=>{fe(this,pt,Vt).call(this,{type:"pause"})},onContinue:()=>{fe(this,pt,Vt).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,yt).config).onSuccess)==null||m.call(f,x,this),(v=(S=R(this,yt).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,pt,Vt).call(this,{type:"error",error:x}),(w=(b=R(this,yt).config).onError)==null||w.call(b,x,this),(C=(j=R(this,yt).config).onSettled)==null||C.call(j,this.state.data,x,this),x}finally{this.scheduleGc()}}},yr=new WeakMap,$n=new WeakMap,br=new WeakMap,yt=new WeakMap,Mn=new WeakMap,Le=new WeakMap,ho=new WeakMap,Ln=new WeakMap,pt=new WeakSet,ld=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Vt=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,br,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,yt).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,mo,Xe,Nn,xr,Ht,dn,go,vr,Sr,Bn,Fn,un,wr,Se,Vr,Si,wi,ki,Ci,ji,Ei,Ti,ud,Hl,Jf=(Hl=class extends xo{constructor(t,n){super();le(this,Se);le(this,it);le(this,he);le(this,mo);le(this,Xe);le(this,Nn);le(this,xr);le(this,Ht);le(this,dn);le(this,go);le(this,vr);le(this,Sr);le(this,Bn);le(this,Fn);le(this,un);le(this,wr,new Set);this.options=n,Z(this,it,t),Z(this,dn,null),Z(this,Ht,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,Vr).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 ft(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,Vr).call(this),this.updateResult(),o&&(R(this,he)!==r||ft(this.options.enabled,R(this,he))!==ft(n.enabled,R(this,he))||mn(this.options.staleTime,R(this,he))!==mn(n.staleTime,R(this,he)))&&fe(this,Se,Si).call(this);const i=fe(this,Se,wi).call(this);o&&(R(this,he)!==r||ft(this.options.enabled,R(this,he))!==ft(n.enabled,R(this,he))||i!==R(this,un))&&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 Xf(this,r)&&(Z(this,Xe,r),Z(this,xr,this.options),Z(this,Nn,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,Ht).status==="pending"&&R(this,Ht).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,o))})}trackProp(t){R(this,wr).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,Vr).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,Nn),c=R(this,xr),u=t!==r?t.state:R(this,mo),{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,Sr))==null?void 0:I.state.data,R(this,Sr)):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,go))m=R(this,vr);else try{Z(this,go,n.select),m=n.select(m),m=bi(i==null?void 0:i.data,m,n),Z(this,vr,m),Z(this,dn,null)}catch(T){Z(this,dn,T)}R(this,dn)&&(S=R(this,dn),m=R(this,vr),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,Ht),isEnabled:ft(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,Ht,g.promise=xi());_(G)},q=R(this,Ht);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,Nn,R(this,he).state),Z(this,xr,this.options),R(this,Nn).data!==void 0&&Z(this,Sr,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,wr).size)return!0;const a=new Set(i??R(this,wr));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,mo=new WeakMap,Xe=new WeakMap,Nn=new WeakMap,xr=new WeakMap,Ht=new WeakMap,dn=new WeakMap,go=new WeakMap,vr=new WeakMap,Sr=new WeakMap,Bn=new WeakMap,Fn=new WeakMap,un=new WeakMap,wr=new WeakMap,Se=new WeakSet,Vr=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=mn(this.options.staleTime,R(this,he));if(oo.isServer()||R(this,Xe).isStale||!mi(t))return;const r=nd(R(this,Xe).dataUpdatedAt,t)+1;Z(this,Bn,_n.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,un,t),!(oo.isServer()||ft(this.options.enabled,R(this,he))===!1||!mi(R(this,un))||R(this,un)===0)&&Z(this,Fn,_n.setInterval(()=>{(this.options.refetchIntervalInBackground||Hi.isFocused())&&fe(this,Se,Vr).call(this)},R(this,un)))},Ci=function(){fe(this,Se,Si).call(this),fe(this,Se,ki).call(this,fe(this,Se,wi).call(this))},ji=function(){R(this,Bn)!==void 0&&(_n.clearTimeout(R(this,Bn)),Z(this,Bn,void 0))},Ei=function(){R(this,Fn)!==void 0&&(_n.clearInterval(R(this,Fn)),Z(this,Fn,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,mo,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 Yf(e,t){return ft(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&ft(t.retryOnMount,e)===!1)}function uc(e,t){return Yf(e,t)||e.state.data!==void 0&&Ai(e,t,t.refetchOnMount)}function Ai(e,t,n){if(ft(t.enabled,e)!==!1&&mn(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||ft(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ji(e,n)}function Ji(e,t){return ft(t.enabled,e)!==!1&&e.isStaleByTime(mn(t.staleTime,e))}function Xf(e,t){return!gi(e.getCurrentResult(),t)}var yo,$t,He,zn,Mt,rn,Gl,Zf=(Gl=class extends cd{constructor(t){super();le(this,Mt);le(this,yo);le(this,$t);le(this,He);le(this,zn);Z(this,yo,t.client),this.mutationId=t.mutationId,Z(this,He,t.mutationCache),Z(this,$t,[]),this.state=t.state||eh(),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,$t).includes(t)||(R(this,$t).push(t),this.clearGcTimeout(),R(this,He).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Z(this,$t,R(this,$t).filter(n=>n!==t)),this.scheduleGc(),R(this,He).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){R(this,$t).length||(this.state.status==="pending"?this.scheduleGc():R(this,He).remove(this))}continue(){var t;return((t=R(this,zn))==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,Mt,rn).call(this,{type:"continue"})},r={client:R(this,yo),meta:this.options.meta,mutationKey:this.options.mutationKey};Z(this,zn,ad({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(g,I)=>{fe(this,Mt,rn).call(this,{type:"failed",failureCount:g,error:I})},onPause:()=>{fe(this,Mt,rn).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,zn).canStart();try{if(o)n();else{fe(this,Mt,rn).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,Mt,rn).call(this,{type:"pending",context:I,variables:t,isPaused:i})}const g=await R(this,zn).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,Mt,rn).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,Mt,rn).call(this,{type:"error",error:g}),g}finally{R(this,He).runNext(this)}}},yo=new WeakMap,$t=new WeakMap,He=new WeakMap,zn=new WeakMap,Mt=new WeakSet,rn=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,$t).forEach(r=>{r.onMutationUpdate(t)}),R(this,He).notify({mutation:this,type:"updated",action:t})})},Gl);function eh(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Gt,Rt,bo,Ql,th=(Ql=class extends xo{constructor(t={}){super();le(this,Gt);le(this,Rt);le(this,bo);this.config=t,Z(this,Gt,new Set),Z(this,Rt,new Map),Z(this,bo,0)}build(t,n,r){const o=new Zf({client:t,mutationCache:this,mutationId:++Do(this,bo)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){R(this,Gt).add(t);const n=Mo(t);if(typeof n=="string"){const r=R(this,Rt).get(n);r?r.push(t):R(this,Rt).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(R(this,Gt).delete(t)){const n=Mo(t);if(typeof n=="string"){const r=R(this,Rt).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,Rt).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Mo(t);if(typeof n=="string"){const r=R(this,Rt).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=Mo(t);if(typeof n=="string"){const o=(r=R(this,Rt).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,Gt).forEach(t=>{this.notify({type:"removed",mutation:t})}),R(this,Gt).clear(),R(this,Rt).clear()})}getAll(){return Array.from(R(this,Gt))}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))))}},Gt=new WeakMap,Rt=new WeakMap,bo=new WeakMap,Ql);function Mo(e){var t;return(t=e.options.scope)==null?void 0:t.id}var Lt,Jl,nh=(Jl=class extends xo{constructor(t={}){super();le(this,Lt);this.config=t,Z(this,Lt,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 Qf({client:t,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(a)),a}add(t){R(this,Lt).has(t.queryHash)||(R(this,Lt).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=R(this,Lt).get(t.queryHash);n&&(t.destroy(),n===t&&R(this,Lt).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Ue.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return R(this,Lt).get(t)}getAll(){return[...R(this,Lt).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()})})}},Lt=new WeakMap,Jl),Ae,pn,fn,kr,Cr,hn,jr,Er,Yl,rh=(Yl=class{constructor(e={}){le(this,Ae);le(this,pn);le(this,fn);le(this,kr);le(this,Cr);le(this,hn);le(this,jr);le(this,Er);Z(this,Ae,e.queryCache||new nh),Z(this,pn,e.mutationCache||new th),Z(this,fn,e.defaultOptions||{}),Z(this,kr,new Map),Z(this,Cr,new Map),Z(this,hn,0)}mount(){Do(this,hn)._++,R(this,hn)===1&&(Z(this,jr,Hi.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ae).onFocus())})),Z(this,Er,os.subscribe(async e=>{e&&(await this.resumePausedMutations(),R(this,Ae).onOnline())})))}unmount(){var e,t;Do(this,hn)._--,R(this,hn)===0&&((e=R(this,jr))==null||e.call(this),Z(this,jr,void 0),(t=R(this,Er))==null||t.call(this),Z(this,Er,void 0))}isFetching(e){return R(this,Ae).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return R(this,pn).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(mn(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=Lf(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(mn(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,pn).resumePausedMutations():Promise.resolve()}getQueryCache(){return R(this,Ae)}getMutationCache(){return R(this,pn)}getDefaultOptions(){return R(this,fn)}setDefaultOptions(e){Z(this,fn,e)}setQueryDefaults(e,t){R(this,kr).set(ro(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...R(this,kr).values()],n={};return t.forEach(r=>{Tr(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){R(this,Cr).set(ro(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...R(this,Cr).values()],n={};return t.forEach(r=>{Tr(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...R(this,fn).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,fn).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){R(this,Ae).clear(),R(this,pn).clear()}},Ae=new WeakMap,pn=new WeakMap,fn=new WeakMap,kr=new WeakMap,Cr=new WeakMap,hn=new WeakMap,jr=new WeakMap,Er=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},oh=({client:e,children:t})=>(p.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),s.jsx(pd.Provider,{value:e,children:t})),fd=p.createContext(!1),sh=()=>p.useContext(fd);fd.Provider;function ih(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var ah=p.createContext(ih()),ch=()=>p.useContext(ah),lh=(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))},dh=e=>{p.useEffect(()=>{e.clearReset()},[e])},uh=({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])),ph=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))}},fh=(e,t)=>e.isLoading&&e.isFetching&&!t,hh=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,fc=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function mh(e,t,n){var m,S,v,b;const r=sh(),o=ch(),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,ph(a),lh(a,o,c),dh(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]),hh(a,d))throw fc(a,h,o);if(uh({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&&!oo.isServer()&&fh(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 mh(e,Jf)}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"},Sn={sm:"4px",md:"6px",lg:"8px"},Ze={xs:"11px",sm:"12px",md:"14px"},Xi={medium:"500",semibold:"600"},so={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)"},Lo={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)"},gh={obsidian:Ns,paper:Lo,white:Lo,dark:Ns,light:Lo,midnight:Ns,arctic:Lo};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 yh=p.createContext(null);function bh({theme:e,defaultTheme:t="dark",onThemeChange:n,applyGlobal:r=!1,children:o}){const[i,a]=p.useState(t),c=e??i,l=gh[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(yh.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 xh(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 wn(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,vh(o,...t)]}function vh(...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 Sh=ed(Zi);function Ar(e){const t=wh(e),n=p.forwardRef((r,o)=>{const{children:i,...a}=r,c=p.Children.toArray(i),l=c.find(Ch);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 wh(e){const t=p.forwardRef((n,r)=>{const{children:o,...i}=n;if(p.isValidElement(o)){const a=Eh(o),c=jh(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 kh(e){const t=({children:n})=>s.jsx(s.Fragment,{children:n});return t.displayName=`${e}.Slottable`,t.__radixId=md,t}function Ch(e){return p.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===md}function jh(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 Eh(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 Th=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Te=Th.reduce((e,t)=>{const n=Ar(`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 gn(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 Ah(e,t=globalThis==null?void 0:globalThis.document){const n=gn(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 Rh="DismissableLayer",Oi="dismissableLayer.update",Oh="dismissableLayer.pointerDownOutside",_h="dismissableLayer.focusOutside",gc,yd=p.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),vo=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=Dh(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=$h(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 Ah(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)})});vo.displayName=Rh;var Ph="DismissableLayerBranch",Ih=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})});Ih.displayName=Ph;function Dh(e,t=globalThis==null?void 0:globalThis.document){const n=gn(e),r=p.useRef(!1),o=p.useRef(()=>{});return p.useEffect(()=>{const i=c=>{if(c.target&&!r.current){let l=function(){bd(Oh,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 $h(e,t=globalThis==null?void 0:globalThis.document){const n=gn(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 yn=globalThis!=null&&globalThis.document?p.useLayoutEffect:()=>{},Mh=td[" useId ".trim().toString()]||(()=>{}),Lh=0;function eo(e){const[t,n]=p.useState(Mh());return yn(()=>{n(r=>r??String(Lh++))},[e]),t?`radix-${t}`:""}const Nh=["top","right","bottom","left"],bn=Math.min,ht=Math.max,ss=Math.round,No=Math.floor,qt=e=>({x:e,y:e}),Bh={left:"right",right:"left",bottom:"top",top:"bottom"};function _i(e,t,n){return ht(e,bn(t,n))}function Qt(e,t){return typeof e=="function"?e(t):e}function Jt(e){return e.split("-")[0]}function Ir(e){return e.split("-")[1]}function ea(e){return e==="x"?"y":"x"}function ta(e){return e==="y"?"height":"width"}function zt(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function na(e){return ea(zt(e))}function Fh(e,t,n){n===void 0&&(n=!1);const r=Ir(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 zh(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"],qh=["top","bottom"],Uh=["bottom","top"];function Wh(e,t,n){switch(e){case"top":case"bottom":return n?t?xc:bc:t?bc:xc;case"left":case"right":return t?qh:Uh;default:return[]}}function Kh(e,t,n,r){const o=Ir(e);let i=Wh(Jt(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=Jt(e);return Bh[t]+e.slice(t.length)}function Vh(e){return{top:0,right:0,bottom:0,left:0,...e}}function xd(e){return typeof e!="number"?Vh(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=zt(t),a=na(t),c=ta(a),l=Jt(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(Ir(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 Hh(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}=Qt(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 Gh=50,Qh=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:a}=n,c=a.detectOverflow?a:{...a,detectOverflow:Hh},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<Gh&&(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}},Jh=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}=Qt(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=bn(d[w],I),O=bn(d[j],I),_=T,M=A-v[S]-O,q=A/2-v[S]/2+g,G=_i(_,q,M),J=!l.arrow&&Ir(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}}}),Yh=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}=Qt(e,t);if((n=i.arrow)!=null&&n.alignmentOffset)return{};const w=Jt(o),j=zt(c),C=Jt(c)===c,x=await(l.isRTL==null?void 0:l.isRTL(u.floating)),E=f||(C||!v?[is(c)]:zh(c)),P=S!=="none";!f&&P&&E.push(...Kh(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=Fh(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!==zt(G):!1)||T.every(L=>zt(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 $=zt(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 Nh.some(t=>e[t]>=0)}const Xh=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:o="referenceHidden",...i}=Qt(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 Zh(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),a=Jt(n),c=Ir(n),l=zt(n)==="y",u=vd.has(a)?-1:1,h=i&&l?-1:1,d=Qt(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 em=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 Zh(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}}}}},tm=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}=Qt(e,t),h={x:n,y:r},d=await i.detectOverflow(t,u),f=zt(Jt(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}}}}}},nm=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}=Qt(e,t),h={x:n,y:r},d=zt(o),f=ea(d);let m=h[f],S=h[d];const v=Qt(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(Jt(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}}}},rm=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}=Qt(e,t),h=await a.detectOverflow(t,u),d=Jt(o),f=Ir(o),m=zt(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=bn(v-h[b],j),E=bn(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=ht(h.left,0),O=ht(h.right,0),_=ht(h.top,0),M=ht(h.bottom,0);m?g=S-2*(T!==0||O!==0?T+O:ht(h.left,h.right)):A=v-2*(_!==0||M!==0?_+M:ht(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 Dr(e){return Sd(e)?(e.nodeName||"").toLowerCase():"#document"}function mt(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ut(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 mt(e).Node:!1}function _t(e){return xs()?e instanceof Element||e instanceof mt(e).Element:!1}function Yt(e){return xs()?e instanceof HTMLElement||e instanceof mt(e).HTMLElement:!1}function kc(e){return!xs()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof mt(e).ShadowRoot}function So(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Pt(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&o!=="inline"&&o!=="contents"}function om(e){return/^(table|td|th)$/.test(Dr(e))}function vs(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const sm=/transform|translate|scale|rotate|perspective|filter/,im=/paint|layout|strict|content/,An=e=>!!e&&e!=="none";let Bs;function ra(e){const t=_t(e)?Pt(e):e;return An(t.transform)||An(t.translate)||An(t.scale)||An(t.rotate)||An(t.perspective)||!oa()&&(An(t.backdropFilter)||An(t.filter))||sm.test(t.willChange||"")||im.test(t.contain||"")}function am(e){let t=xn(e);for(;Yt(t)&&!Rr(t);){if(ra(t))return t;if(vs(t))return null;t=xn(t)}return null}function oa(){return Bs==null&&(Bs=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Bs}function Rr(e){return/^(html|body|#document)$/.test(Dr(e))}function Pt(e){return mt(e).getComputedStyle(e)}function Ss(e){return _t(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function xn(e){if(Dr(e)==="html")return e;const t=e.assignedSlot||e.parentNode||kc(e)&&e.host||Ut(e);return kc(t)?t.host:t}function wd(e){const t=xn(e);return Rr(t)?e.ownerDocument?e.ownerDocument.body:e.body:Yt(t)&&So(t)?t:wd(t)}function io(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=mt(o);if(i){const c=Ii(a);return t.concat(a,a.visualViewport||[],So(o)?o:[],c&&n?io(c):[])}else return t.concat(o,io(o,[],n))}function Ii(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function kd(e){const t=Pt(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Yt(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 _t(e)?e:e.contextElement}function ur(e){const t=sa(e);if(!Yt(t))return qt(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 cm=qt(0);function Cd(e){const t=mt(e);return!oa()||!t.visualViewport?cm:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function lm(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==mt(e)?!1:t}function Un(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=sa(e);let a=qt(1);t&&(r?_t(r)&&(a=ur(r)):a=ur(e));const c=lm(i,n,r)?Cd(i):qt(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=mt(i),m=r&&_t(r)?mt(r):r;let S=f,v=Ii(S);for(;v&&r&&m!==S;){const b=ur(v),w=v.getBoundingClientRect(),j=Pt(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=mt(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:Un(Ut(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 dm(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i=o==="fixed",a=Ut(r),c=t?vs(t.floating):!1;if(r===a||c&&i)return n;let l={scrollLeft:0,scrollTop:0},u=qt(1);const h=qt(0),d=Yt(r);if((d||!d&&!i)&&((Dr(r)!=="body"||So(a))&&(l=Ss(r)),d)){const m=Un(r);u=ur(r),h.x=m.x+r.clientLeft,h.y=m.y+r.clientTop}const f=a&&!d&&!i?jd(a,l):qt(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 um(e){return Array.from(e.getClientRects())}function pm(e){const t=Ut(e),n=Ss(e),r=e.ownerDocument.body,o=ht(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=ht(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+ws(e);const c=-n.scrollTop;return Pt(r).direction==="rtl"&&(a+=ht(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:a,y:c}}const Cc=25;function fm(e,t){const n=mt(e),r=Ut(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 hm(e,t){const n=Un(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Yt(e)?ur(e):qt(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=fm(e,n);else if(t==="document")r=pm(Ut(e));else if(_t(t))r=hm(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=xn(e);return n===t||!_t(n)||Rr(n)?!1:Pt(n).position==="fixed"||Ed(n,t)}function mm(e,t){const n=t.get(e);if(n)return n;let r=io(e,[],!1).filter(c=>_t(c)&&Dr(c)!=="body"),o=null;const i=Pt(e).position==="fixed";let a=i?xn(e):e;for(;_t(a)&&!Rr(a);){const c=Pt(a),l=ra(a);!l&&c.position==="fixed"&&(o=null),(i?!l&&!o:!l&&c.position==="static"&&!!o&&(o.position==="absolute"||o.position==="fixed")||So(a)&&!l&&Ed(e,a))?r=r.filter(h=>h!==a):o=c,a=xn(a)}return t.set(e,r),r}function gm(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const a=[...n==="clippingAncestors"?vs(t)?[]:mm(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=ht(m.top,l),u=bn(m.right,u),h=bn(m.bottom,h),d=ht(m.left,d)}return{width:u-d,height:h-l,x:d,y:l}}function ym(e){const{width:t,height:n}=kd(e);return{width:t,height:n}}function bm(e,t,n){const r=Yt(t),o=Ut(t),i=n==="fixed",a=Un(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=qt(0);function u(){l.x=ws(o)}if(r||!r&&!i)if((Dr(t)!=="body"||So(o))&&(c=Ss(t)),r){const m=Un(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):qt(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 Pt(e).position==="static"}function Ec(e,t){if(!Yt(e)||Pt(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Ut(e)===n&&(n=n.ownerDocument.body),n}function Td(e,t){const n=mt(e);if(vs(e))return n;if(!Yt(e)){let o=xn(e);for(;o&&!Rr(o);){if(_t(o)&&!Fs(o))return o;o=xn(o)}return n}let r=Ec(e,t);for(;r&&om(r)&&Fs(r);)r=Ec(r,t);return r&&Rr(r)&&Fs(r)&&!ra(r)?n:r||am(e)||n}const xm=async function(e){const t=this.getOffsetParent||Td,n=this.getDimensions,r=await n(e.floating);return{reference:bm(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function vm(e){return Pt(e).direction==="rtl"}const Sm={convertOffsetParentRelativeRectToViewportRelativeRect:dm,getDocumentElement:Ut,getClippingRect:gm,getOffsetParent:Td,getElementRects:xm,getClientRects:um,getDimensions:ym,getScale:ur,isElement:_t,isRTL:vm};function Ad(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function wm(e,t){let n=null,r;const o=Ut(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=No(d),v=No(o.clientWidth-(h+f)),b=No(o.clientHeight-(d+m)),w=No(h),C={rootMargin:-S+"px "+-v+"px "+-b+"px "+-w+"px",threshold:ht(0,bn(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 km(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?io(u):[],...t?io(t):[]]:[];h.forEach(w=>{o&&w.addEventListener("scroll",n,{passive:!0}),i&&w.addEventListener("resize",n)});const d=u&&c?wm(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?Un(e):null;l&&b();function b(){const w=Un(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 Cm=em,jm=tm,Em=Yh,Tm=rm,Am=Xh,Tc=Jh,Rm=nm,Om=(e,t,n)=>{const r=new Map,o={platform:Sm,...n},i={...o.platform,_c:r};return Qh(e,t,{...o,platform:i})};var _m=typeof document<"u",Pm=function(){},Xo=_m?p.useLayoutEffect:Pm;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 Im(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),Om(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 Dm=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):{}}}},$m=(e,t)=>{const n=Cm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Mm=(e,t)=>{const n=jm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Lm=(e,t)=>({fn:Rm(e).fn,options:[e,t]}),Nm=(e,t)=>{const n=Em(e);return{name:n.name,fn:n.fn,options:[e,t]}},Bm=(e,t)=>{const n=Tm(e);return{name:n.name,fn:n.fn,options:[e,t]}},Fm=(e,t)=>{const n=Am(e);return{name:n.name,fn:n.fn,options:[e,t]}},zm=(e,t)=>{const n=Dm(e);return{name:n.name,fn:n.fn,options:[e,t]}};var qm="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=qm;var Um=Od;function Wm(e){const[t,n]=p.useState(void 0);return yn(()=>{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,$r]=wn(ia),[Km,Pd]=_d(ia),Id=e=>{const{__scopePopper:t,children:n}=e,[r,o]=p.useState(null);return s.jsx(Km,{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",[Vm,Hm]=_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=Wm(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(Qm),altBoundary:_},{refs:q,floatingStyles:G,placement:J,isPositioned:H,middlewareData:L}=Im({strategy:"fixed",placement:I,whileElementsMounted:(...Ee)=>km(...Ee,{animationFrame:m==="always"}),elements:{reference:b.anchor},middleware:[$m({mainAxis:o+g,alignmentAxis:a}),l&&Mm({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?Lm():void 0,...M}),l&&Nm({...M}),Bm({...M,apply:({elements:Ee,rects:ge,availableWidth:Je,availableHeight:tt})=>{const{width:Fe,height:Ke}=ge.reference,gt=Ee.floating.style;gt.setProperty("--radix-popper-available-width",`${Je}px`),gt.setProperty("--radix-popper-available-height",`${tt}px`),gt.setProperty("--radix-popper-anchor-width",`${Fe}px`),gt.setProperty("--radix-popper-anchor-height",`${Ke}px`)}}),x&&zm({element:x,padding:c}),Jm({arrowWidth:A,arrowHeight:g}),f&&Fm({strategy:"referenceHidden",...M})]}),[$,X]=Bd(J),W=gn(S);yn(()=>{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 yn(()=>{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(Vm,{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",Gm={top:"bottom",right:"left",bottom:"top",left:"right"},Nd=p.forwardRef(function(t,n){const{__scopePopper:r,...o}=t,i=Hm(Ld,r),a=Gm[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(Um,{...o,ref:n,style:{...o.style,display:"block"}})})});Nd.displayName=Ld;function Qm(e){return e!==null}var Jm=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 Ym=Id,ks=$d,ca=Md,la=Nd,Xm="Portal",wo=p.forwardRef((e,t)=>{var c;const{container:n,...r}=e,[o,i]=p.useState(!1);yn(()=>i(!0),[]);const a=n||o&&((c=globalThis==null?void 0:globalThis.document)==null?void 0:c.body);return a?Sh.createPortal(s.jsx(Te.div,{...r,ref:t}),a):null});wo.displayName=Xm;function Zm(e,t){return p.useReducer((n,r)=>t[n][r]??n,e)}var wt=e=>{const{present:t,children:n}=e,r=eg(t),o=typeof n=="function"?n({present:r.isPresent}):p.Children.only(n),i=Oe(r.ref,tg(o));return typeof n=="function"||r.isPresent?p.cloneElement(o,{ref:i}):null};wt.displayName="Presence";function eg(e){const[t,n]=p.useState(),r=p.useRef(null),o=p.useRef(e),i=p.useRef("none"),a=e?"mounted":"unmounted",[c,l]=Zm(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return p.useEffect(()=>{const u=Bo(r.current);i.current=c==="mounted"?u:"none"},[c]),yn(()=>{const u=r.current,h=o.current;if(h!==e){const f=i.current,m=Bo(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]),yn(()=>{if(t){let u;const h=t.ownerDocument.defaultView??window,d=m=>{const v=Bo(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=Bo(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 Bo(e){return(e==null?void 0:e.animationName)||"none"}function tg(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 ng=td[" useInsertionEffect ".trim().toString()]||yn;function da({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,i,a]=rg({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=og(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 rg({defaultProp:e,onChange:t}){const[n,r]=p.useState(e),o=p.useRef(n),i=p.useRef(t);return ng(()=>{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 og(e){return typeof e=="function"}var sg=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"}),ig="VisuallyHidden",Fd=p.forwardRef((e,t)=>s.jsx(Te.span,{...e,ref:t,style:{...sg,...e.style}}));Fd.displayName=ig;var ag=Fd,[Cs]=wn("Tooltip",[$r]),js=$r(),zd="TooltipProvider",cg=700,Di="tooltip.open",[lg,ua]=Cs(zd),qd=e=>{const{__scopeTooltip:t,delayDuration:n=cg,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(lg,{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 ao="Tooltip",[dg,ko]=Cs(ao),Ud=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:a,delayDuration:c}=e,l=ua(ao,e.__scopeTooltip),u=js(t),[h,d]=p.useState(null),f=eo(),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:ao}),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(Ym,{...u,children:s.jsx(dg,{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=ao;var $i="TooltipTrigger",Wd=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=ko($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",[ug,pg]=Cs(pa,{forceMount:void 0}),Kd=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:o}=e,i=ko(pa,t);return s.jsx(ug,{scope:t,forceMount:n,children:s.jsx(wt,{present:n||i.open,children:s.jsx(wo,{asChild:!0,container:o,children:r})})})};Kd.displayName=pa;var Or="TooltipContent",Vd=p.forwardRef((e,t)=>{const n=pg(Or,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,a=ko(Or,e.__scopeTooltip);return s.jsx(wt,{present:r||a.open,children:a.disableHoverableContent?s.jsx(Hd,{side:o,...i,ref:t}):s.jsx(fg,{side:o,...i,ref:t})})}),fg=p.forwardRef((e,t)=>{const n=ko(Or,e.__scopeTooltip),r=ua(Or,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=bg(w,b.getBoundingClientRect()),C=xg(w,j),x=vg(v.getBoundingClientRect()),E=wg([...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=!Sg(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})}),[hg,mg]=Cs(ao,{isInside:!1}),gg=kh("TooltipContent"),Hd=p.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:a,...c}=e,l=ko(Or,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(vo,{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(gg,{children:r}),s.jsx(hg,{scope:n,isInside:!0,children:s.jsx(ag,{id:l.contentId,role:"tooltip",children:o||r})})]})})});Vd.displayName=Or;var Gd="TooltipArrow",yg=p.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=js(n);return mg(Gd,n).isInside?null:s.jsx(la,{...o,...r,ref:t})});yg.displayName=Gd;function bg(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 xg(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 vg(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 Sg(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 wg(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),kg(t)}function kg(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 Cg=qd,jg=Ud,Eg=Wd,Tg=Kd,Ag=Vd;function Qd({content:e,children:t,side:n="right",align:r="center",sideOffset:o=6,delayMs:i=200,container:a}){return s.jsxs(jg,{delayDuration:i,children:[s.jsx(Eg,{asChild:!0,children:t}),s.jsx(Tg,{container:a,children:s.jsx(Ag,{side:n,align:r,sideOffset:o,style:{background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:Sn.sm,padding:`${be[1]} ${be[2]}`,fontSize:Ze.sm,boxShadow:pe("shadowMd"),zIndex:so.tooltip,userSelect:"none"},children:e})})]})}const Rg=Cg;var qs="focusScope.autoFocusOnMount",Us="focusScope.autoFocusOnUnmount",Rc={bubbles:!1,cancelable:!0},Og="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=gn(o),h=gn(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:on(d.current,{select:!0})},b=function(C){if(m.paused||!c)return;const x=C.relatedTarget;x!==null&&(c.contains(x)||on(d.current,{select:!0}))},w=function(C){if(document.activeElement===document.body)for(const E of C)E.removedNodes.length>0&&on(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(Mg(Jd(c)),{select:!0}),document.activeElement===v&&on(c))}return()=>{c.removeEventListener(qs,u),setTimeout(()=>{const w=new CustomEvent(Us,Rc);c.addEventListener(Us,h),c.dispatchEvent(w),w.defaultPrevented||on(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]=Pg(j);C&&x?!v.shiftKey&&w===x?(v.preventDefault(),n&&on(C,{select:!0})):v.shiftKey&&w===C&&(v.preventDefault(),n&&on(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=Og;function _g(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(on(r,{select:t}),document.activeElement!==n)return}function Pg(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(!Ig(n,{upTo:t}))return n}function Ig(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 Dg(e){return e instanceof HTMLInputElement&&"select"in e}function on(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Dg(e)&&t&&e.select()}}var _c=$g();function $g(){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 Mg(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 Bt=function(){return Bt=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},Bt.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 Lg(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",Ng="with-scroll-bars-hidden",Bg="--removed-body-scroll-bar-size";function Ks(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Fg(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 zg=typeof window<"u"?p.useLayoutEffect:p.useEffect,Dc=new WeakMap;function qg(e,t){var n=Fg(null,function(r){return e.forEach(function(o){return Ks(o,r)})});return zg(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 Ug(e){return e}function Wg(e,t){t===void 0&&(t=Ug);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 Kg(e){e===void 0&&(e={});var t=Wg(null);return t.options=Bt({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,Bt({},n))};Xd.isSideCarExport=!0;function Vg(e,t){return e.useMedium(t),Xd}var Zd=Kg(),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=qg([n,t]),A=Bt(Bt({},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),Bt(Bt({},A),{ref:P})):p.createElement(j,Bt({},A,{className:l,ref:P}),c))});Ts.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Ts.classNames={fullWidth:es,zeroRight:Zo};var Hg=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function Gg(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Hg();return t&&e.setAttribute("nonce",t),e}function Qg(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Jg(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Yg=function(){var e=0,t=null;return{add:function(n){e==0&&(t=Gg())&&(Qg(t,n),Jg(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Xg=function(){var e=Yg();return function(t,n){p.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},eu=function(){var e=Xg(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Zg={left:0,top:0,right:0,gap:0},Hs=function(e){return parseInt(e||"",10)||0},ey=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)]},ty=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Zg;var t=ey(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])}},ny=eu(),pr="data-scroll-locked",ry=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(Ng,` {
12
+ overflow: hidden `).concat(r,`;
13
+ padding-right: `).concat(c,"px ").concat(r,`;
14
+ }
15
+ body[`).concat(pr,`] {
16
+ overflow: hidden `).concat(r,`;
17
+ overscroll-behavior: contain;
18
+ `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&`
19
+ padding-left: `.concat(o,`px;
20
+ padding-top: `).concat(i,`px;
21
+ padding-right: `).concat(a,`px;
22
+ margin-left:0;
23
+ margin-top:0;
24
+ margin-right: `).concat(c,"px ").concat(r,`;
25
+ `),n==="padding"&&"padding-right: ".concat(c,"px ").concat(r,";")].filter(Boolean).join(""),`
26
+ }
27
+
28
+ .`).concat(Zo,` {
29
+ right: `).concat(c,"px ").concat(r,`;
30
+ }
31
+
32
+ .`).concat(es,` {
33
+ margin-right: `).concat(c,"px ").concat(r,`;
34
+ }
35
+
36
+ .`).concat(Zo," .").concat(Zo,` {
37
+ right: 0 `).concat(r,`;
38
+ }
39
+
40
+ .`).concat(es," .").concat(es,` {
41
+ margin-right: 0 `).concat(r,`;
42
+ }
43
+
44
+ body[`).concat(pr,`] {
45
+ `).concat(Bg,": ").concat(c,`px;
46
+ }
47
+ `)},$c=function(){var e=parseInt(document.body.getAttribute(pr)||"0",10);return isFinite(e)?e:0},oy=function(){p.useEffect(function(){return document.body.setAttribute(pr,($c()+1).toString()),function(){var e=$c()-1;e<=0?document.body.removeAttribute(pr):document.body.setAttribute(pr,e.toString())}},[])},sy=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r;oy();var i=p.useMemo(function(){return ty(o)},[o]);return p.createElement(ny,{styles:ry(i,!t,o,n?"":"!important")})},Mi=!1;if(typeof window<"u")try{var Fo=Object.defineProperty({},"passive",{get:function(){return Mi=!0,!0}});window.addEventListener("test",Fo,Fo),window.removeEventListener("test",Fo,Fo)}catch{Mi=!1}var Zn=Mi?{passive:!1}:!1,iy=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&&!iy(e)&&n[t]==="visible")},ay=function(e){return tu(e,"overflowY")},cy=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},ly=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},dy=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},nu=function(e,t){return e==="v"?ay(t):cy(t)},ru=function(e,t){return e==="v"?ly(t):dy(t)},uy=function(e,t){return e==="h"&&t==="rtl"?-1:1},py=function(e,t,n,r,o){var i=uy(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},zo=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},fy=function(e,t){return e[0]===t[0]&&e[1]===t[1]},hy=function(e){return`
48
+ .block-interactivity-`.concat(e,` {pointer-events: none;}
49
+ .allow-interactivity-`).concat(e,` {pointer-events: all;}
50
+ `)},my=0,er=[];function gy(e){var t=p.useRef([]),n=p.useRef([0,0]),r=p.useRef(),o=p.useState(my++)[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=Lg([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=zo(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 py(_,b,v,_==="h"?C:x)},[]),l=p.useCallback(function(v){var b=v;if(!(!er.length||er[er.length-1]!==i)){var w="deltaY"in b?Lc(b):zo(b),j=t.current.filter(function(E){return E.name===b.type&&(E.target===b.target||b.target===E.shadowParent)&&fy(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:yy(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=zo(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,zo(v),v.target,c(v,e.lockRef.current))},[]);p.useEffect(function(){return er.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,Zn),document.addEventListener("touchmove",l,Zn),document.addEventListener("touchstart",h,Zn),function(){er=er.filter(function(v){return v!==i}),document.removeEventListener("wheel",l,Zn),document.removeEventListener("touchmove",l,Zn),document.removeEventListener("touchstart",h,Zn)}},[]);var m=e.removeScrollBar,S=e.inert;return p.createElement(p.Fragment,null,S?p.createElement(i,{styles:hy(o)}):null,m?p.createElement(sy,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function yy(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const by=Vg(Zd,gy);var As=p.forwardRef(function(e,t){return p.createElement(Ts,Bt({},e,{ref:t,sideCar:by}))});As.classNames=Ts.classNames;var xy=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},tr=new WeakMap,qo=new WeakMap,Uo={},Gs=0,ou=function(e){return e&&(e.host||ou(e.parentNode))},vy=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})},Sy=function(e,t,n,r){var o=vy(t,Array.isArray(e)?e:[e]);Uo[n]||(Uo[n]=new WeakMap);var i=Uo[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=(tr.get(f)||0)+1,b=(i.get(f)||0)+1;tr.set(f,v),i.set(f,b),a.push(f),v===1&&S&&qo.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=tr.get(d)-1,m=i.get(d)-1;tr.set(d,f),i.set(d,m),f||(qo.has(d)||d.removeAttribute(r),qo.delete(d)),m||d.removeAttribute(n)}),Gs--,Gs||(tr=new WeakMap,tr=new WeakMap,qo=new WeakMap,Uo={})}},ha=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=xy(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live], script"))),Sy(r,o,n,"aria-hidden")):function(){return null}},Rs="Dialog",[su]=wn(Rs),[wy,It]=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(wy,{scope:t,triggerRef:c,contentRef:l,contentId:eo(),titleId:eo(),descriptionId:eo(),open:u,onOpenChange:h,onOpenToggle:p.useCallback(()=>h(d=>!d),[h]),modal:a,children:n})};iu.displayName=Rs;var au="DialogTrigger",ky=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(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)})});ky.displayName=au;var ma="DialogPortal",[Cy,cu]=su(ma,{forceMount:void 0}),lu=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=It(ma,t);return s.jsx(Cy,{scope:t,forceMount:n,children:p.Children.map(r,a=>s.jsx(wt,{present:n||i.open,children:s.jsx(wo,{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=It(ls,e.__scopeDialog);return i.modal?s.jsx(wt,{present:r||i.open,children:s.jsx(Ey,{...o,ref:t})}):null});du.displayName=ls;var jy=Ar("DialogOverlay.RemoveScroll"),Ey=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(ls,n);return s.jsx(As,{as:jy,allowPinchZoom:!0,shards:[o.contentRef],children:s.jsx(Te.div,{"data-state":ya(o.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Wn="DialogContent",uu=p.forwardRef((e,t)=>{const n=cu(Wn,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=It(Wn,e.__scopeDialog);return s.jsx(wt,{present:r||i.open,children:i.modal?s.jsx(Ty,{...o,ref:t}):s.jsx(Ay,{...o,ref:t})})});uu.displayName=Wn;var Ty=p.forwardRef((e,t)=>{const n=It(Wn,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())})}),Ay=p.forwardRef((e,t)=>{const n=It(Wn,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=It(Wn,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(vo,{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(Iy,{contentRef:l,descriptionId:c.descriptionId})]})]})}),ga="DialogTitle",fu=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(ga,n);return s.jsx(Te.h2,{id:o.titleId,...r,ref:t})});fu.displayName=ga;var hu="DialogDescription",Ry=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(hu,n);return s.jsx(Te.p,{id:o.descriptionId,...r,ref:t})});Ry.displayName=hu;var mu="DialogClose",Oy=p.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=It(mu,n);return s.jsx(Te.button,{type:"button",...r,ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))})});Oy.displayName=mu;function ya(e){return e?"open":"closed"}var gu="DialogTitleWarning",[Rj,yu]=xh(gu,{contentName:Wn,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.
51
+
52
+ If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
53
+
54
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return p.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Py="DialogDescriptionWarning",Iy=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${yu(Py).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},Dy=iu,$y=lu,My=du,Ly=uu,Ny=fu;function bu(e){const t=e+"CollectionProvider",[n,r]=wn(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=Ar(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=Ar(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 By=p.createContext(void 0);function Fy(e){const t=p.useContext(By);return e||t||"ltr"}var Qs="rovingFocusGroup.onEntryFocus",zy={bubbles:!1,cancelable:!0},Co="RovingFocusGroup",[Li,xu,qy]=bu(Co),[Uy,vu]=wn(Co,[qy]),[Wy,Ky]=Uy(Co),Su=p.forwardRef((e,t)=>s.jsx(Li.Provider,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Li.Slot,{scope:e.__scopeRovingFocusGroup,children:s.jsx(Vy,{...e,ref:t})})}));Su.displayName=Co;var Vy=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=Fy(i),[v,b]=da({prop:a,defaultProp:c??null,onChange:l,caller:Co}),[w,j]=p.useState(!1),C=gn(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(Wy,{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,zy);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=eo(),u=i||l,h=Ky(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=Qy(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?Jy(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 Hy={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Gy(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Qy(e,t,n){const r=Gy(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Hy[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 Jy(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Yy=Su,Xy=ku,Ni=["Enter"," "],Zy=["ArrowDown","PageUp","Home"],ju=["ArrowUp","PageDown","End"],eb=[...Zy,...ju],tb={ltr:[...Ni,"ArrowRight"],rtl:[...Ni,"ArrowLeft"]},nb={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Os="Menu",[co,rb,ob]=bu(Os),[Hn,Eu]=wn(Os,[ob,$r,vu]),ba=$r(),Tu=vu(),[Oj,Gn]=Hn(Os),[_j,jo]=Hn(Os),sb="MenuAnchor",xa=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ba(n);return s.jsx(ks,{...o,...r,ref:t})});xa.displayName=sb;var va="MenuPortal",[ib,Au]=Hn(va,{forceMount:void 0}),Ru=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Gn(va,t);return s.jsx(ib,{scope:t,forceMount:n,children:s.jsx(wt,{present:n||i.open,children:s.jsx(wo,{asChild:!0,container:o,children:r})})})};Ru.displayName=va;var vt="MenuContent",[ab,Sa]=Hn(vt),Ou=p.forwardRef((e,t)=>{const n=Au(vt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Gn(vt,e.__scopeMenu),a=jo(vt,e.__scopeMenu);return s.jsx(co.Provider,{scope:e.__scopeMenu,children:s.jsx(wt,{present:r||i.open,children:s.jsx(co.Slot,{scope:e.__scopeMenu,children:a.modal?s.jsx(cb,{...o,ref:t}):s.jsx(lb,{...o,ref:t})})})})}),cb=p.forwardRef((e,t)=>{const n=Gn(vt,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)})}),lb=p.forwardRef((e,t)=>{const n=Gn(vt,e.__scopeMenu);return s.jsx(wa,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),db=Ar("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=Gn(vt,n),w=jo(vt,n),j=ba(n),C=Tu(n),x=rb(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:db,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=wb(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)&&Cb($,(te=_.current)==null?void 0:te.area)},[]);return s.jsx(ab,{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(vo,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:d,onInteractOutside:f,onDismiss:m,children:s.jsx(Yy,{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||!eb.includes($.key))return;$.preventDefault();const ee=x().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);ju.includes($.key)&&ee.reverse(),vb(ee)}),onBlur:de(e.onBlur,$=>{$.currentTarget.contains($.target)||(window.clearTimeout(I.current),T.current="")}),onPointerMove:de(e.onPointerMove,lo($=>{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=vt;var ub="MenuGroup",ka=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{role:"group",...r,ref:t})});ka.displayName=ub;var pb="MenuLabel",_u=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return s.jsx(Te.div,{...r,ref:t})});_u.displayName=pb;var ds="MenuItem",Bc="menu.itemSelect",_s=p.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=p.useRef(null),a=jo(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(co.ItemSlot,{scope:n,disabled:r,textValue:o??f,children:s.jsx(Xy,{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,lo(S=>{r?a.onItemLeave(S):(a.onItemEnter(S),S.defaultPrevented||S.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:de(e.onPointerLeave,lo(S=>a.onItemLeave(S))),onFocus:de(e.onFocus,()=>d(!0)),onBlur:de(e.onBlur,()=>d(!1))})})})}),fb="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=fb;var Du="MenuRadioGroup",[hb,mb]=Hn(Du,{value:void 0,onValueChange:()=>{}}),$u=p.forwardRef((e,t)=>{const{value:n,onValueChange:r,...o}=e,i=gn(r);return s.jsx(hb,{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=mb(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,gb]=Hn(Ca,{checked:!1}),Bu=p.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=gb(Ca,n);return s.jsx(wt,{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 yb="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=yb;var bb="MenuArrow",zu=p.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=ba(n);return s.jsx(la,{...o,...r,ref:t})});zu.displayName=bb;var xb="MenuSub",[Pj,qu]=Hn(xb),Hr="MenuSubTrigger",Uu=p.forwardRef((e,t)=>{const n=Gn(Hr,e.__scopeMenu),r=jo(Hr,e.__scopeMenu),o=qu(Hr,e.__scopeMenu),i=Sa(Hr,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,lo(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,lo(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===" "||tb[r.dir].includes(d.key)&&(n.onOpenChange(!0),(m=n.content)==null||m.focus(),d.preventDefault())})})})});Uu.displayName=Hr;var Wu="MenuSubContent",Ku=p.forwardRef((e,t)=>{const n=Au(vt,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Gn(vt,e.__scopeMenu),a=jo(vt,e.__scopeMenu),c=qu(Wu,e.__scopeMenu),l=p.useRef(null),u=Oe(t,l);return s.jsx(co.Provider,{scope:e.__scopeMenu,children:s.jsx(wt,{present:r||i.open,children:s.jsx(co.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=nb[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 vb(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Sb(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function wb(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=Sb(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 kb(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 Cb(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return kb(n,t)}function lo(e){return t=>t.pointerType==="mouse"?e(t):void 0}var jb=xa,Eb=Ru,Tb=Ou,Ab=ka,Rb=_u,Ob=_s,_b=Iu,Pb=$u,Ib=Lu,Db=Bu,$b=Fu,Mb=zu,Lb=Uu,Nb=Ku,Hu="DropdownMenu",[Bb]=wn(Hu,[Eu]),dt=Eu(),[Ij,Gu]=Bb(Hu),Qu="DropdownMenuTrigger",Fb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=Gu(Qu,n),a=dt(n);return s.jsx(jb,{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())})})})});Fb.displayName=Qu;var zb="DropdownMenuPortal",Ju=e=>{const{__scopeDropdownMenu:t,...n}=e,r=dt(t);return s.jsx(Eb,{...r,...n})};Ju.displayName=zb;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(Tb,{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 qb="DropdownMenuGroup",Ub=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Ab,{...o,...r,ref:t})});Ub.displayName=qb;var Wb="DropdownMenuLabel",Zu=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Rb,{...o,...r,ref:t})});Zu.displayName=Wb;var Kb="DropdownMenuItem",ep=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Ob,{...o,...r,ref:t})});ep.displayName=Kb;var Vb="DropdownMenuCheckboxItem",Hb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(_b,{...o,...r,ref:t})});Hb.displayName=Vb;var Gb="DropdownMenuRadioGroup",Qb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Pb,{...o,...r,ref:t})});Qb.displayName=Gb;var Jb="DropdownMenuRadioItem",Yb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Ib,{...o,...r,ref:t})});Yb.displayName=Jb;var Xb="DropdownMenuItemIndicator",Zb=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Db,{...o,...r,ref:t})});Zb.displayName=Xb;var ex="DropdownMenuSeparator",tp=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx($b,{...o,...r,ref:t})});tp.displayName=ex;var tx="DropdownMenuArrow",nx=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Mb,{...o,...r,ref:t})});nx.displayName=tx;var rx="DropdownMenuSubTrigger",ox=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Lb,{...o,...r,ref:t})});ox.displayName=rx;var sx="DropdownMenuSubContent",ix=p.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=dt(n);return s.jsx(Nb,{...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)"}})});ix.displayName=sx;var ax=Ju,cx=Xu,lx=Zu,dx=ep,ux=tp;const px=p.forwardRef(({container:e,style:t,sideOffset:n=4,...r},o)=>s.jsx(ax,{container:e,children:s.jsx(cx,{ref:o,sideOffset:n,style:{minWidth:180,background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:Sn.md,boxShadow:pe("shadowMd"),padding:be[1],zIndex:so.popover,...t},...r})}));px.displayName="DropdownMenuContent";const fx=p.forwardRef(({style:e,...t},n)=>s.jsx(dx,{ref:n,style:{display:"flex",alignItems:"center",gap:be[2],padding:`${be[1]} ${be[2]}`,fontSize:Ze.sm,borderRadius:Sn.sm,cursor:"default",outline:"none",userSelect:"none",...e},...t}));fx.displayName="DropdownMenuItem";const hx=p.forwardRef(({style:e,...t},n)=>s.jsx(ux,{ref:n,style:{height:1,background:pe("borderSubtle"),margin:`${be[1]} 0`,...e},...t}));hx.displayName="DropdownMenuSeparator";const mx=p.forwardRef(({style:e,...t},n)=>s.jsx(lx,{ref:n,style:{padding:`${be[1]} ${be[2]}`,fontSize:Ze.xs,color:pe("textMuted"),textTransform:"uppercase",letterSpacing:"0.04em",...e},...t}));mx.displayName="DropdownMenuLabel";var np="Popover",[rp]=wn(np,[$r]),Ps=$r(),[Dj,kn]=rp(np),op="PopoverAnchor",gx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=kn(op,n),i=Ps(n),{onCustomAnchorAdd:a,onCustomAnchorRemove:c}=o;return p.useEffect(()=>(a(),()=>c()),[a,c]),s.jsx(ks,{...i,...r,ref:t})});gx.displayName=op;var sp="PopoverTrigger",yx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=kn(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})});yx.displayName=sp;var Ea="PopoverPortal",[bx,xx]=rp(Ea,{forceMount:void 0}),ip=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=kn(Ea,t);return s.jsx(bx,{scope:t,forceMount:n,children:s.jsx(wt,{present:n||i.open,children:s.jsx(wo,{asChild:!0,container:o,children:r})})})};ip.displayName=Ea;var _r="PopoverContent",ap=p.forwardRef((e,t)=>{const n=xx(_r,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=kn(_r,e.__scopePopover);return s.jsx(wt,{present:r||i.open,children:i.modal?s.jsx(Sx,{...o,ref:t}):s.jsx(wx,{...o,ref:t})})});ap.displayName=_r;var vx=Ar("PopoverContent.RemoveScroll"),Sx=p.forwardRef((e,t)=>{const n=kn(_r,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:vx,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})})})}),wx=p.forwardRef((e,t)=>{const n=kn(_r,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=kn(_r,n),m=Ps(n);return fa(),s.jsx(Es,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:s.jsx(vo,{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",kx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=kn(lp,n);return s.jsx(Te.button,{type:"button",...r,ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))})});kx.displayName=lp;var Cx="PopoverArrow",jx=p.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Ps(n);return s.jsx(la,{...o,...r,ref:t})});jx.displayName=Cx;function dp(e){return e?"open":"closed"}var Ex=ip,Tx=ap;const Ax=p.forwardRef(({container:e,style:t,sideOffset:n=6,...r},o)=>s.jsx(Ex,{container:e,children:s.jsx(Tx,{ref:o,sideOffset:n,style:{background:pe("surfaceElevated"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:Sn.md,boxShadow:pe("shadowMd"),padding:be[3],zIndex:so.popover,minWidth:220,...t},...r})}));Ax.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 to({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 Rx({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:Sn.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},Ox=(e=>e?Fc(e):Fc),_x=e=>e;function Px(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=Ox(e),n=r=>Px(t,r);return Object.assign(n,t),n},Ix=(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},Dx=(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 $x(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):Dx(e,t):Wc({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Mr(e){const t=qe.useRef(void 0);return n=>{const r=e(n);return $x(t.current,r)?t.current:t.current=r}}const Mx=/\{\{\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(Mx)){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 Lx(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 Nx(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 Bx(){var e;if(typeof window<"u")try{(e=window.localStorage)==null||e.removeItem("dql-app-mode")}catch{}return"studio"}function Fx(){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 zx(){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 qx={mainView:zx(),agentLogRun:void 0,settingsTab:"overview",themeMode:Fx(),appMode:Bx(),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=bt();while(t.has(r));return t.add(r),r===n.id?n:{...n,id:r}})}function Ux(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:bt()}: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?Nx(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=Ix((e,t)=>({...qx,dispatch:n=>{const r=Ux(t(),n);e(r)}})),Pn=Ge,Wx=p.createContext(null);function Kx({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(Mr(r=>{const{dispatch:o,...i}=r;return i})),t=Ge(r=>r.dispatch);return p.useContext(Wx)??{state:e,dispatch:t}}function Cn(){return Ge(e=>e.dispatch)}function bt(){return`cell_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ra(e,t=""){const n={id:bt(),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 Vx="modulepreload",Hx=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=Hx(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":Vx,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
+ * @license lucide-react v0.563.0 - ISC
56
+ *
57
+ * This source code is licensed under the ISC license.
58
+ * See the LICENSE file in the root directory of this source tree.
59
+ */const fp=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/**
60
+ * @license lucide-react v0.563.0 - ISC
61
+ *
62
+ * This source code is licensed under the ISC license.
63
+ * See the LICENSE file in the root directory of this source tree.
64
+ */const Gx=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
65
+ * @license lucide-react v0.563.0 - ISC
66
+ *
67
+ * This source code is licensed under the ISC license.
68
+ * See the LICENSE file in the root directory of this source tree.
69
+ */const Qx=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase());/**
70
+ * @license lucide-react v0.563.0 - ISC
71
+ *
72
+ * This source code is licensed under the ISC license.
73
+ * See the LICENSE file in the root directory of this source tree.
74
+ */const Vc=e=>{const t=Qx(e);return t.charAt(0).toUpperCase()+t.slice(1)};/**
75
+ * @license lucide-react v0.563.0 - ISC
76
+ *
77
+ * This source code is licensed under the ISC license.
78
+ * See the LICENSE file in the root directory of this source tree.
79
+ */var Jx={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
80
+ * @license lucide-react v0.563.0 - ISC
81
+ *
82
+ * This source code is licensed under the ISC license.
83
+ * See the LICENSE file in the root directory of this source tree.
84
+ */const Yx=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};/**
85
+ * @license lucide-react v0.563.0 - ISC
86
+ *
87
+ * This source code is licensed under the ISC license.
88
+ * See the LICENSE file in the root directory of this source tree.
89
+ */const Xx=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,...Jx,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:fp("lucide",o),...!i&&!Yx(c)&&{"aria-hidden":"true"},...c},[...a.map(([u,h])=>p.createElement(u,h)),...Array.isArray(i)?i:[i]]));/**
90
+ * @license lucide-react v0.563.0 - ISC
91
+ *
92
+ * This source code is licensed under the ISC license.
93
+ * See the LICENSE file in the root directory of this source tree.
94
+ */const ne=(e,t)=>{const n=p.forwardRef(({className:r,...o},i)=>p.createElement(Xx,{ref:i,iconNode:t,className:fp(`lucide-${Gx(Vc(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Vc(e),n};/**
95
+ * @license lucide-react v0.563.0 - ISC
96
+ *
97
+ * This source code is licensed under the ISC license.
98
+ * See the LICENSE file in the root directory of this source tree.
99
+ */const Zx=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],ev=ne("arrow-down",Zx);/**
100
+ * @license lucide-react v0.563.0 - ISC
101
+ *
102
+ * This source code is licensed under the ISC license.
103
+ * See the LICENSE file in the root directory of this source tree.
104
+ */const tv=[["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"}]],nv=ne("arrow-right-left",tv);/**
105
+ * @license lucide-react v0.563.0 - ISC
106
+ *
107
+ * This source code is licensed under the ISC license.
108
+ * See the LICENSE file in the root directory of this source tree.
109
+ */const rv=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],ov=ne("arrow-up",rv);/**
110
+ * @license lucide-react v0.563.0 - ISC
111
+ *
112
+ * This source code is licensed under the ISC license.
113
+ * See the LICENSE file in the root directory of this source tree.
114
+ */const sv=[["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",sv);/**
115
+ * @license lucide-react v0.563.0 - ISC
116
+ *
117
+ * This source code is licensed under the ISC license.
118
+ * See the LICENSE file in the root directory of this source tree.
119
+ */const iv=[["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"}]],av=ne("bookmark",iv);/**
120
+ * @license lucide-react v0.563.0 - ISC
121
+ *
122
+ * This source code is licensed under the ISC license.
123
+ * See the LICENSE file in the root directory of this source tree.
124
+ */const cv=[["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"}]],lv=ne("box",cv);/**
125
+ * @license lucide-react v0.563.0 - ISC
126
+ *
127
+ * This source code is licensed under the ISC license.
128
+ * See the LICENSE file in the root directory of this source tree.
129
+ */const dv=[["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",dv);/**
130
+ * @license lucide-react v0.563.0 - ISC
131
+ *
132
+ * This source code is licensed under the ISC license.
133
+ * See the LICENSE file in the root directory of this source tree.
134
+ */const uv=[["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"}]],pv=ne("briefcase",uv);/**
135
+ * @license lucide-react v0.563.0 - ISC
136
+ *
137
+ * This source code is licensed under the ISC license.
138
+ * See the LICENSE file in the root directory of this source tree.
139
+ */const fv=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],hv=ne("check",fv);/**
140
+ * @license lucide-react v0.563.0 - ISC
141
+ *
142
+ * This source code is licensed under the ISC license.
143
+ * See the LICENSE file in the root directory of this source tree.
144
+ */const mv=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],_a=ne("chevron-down",mv);/**
145
+ * @license lucide-react v0.563.0 - ISC
146
+ *
147
+ * This source code is licensed under the ISC license.
148
+ * See the LICENSE file in the root directory of this source tree.
149
+ */const gv=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Is=ne("chevron-right",gv);/**
150
+ * @license lucide-react v0.563.0 - ISC
151
+ *
152
+ * This source code is licensed under the ISC license.
153
+ * See the LICENSE file in the root directory of this source tree.
154
+ */const yv=[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]],bv=ne("chevrons-left",yv);/**
155
+ * @license lucide-react v0.563.0 - ISC
156
+ *
157
+ * This source code is licensed under the ISC license.
158
+ * See the LICENSE file in the root directory of this source tree.
159
+ */const xv=[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]],vv=ne("chevrons-right",xv);/**
160
+ * @license lucide-react v0.563.0 - ISC
161
+ *
162
+ * This source code is licensed under the ISC license.
163
+ * See the LICENSE file in the root directory of this source tree.
164
+ */const Sv=[["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"}]],wv=ne("circle-alert",Sv);/**
165
+ * @license lucide-react v0.563.0 - ISC
166
+ *
167
+ * This source code is licensed under the ISC license.
168
+ * See the LICENSE file in the root directory of this source tree.
169
+ */const kv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],hp=ne("circle-check",kv);/**
170
+ * @license lucide-react v0.563.0 - ISC
171
+ *
172
+ * This source code is licensed under the ISC license.
173
+ * See the LICENSE file in the root directory of this source tree.
174
+ */const Cv=[["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"}]],jv=ne("circle-question-mark",Cv);/**
175
+ * @license lucide-react v0.563.0 - ISC
176
+ *
177
+ * This source code is licensed under the ISC license.
178
+ * See the LICENSE file in the root directory of this source tree.
179
+ */const Ev=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Tv=ne("clock",Ev);/**
180
+ * @license lucide-react v0.563.0 - ISC
181
+ *
182
+ * This source code is licensed under the ISC license.
183
+ * See the LICENSE file in the root directory of this source tree.
184
+ */const Av=[["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"}]],Rv=ne("command",Av);/**
185
+ * @license lucide-react v0.563.0 - ISC
186
+ *
187
+ * This source code is licensed under the ISC license.
188
+ * See the LICENSE file in the root directory of this source tree.
189
+ */const Ov=[["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"}]],Eo=ne("database",Ov);/**
190
+ * @license lucide-react v0.563.0 - ISC
191
+ *
192
+ * This source code is licensed under the ISC license.
193
+ * See the LICENSE file in the root directory of this source tree.
194
+ */const _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);/**
195
+ * @license lucide-react v0.563.0 - ISC
196
+ *
197
+ * This source code is licensed under the ISC license.
198
+ * See the LICENSE file in the root directory of this source tree.
199
+ */const Pv=[["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"}]],Iv=ne("eye-off",Pv);/**
200
+ * @license lucide-react v0.563.0 - ISC
201
+ *
202
+ * This source code is licensed under the ISC license.
203
+ * See the LICENSE file in the root directory of this source tree.
204
+ */const Dv=[["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"}]],$v=ne("eye",Dv);/**
205
+ * @license lucide-react v0.563.0 - ISC
206
+ *
207
+ * This source code is licensed under the ISC license.
208
+ * See the LICENSE file in the root directory of this source tree.
209
+ */const Mv=[["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"}]],Lv=ne("file-check",Mv);/**
210
+ * @license lucide-react v0.563.0 - ISC
211
+ *
212
+ * This source code is licensed under the ISC license.
213
+ * See the LICENSE file in the root directory of this source tree.
214
+ */const Nv=[["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"}]],Bv=ne("file-pen",Nv);/**
215
+ * @license lucide-react v0.563.0 - ISC
216
+ *
217
+ * This source code is licensed under the ISC license.
218
+ * See the LICENSE file in the root directory of this source tree.
219
+ */const 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 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],gp=ne("file-plus",Fv);/**
220
+ * @license lucide-react v0.563.0 - ISC
221
+ *
222
+ * This source code is licensed under the ISC license.
223
+ * See the LICENSE file in the root directory of this source tree.
224
+ */const 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:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],qv=ne("file-question-mark",zv);/**
225
+ * @license lucide-react v0.563.0 - ISC
226
+ *
227
+ * This source code is licensed under the ISC license.
228
+ * See the LICENSE file in the root directory of this source tree.
229
+ */const Uv=[["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",Uv);/**
230
+ * @license lucide-react v0.563.0 - ISC
231
+ *
232
+ * This source code is licensed under the ISC license.
233
+ * See the LICENSE file in the root directory of this source tree.
234
+ */const 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:"m14.5 12.5-5 5",key:"b62r18"}],["path",{d:"m9.5 12.5 5 5",key:"1rk7el"}]],Kv=ne("file-x",Wv);/**
235
+ * @license lucide-react v0.563.0 - ISC
236
+ *
237
+ * This source code is licensed under the ISC license.
238
+ * See the LICENSE file in the root directory of this source tree.
239
+ */const Vv=[["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"}]],Hv=ne("files",Vv);/**
240
+ * @license lucide-react v0.563.0 - ISC
241
+ *
242
+ * This source code is licensed under the ISC license.
243
+ * See the LICENSE file in the root directory of this source tree.
244
+ */const Gv=[["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",Gv);/**
245
+ * @license lucide-react v0.563.0 - ISC
246
+ *
247
+ * This source code is licensed under the ISC license.
248
+ * See the LICENSE file in the root directory of this source tree.
249
+ */const Qv=[["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"}]],no=ne("folder",Qv);/**
250
+ * @license lucide-react v0.563.0 - ISC
251
+ *
252
+ * This source code is licensed under the ISC license.
253
+ * See the LICENSE file in the root directory of this source tree.
254
+ */const Jv=[["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"}]],Yv=ne("funnel",Jv);/**
255
+ * @license lucide-react v0.563.0 - ISC
256
+ *
257
+ * This source code is licensed under the ISC license.
258
+ * See the LICENSE file in the root directory of this source tree.
259
+ */const Xv=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Zv=ne("gauge",Xv);/**
260
+ * @license lucide-react v0.563.0 - ISC
261
+ *
262
+ * This source code is licensed under the ISC license.
263
+ * See the LICENSE file in the root directory of this source tree.
264
+ */const eS=[["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"}]],Lr=ne("git-branch",eS);/**
265
+ * @license lucide-react v0.563.0 - ISC
266
+ *
267
+ * This source code is licensed under the ISC license.
268
+ * See the LICENSE file in the root directory of this source tree.
269
+ */const tS=[["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"}]],nS=ne("git-commit-horizontal",tS);/**
270
+ * @license lucide-react v0.563.0 - ISC
271
+ *
272
+ * This source code is licensed under the ISC license.
273
+ * See the LICENSE file in the root directory of this source tree.
274
+ */const rS=[["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"}]],oS=ne("git-fork",rS);/**
275
+ * @license lucide-react v0.563.0 - ISC
276
+ *
277
+ * This source code is licensed under the ISC license.
278
+ * See the LICENSE file in the root directory of this source tree.
279
+ */const sS=[["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",sS);/**
280
+ * @license lucide-react v0.563.0 - ISC
281
+ *
282
+ * This source code is licensed under the ISC license.
283
+ * See the LICENSE file in the root directory of this source tree.
284
+ */const iS=[["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"}]],aS=ne("layout-dashboard",iS);/**
285
+ * @license lucide-react v0.563.0 - ISC
286
+ *
287
+ * This source code is licensed under the ISC license.
288
+ * See the LICENSE file in the root directory of this source tree.
289
+ */const cS=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],qn=ne("loader-circle",cS);/**
290
+ * @license lucide-react v0.563.0 - ISC
291
+ *
292
+ * This source code is licensed under the ISC license.
293
+ * See the LICENSE file in the root directory of this source tree.
294
+ */const lS=[["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"}]],dS=ne("message-circle",lS);/**
295
+ * @license lucide-react v0.563.0 - ISC
296
+ *
297
+ * This source code is licensed under the ISC license.
298
+ * See the LICENSE file in the root directory of this source tree.
299
+ */const uS=[["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"}]],pS=ne("monitor",uS);/**
300
+ * @license lucide-react v0.563.0 - ISC
301
+ *
302
+ * This source code is licensed under the ISC license.
303
+ * See the LICENSE file in the root directory of this source tree.
304
+ */const fS=[["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"}]],hS=ne("network",fS);/**
305
+ * @license lucide-react v0.563.0 - ISC
306
+ *
307
+ * This source code is licensed under the ISC license.
308
+ * See the LICENSE file in the root directory of this source tree.
309
+ */const mS=[["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"}]],gS=ne("notebook-pen",mS);/**
310
+ * @license lucide-react v0.563.0 - ISC
311
+ *
312
+ * This source code is licensed under the ISC license.
313
+ * See the LICENSE file in the root directory of this source tree.
314
+ */const yS=[["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"}]],bS=ne("package",yS);/**
315
+ * @license lucide-react v0.563.0 - ISC
316
+ *
317
+ * This source code is licensed under the ISC license.
318
+ * See the LICENSE file in the root directory of this source tree.
319
+ */const xS=[["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"}]],vS=ne("palette",xS);/**
320
+ * @license lucide-react v0.563.0 - ISC
321
+ *
322
+ * This source code is licensed under the ISC license.
323
+ * See the LICENSE file in the root directory of this source tree.
324
+ */const SS=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],wS=ne("panel-left",SS);/**
325
+ * @license lucide-react v0.563.0 - ISC
326
+ *
327
+ * This source code is licensed under the ISC license.
328
+ * See the LICENSE file in the root directory of this source tree.
329
+ */const kS=[["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"}]],CS=ne("plug",kS);/**
330
+ * @license lucide-react v0.563.0 - ISC
331
+ *
332
+ * This source code is licensed under the ISC license.
333
+ * See the LICENSE file in the root directory of this source tree.
334
+ */const jS=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ES=ne("plus",jS);/**
335
+ * @license lucide-react v0.563.0 - ISC
336
+ *
337
+ * This source code is licensed under the ISC license.
338
+ * See the LICENSE file in the root directory of this source tree.
339
+ */const TS=[["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",TS);/**
340
+ * @license lucide-react v0.563.0 - ISC
341
+ *
342
+ * This source code is licensed under the ISC license.
343
+ * See the LICENSE file in the root directory of this source tree.
344
+ */const AS=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Hc=ne("search",AS);/**
345
+ * @license lucide-react v0.563.0 - ISC
346
+ *
347
+ * This source code is licensed under the ISC license.
348
+ * See the LICENSE file in the root directory of this source tree.
349
+ */const RS=[["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"}]],OS=ne("settings-2",RS);/**
350
+ * @license lucide-react v0.563.0 - ISC
351
+ *
352
+ * This source code is licensed under the ISC license.
353
+ * See the LICENSE file in the root directory of this source tree.
354
+ */const _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"}]],PS=ne("settings",_S);/**
355
+ * @license lucide-react v0.563.0 - ISC
356
+ *
357
+ * This source code is licensed under the ISC license.
358
+ * See the LICENSE file in the root directory of this source tree.
359
+ */const IS=[["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"}]],DS=ne("shield-alert",IS);/**
360
+ * @license lucide-react v0.563.0 - ISC
361
+ *
362
+ * This source code is licensed under the ISC license.
363
+ * See the LICENSE file in the root directory of this source tree.
364
+ */const $S=[["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"}]],MS=ne("shield-check",$S);/**
365
+ * @license lucide-react v0.563.0 - ISC
366
+ *
367
+ * This source code is licensed under the ISC license.
368
+ * See the LICENSE file in the root directory of this source tree.
369
+ */const LS=[["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"}]],NS=ne("sigma",LS);/**
370
+ * @license lucide-react v0.563.0 - ISC
371
+ *
372
+ * This source code is licensed under the ISC license.
373
+ * See the LICENSE file in the root directory of this source tree.
374
+ */const BS=[["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",BS);/**
375
+ * @license lucide-react v0.563.0 - ISC
376
+ *
377
+ * This source code is licensed under the ISC license.
378
+ * See the LICENSE file in the root directory of this source tree.
379
+ */const FS=[["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"}]],zS=ne("square-dashed",FS);/**
380
+ * @license lucide-react v0.563.0 - ISC
381
+ *
382
+ * This source code is licensed under the ISC license.
383
+ * See the LICENSE file in the root directory of this source tree.
384
+ */const qS=[["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"}]],US=ne("tag",qS);/**
385
+ * @license lucide-react v0.563.0 - ISC
386
+ *
387
+ * This source code is licensed under the ISC license.
388
+ * See the LICENSE file in the root directory of this source tree.
389
+ */const WS=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],KS=ne("terminal",WS);/**
390
+ * @license lucide-react v0.563.0 - ISC
391
+ *
392
+ * This source code is licensed under the ISC license.
393
+ * See the LICENSE file in the root directory of this source tree.
394
+ */const VS=[["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",VS);function HS(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 GS(e,t){const n=e.mode??"both";return n==="both"||n===t}function QS({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",Hv],["Lineage","lineage",oS],["Git","git",Lr],["Block Library","block_library",Oa],["Apps","apps",hS],["Connections","connection",CS]],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:wS,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?Iv:$v,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:aS,shortcut:"⌘D",run:v(()=>m({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:KS,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:zS,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:vS,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=>GS(v,n.appMode)).map(v=>({a:v,s:HS(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(Dy,{open:e,onOpenChange:m=>!m&&t(),children:s.jsxs($y,{children:[s.jsx(My,{style:{position:"fixed",inset:0,background:pe("surfaceOverlay"),zIndex:so.overlay}}),s.jsxs(Ly,{"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:Sn.lg,boxShadow:pe("shadowLg"),zIndex:so.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:d,children:[s.jsx(Ny,{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(Rv,{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(Rx,{shortcut:m.shortcut})]})]},m.id)})]})]})]})})}function zi(e){const t=Xt(e);if(!t)return;const n=ZS(t.kind),r=JS(t.source);if(!n||!r)return;const o=dw(t.limit);return{kind:n,source:r,name:St(t.name),sourcePath:St(t.sourcePath),metrics:qi(t.metrics),dimensions:qi(t.dimensions),filters:ew(t.filters),timeDimension:tw(t.timeDimension),orderBy:nw(t.orderBy),parameters:rw(t.parameters),parameterValues:aw(t.parameterValues),persistence:cw(t.persistence),trustState:lw(t.trustState),compiledSql:St(t.compiledSql),executionReceipt:XS(t.executionReceipt),filterableColumns:YS(t.filterableColumns),...o===void 0?{}:{limit:o}}}function JS(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function YS(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Xt(n),o=St(r==null?void 0:r.column),i=St(r==null?void 0:r.predicateTarget);return o&&i?[{column:o,predicateTarget:i}]:[]});return t.length>0?t:void 0}function XS(e){const t=Xt(e);if(!t)return;const n=Wo(t.sourceFingerprint),r=Wo(t.compiledSqlFingerprint),o=Wo(t.parameterFingerprint),i=Wo(t.resultFingerprint);return n&&r&&o&&i?{sourceFingerprint:n,compiledSqlFingerprint:r,parameterFingerprint:o,resultFingerprint:i}:void 0}function Wo(e){return typeof e=="string"&&/^[a-f0-9]{64}$/i.test(e.trim())?e.trim().toLowerCase():void 0}function ZS(e){return e==="certified_block"||e==="semantic_block"||e==="sql_block"?e:void 0}function ew(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Xt(n);if(!r)return[];const o=St(r.dimension),i=St(r.operator);return!o||!i?[]:[{dimension:o,operator:i,values:qi(r.values)??[]}]});return t.length?t:void 0}function tw(e){const t=Xt(e);if(!t)return;const n=St(t.name),r=St(t.granularity);return n&&r?{name:n,granularity:r}:void 0}function nw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Xt(n);if(!r)return[];const o=St(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 rw(e){if(!Array.isArray(e))return;const t=new Set,n=e.flatMap(r=>{const o=Xt(r),i=St(o==null?void 0:o.name),a=ow(o==null?void 0:o.type),c=sw(o==null?void 0:o.policy);if(!o||!i||!a||!c||t.has(i))return[];t.add(i);const l=iw(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 ow(e){return e==="string"||e==="number"||e==="boolean"||e==="date"||e==="string[]"||e==="number[]"||e==="date[]"?e:void 0}function sw(e){return e==="dynamic"||e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:void 0}function iw(e){const t=Xt(e);if(!t)return;if(t.kind==="sql_value")return{kind:"sql_value"};if(t.kind==="limit")return{kind:"limit"};const n=St(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 aw(e){const t=Xt(e);if(!t)return;const n=Object.entries(t).filter(([r])=>r.trim().length>0);return n.length?Object.fromEntries(n):void 0}function cw(e){return e==="transient"||e==="saved"?e:void 0}function lw(e){return e==="certified"||e==="governed"||e==="review_required"?e:void 0}function Xt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function St(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 dw(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}const Sp="dql_token",Gc="dql.server-token.v1";function uw(e){var r;return((r=new URLSearchParams(e.replace(/^#/,"")).get(Sp))==null?void 0:r.trim())||void 0}function pw(e){const t=new URLSearchParams(e.replace(/^#/,""));t.delete(Sp);const n=t.toString();return n?`#${n}`:""}function fw(){var e;if(!(typeof window>"u"))try{const t=uw(window.location.hash);if(t){window.sessionStorage.setItem(Gc,t);const n=pw(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=fw();function cr(e){const t=new Headers(e);return Qc&&t.set("Authorization",`Bearer ${Qc}`),t}async function wp(e,t,n){const r=await fetch(e,{headers:cr({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 hw={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 Gr=window.location.origin;class xt 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 xt({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 xt({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 xt({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=cr(t==null?void 0:t.headers);o.has("Content-Type")||o.set("Content-Type","application/json"),n=await fetch(`${Gr}${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 mw(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 sn(e){var r;const t=Array.isArray(e==null?void 0:e.columns)?e.columns.map(o=>typeof o=="string"?o:typeof(o==null?void 0:o.name)=="string"?o.name:String(o)):[],n=e!=null&&e.semanticRefs&&typeof e.semanticRefs=="object"?{metrics:Array.isArray(e.semanticRefs.metrics)?e.semanticRefs.metrics.map(String):[],dimensions:Array.isArray(e.semanticRefs.dimensions)?e.semanticRefs.dimensions.map(String):[]}:void 0;return{columns:t,rows:Array.isArray(e==null?void 0:e.rows)?e.rows:[],rowCount:(e==null?void 0:e.rowCount)??((r=e==null?void 0:e.rows)==null?void 0:r.length)??0,executionTime:(e==null?void 0:e.executionTime)??(e==null?void 0:e.executionTimeMs)??0,...n?{semanticRefs:n}:{}}}function Wt(e){var n;const t=e!=null&&e.resultPreview&&typeof e.resultPreview=="object"?sn(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:jw((e==null?void 0:e.dqlPromotionAction)??((n=e==null?void 0:e.dqlPromotion)==null?void 0:n.recommendedAction)),dqlPromotion:kp(e==null?void 0:e.dqlPromotion),researchPlan:gw(e==null?void 0:e.researchPlan),reviewChecklist:kw(e==null?void 0:e.reviewChecklist,e),...t?{resultPreview:t}:{resultPreview:void 0}}}function gw(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:yw(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 yw(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 nr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function bw(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:nr(t.draftCreationRate),certifyConversionRate:nr(t.certifyConversionRate),medianOpenReviewAgeMs:nr(t.medianOpenReviewAgeMs),medianTimeToDraftMs:nr(t.medianTimeToDraftMs),medianTimeToCertificationMs:nr(t.medianTimeToCertificationMs),medianTimeToTerminalMs:nr(t.medianTimeToTerminalMs)}}function xw(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 vw(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 Sw(e){const t=typeof e=="string"?e:"";return(t.split(/[\\/]/).pop()??t).replace(/\.dqlnb$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()||"Untitled notebook"}function ww(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 kw(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 Cw(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 jw(e){return e==="reuse_existing"||e==="extend_existing"||e==="create_replacement"||e==="create_new"||e==="review_required"?e:void 0}function kp(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:hw,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(`${Gr}/api/agent-runs?stream=1`,{method:"POST",headers:cr({"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 mw(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 xt({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:sn(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:sn(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:{...sn(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:{...sn(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(`${Gr}/api/block-studio/certify`,{headers:cr({"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 xt({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{...sn(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:sn(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 xt({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?sn(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(`${Gr}/api/datasets/import`,{method:"POST",headers:cr(),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(Wt),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:vw(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:Sw(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:ww((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:bw(r.reviewMetrics),limit:r.limit,offset:typeof r.offset=="number"?r.offset:0}},async getNotebookResearchDiagnostics(){const e=await k("/api/notebook/research/diagnostics");return xw(e)},async createNotebookResearch(e){const t=await k("/api/notebook/research",{method:"POST",body:JSON.stringify(e)});return Wt(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(Wt):[],createdCount:typeof t.createdCount=="number"?t.createdCount:Array.isArray(t.created)?t.created.length:0,skippedCount:typeof t.skippedCount=="number"?t.skippedCount:0,limitApplied:t.limitApplied===!0}},async listNotebookResearchSourceCoverage(e){const t=await 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(Wt):[],requestedCount:typeof t.requestedCount=="number"?t.requestedCount:e.sourceCellIds.length,matchedCount:typeof t.matchedCount=="number"?t.matchedCount:Array.isArray(t.runs)?t.runs.length:0,limitApplied:t.limitApplied===!0}},async previewNotebookResearchContext(e){const t=await k("/api/notebook/research/context-preview",{method:"POST",body:JSON.stringify(e)});return Cw(t)},async getNotebookResearch(e){const t=await k(`/api/notebook/research/${encodeURIComponent(e)}`);return Wt(t.run)},async updateNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});return Wt(n.run)},async runNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t??{})});return Wt(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:Wt(n.run),promotion:kp(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:Wt(n.run)}},async getSchema(){try{const e=await fetch(`${Gr}/api/schema`,{headers:cr()});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 xt?{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})})}},Ew={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"},Tw={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"},Cp={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"},$j={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"},Mj={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"},Aw={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Xc={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Zc=["source","transform","answer","consumption"],Lj=["term","business_view","block","metric","dimension","domain","source_table","dbt_source","dbt_model","chart","notebook","dashboard","app"],Nj=["source_table","dbt_source","dbt_model"],Rw=["term","domain","business_view","metric","dimension","block"];[...Rw];function Ow(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 _w(){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?Pw(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:Sn.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:be[4]},children:n?s.jsx(Iw,{context:n}):s.jsx(Lw,{})})]})}function Pw(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function Iw({context:e}){return e.kind==="cell"?s.jsx(Dw,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx($w,{nodeId:e.nodeId}):s.jsx(Mw,{name:e.name})}function Dw({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 $w({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:Cp[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 Mw({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:Sn.md,padding:be[3]},children:e})}function Lw(){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 Qr={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=Qr[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||el[e]}function Nw(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Qr)return tl(t)},has(e,t){return typeof t=="string"&&t in Qr},ownKeys(){return Object.keys(Qr)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Qr)))return{enumerable:!0,configurable:!0,value:tl(t)}}})}const Rn=Nw(),Qe={obsidian:Rn,paper:Rn,white:Rn,dark:Rn,light:Rn,midnight:Rn,arctic:Rn};function kt(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 Bw=kt(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"})]}));kt(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 Fw=kt(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"})]})),Bj=kt(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"})]}));kt(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),s.jsx("path",{d:"M16 20l4 4"})]}));kt(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 3v18h18"}),s.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]}));kt(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"})]}));kt(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 Fj=kt(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),s.jsx("circle",{cx:"18",cy:"17",r:"2"})]}));kt(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));kt(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"})]}));kt(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 jp=44,Ep=188,Tp="dql-activitybar-expanded";function zw(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(Tp))==="1"}catch{return!1}}function qw(e){var t;try{(t=window.localStorage)==null||t.setItem(Tp,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?Ep-12:jp-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 Uw(){const e=Ge(Mr(l=>({mainView:l.mainView,sidebarOpen:l.sidebarOpen,sidebarPanel:l.sidebarPanel,themeMode:l.themeMode}))),t=Cn(),n=Qe[e.themeMode],[r,o]=p.useState(zw);p.useEffect(()=>{qw(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(bS,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"ask",title:"Ask",icon:s.jsx(dS,{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(Bw,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(Fw,{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(Lr,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"settings",title:"Settings",icon:s.jsx(PS,{size:16,strokeWidth:1.75}),active:e.mainView==="settings"||e.mainView==="connection"}]}],c=[{key:"help",title:"Help",icon:s.jsx(jv,{size:16,strokeWidth:1.75}),active:e.mainView==="help",onClick:()=>t({type:"SET_MAIN_VIEW",view:"help"})}];return s.jsxs("div",{style:{width:r?Ep:jp,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(bv,{size:14,strokeWidth:2}):s.jsx(vv,{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 Ww=2e4,zj="application/dql-semantic-ref",rl=new Map;let uo=null;function Kw(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()+Ww}),c}function Ap(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 qj(e){uo=e}function Uj(e){uo===e&&(uo=null)}function Vw(e){return uo?(Ap(uo,e),!0):!1}function Wj(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;Ap(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?`
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}}),Kw(e.name)}}}function Hw(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 Kj=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?Hw(n-a[0].length):(e.explicit,null)};function Vj(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 Gw=6,Qw=999,Jw={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=Jw[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?Qw:Gw,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 Yw=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 Rp(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)||Rp(e).toLowerCase().includes(t)?!0:(e.children??[]).some(n=>Ia(n,t))}function Op(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=Op(o.children));return t}const Ys={metric:{Icon:Zv,tone:e=>e.accent},measure:{Icon:NS,tone:e=>e.accent},dimension:{Icon:US,tone:e=>e.success},time_dimension:{Icon:Tv,tone:e=>e.warning},entity:{Icon:lv,tone:e=>e.textSecondary},segment:{Icon:Yv,tone:e=>e.textMuted},hierarchy:{Icon:Lr,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:av,tone:e=>e.textMuted},provider:{Icon:no,tone:e=>e.textMuted},domain:{Icon:no,tone:e=>e.textMuted},group:{Icon:no,tone:e=>e.textMuted}};function Xw(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 Zw({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=Op(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=Yw.has(e.kind),m=Xw(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=Rp(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 Ft(e){return(e==null?void 0:e.trim())??""}function Qn(e){const t=new Map;for(const r of e){const o=Ft(r.id);o&&!t.has(o)&&t.set(o,{...r,id:o})}const n=r=>{const o=[Ft(r.name)||r.id],i=new Set([r.id]);let a=Ft(r.parent);for(;a&&!i.has(a);){i.add(a);const c=t.get(a);if(!c)break;o.unshift(Ft(c.name)||c.id),a=Ft(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 Hj(e,t){const n=Qn(t),r=Ft(e??void 0);return!r||n.some(o=>o.value===r)?n:[{value:r,label:`${r} (missing Domain page)`,disabled:!0},...n]}function To(e){return new Set(Qn(e).map(t=>t.value))}function Gj(e,t){const n=Ft(e??void 0).toLowerCase();if(!n)return"";const r=t.find(o=>Ft(o.id).toLowerCase()===n||Ft(o.name).toLowerCase()===n);return Ft(r==null?void 0:r.id)}function e0(e,t){const n=To(t),r=e.some(o=>{var i;return!n.has(((i=o.domain)==null?void 0:i.trim())??"")});return[...Qn(t).map(o=>o.value),...r?["uncategorized"]:[]]}function t0(e,t,n="",r=[]){const o=n.trim().toLowerCase(),i=To(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 lr;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(lr||(lr={}));class n0{constructor(){Pe(this,"diagnostics",[])}report(t){this.diagnostics.push(t)}error(t,n,r){this.report({severity:lr.Error,message:t,span:n,hint:r})}warning(t,n,r){this.report({severity:lr.Warning,message:t,span:n,hint:r})}hasErrors(){return this.diagnostics.some(t=>t.severity===lr.Error)}getErrors(){return this.diagnostics.filter(t=>t.severity===lr.Error)}getAll(){return[...this.diagnostics]}clear(){this.diagnostics=[]}format(t){return this.diagnostics.map(n=>r0(n,t)).join(`
399
+
400
+ `)}}function r0(e,t){const{severity:n,message:r,span:o,hint:i}=e,c=t.split(`
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
+ `;d+=` --> ${h}${o.start.line}:${o.start.column}
403
+ `,d+=`${u} |
404
+ `,d+=`${l} | ${c}
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 o0 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 s0={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 i0(e){return s0[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"]),a0={"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 c0(e){return a0[e]??e}const Zs=new Set(["dropdown","date_range","text","multi_select","range"]),l0=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
+ `;)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=i0(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
+ `)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
+ `?(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 d0=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"]),u0=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 p0(e){return d0.has(e)}function f0(e){return u0.has(e)}class h0{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 n0;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 o0(`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=c0(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 tn;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,gt,Dt,Ct,jt,Zt,en,En,Tn,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"?En=Number(Y.value):ve=Number(Y.value)}else if(this.check(y.Identifier)&&p0(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":gt=Y.value;break;case"draft_path":Dt=Y.value;break}}else if(this.check(y.Identifier)&&f0(this.current().value)){const ie=this.advance();this.expect(y.Equals);const Y=this.parseStringArrayValues();switch(ie.value){case"upstream_refs":Ct=Y;break;case"requested_filters":jt=Y;break;case"requested_dimensions":Zt=Y;break;case"order_by":en=Y;break;case"source_dql_metrics":Tn=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,Jn;for(;!this.check(y.RightBrace)&&!this.isAtEnd();){const Yn=this.current();if(Yn.type!==y.Identifier){this.error(`Expected 'question' or 'sql' in example entry, got '${Yn.value}'.`),this.advance();continue}this.advance(),this.expect(y.Equals);const Ao=this.expect(y.StringLiteral);Yn.value==="question"?$e=Ao.value:Yn.value==="sql"&&(Jn=Ao.value),this.check(y.Comma)&&this.advance()}this.expect(y.RightBrace),$e&&Y.push(Jn?{question:$e,sql:Jn}:{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)&&((tn=this.tokens[this.pos+1])==null?void 0:tn.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:gt,draftPath:Dt,upstreamRefs:Ct,requestedFilters:jt,requestedDimensions:Zt,orderBy:en,limit:En,sourceDqlMetrics:Tn,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)&&l0.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 m0(e,t){return new h0(e,t).parse()}function g0(e,t={}){const n=m0(e);return y0(n,t)}function y0(e,t={}){const n={indentUnit:t.indent??" "},r=e.statements.map(o=>b0(o,0,n)).join(`
412
+
413
+ `).trimEnd();return t.finalNewline===!1?r:`${r}
414
+ `}function N(e,t){return t.indentUnit.repeat(e)}function b0(e,t,n){switch(e.kind){case Q.Dashboard:return x0(e,t,n);case Q.ChartCall:return $a(e,t,n);case Q.Workbook:return w0(e,t,n);case Q.ImportDecl:return C0(e,t,n);case Q.DomainDecl:return _0(e,t,n);case Q.BlockDecl:return O0(e,t,n);case Q.TermDecl:return P0(e,t,n);case Q.BusinessViewDecl:return I0(e,t,n);case Q.Digest:return v0(e,t,n);default:return""}}function x0(e,t,n){const r=[];r.push(...jn(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 v0(e,t,n){const r=[];r.push(...jn(e.decorators,t,n)),r.push(`${N(t,n)}digest ${V(e.title)} {`),e.narrative&&r.push(S0(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 S0(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 w0(e,t,n){const r=[];r.push(...jn(e.decorators,t,n)),r.push(`${N(t,n)}workbook ${V(e.title)} {`);for(const o of e.pages)r.push(k0(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
418
+ `)}function k0(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 E0(e,t,n);case Q.ParamDecl:return T0(e,t,n);case Q.ChartCall:return $a(e,t,n);case Q.FilterCall:return Pp(e,t,n);case Q.UseDecl:return j0(e,t,n);case Q.LayoutBlock:return A0(e,t,n);default:return""}}function C0(e,t,n){return`${N(t,n)}import { ${e.names.join(", ")} } from ${V(e.path)}`}function j0(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 E0(e,t,n){return`${N(t,n)}let ${e.name} = ${Ot(e.initializer)}`}function T0(e,t,n){const r=`: ${e.paramType}`,o=e.defaultValue?` = ${Ot(e.defaultValue)}`:"";return`${N(t,n)}param ${e.name}${r}${o}`}function jn(e,t,n){return e.map(r=>{if(r.arguments.length===0)return`${N(t,n)}@${r.name}`;const o=r.arguments.map(i=>Ot(i)).join(", ");return`${N(t,n)}@${r.name}(${o})`})}function $a(e,t,n){return Ip(`chart.${e.chartType}`,e.decorators,e.query,e.args,t,n)}function Pp(e,t,n){return Ip(`filter.${e.filterType}`,[],e.query,e.args,t,n)}function Ip(e,t,n,r,o,i){const a=[];a.push(...jn(t,o,i)),a.push(`${N(o,i)}${e}(`);const c=[];n&&c.push(Dp(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 A0(e,t,n){const r=[];r.push(`${N(t,n)}layout(columns = ${e.columns}) {`);for(const o of e.rows)r.push(R0(o,t+1,n));return r.push(`${N(t,n)}}`),r.join(`
421
+ `)}function R0(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):Pp(o.node,t+1,n);if(o.span==null){r.push(i);continue}const a=i.split(`
422
+ `);a[a.length-1]=`${a[a.length-1]} span ${o.span}`,r.push(a.join(`
423
+ `))}return r.push(`${N(t,n)}}`),r.join(`
424
+ `)}function O0(e,t,n){const r=[];if(r.push(...jn(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 = [${D0(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?` = ${Ot(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(...Dp(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} ${Ot(o.expected)}`);r.push(`${N(t+1,n)}}`)}return r.push(`${N(t,n)}}`),r.join(`
425
+ `)}function _0(e,t,n){var o,i,a,c,l,u,h,d;const r=[];return r.push(...jn(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 P0(e,t,n){const r=[];return r.push(...jn(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 I0(e,t,n){const r=[];r.push(...jn(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 Dp(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} = ${Ot(e.value)}`}function D0(e){return e.map(t=>{const n=[`question = ${V(t.question)}`];return t.sql&&n.push(`sql = ${V(t.sql)}`),`{ ${n.join(", ")} }`}).join(", ")}function Ot(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=>Ot(t)).join(", ")}]`;case Q.BinaryExpr:return`${Ot(e.left)} ${e.operator} ${Ot(e.right)}`;case Q.IntervalExpr:return`INTERVAL ${V(e.value)}`;case Q.FunctionCall:return`${e.callee}(${e.arguments.map(t=>Ot(t)).join(", ")})`;case Q.TemplateString:return V(e.parts.map(t=>typeof t=="string"?t:`{${Ot(t)}}`).join(""));default:return""}}function V(e){return JSON.stringify(e)}function $0(e){var u,h,d,f,m,S,v,b;const t=Fr(e.metrics),n=Fr(e.dimensions??[]),r=Fr(e.requestedFilters??[]),o=Fr((e.orderBy??[]).map(w=>typeof w=="string"?w:`${w.name} ${w.direction}`)),i=L0(e.parameters??[]),a=[`block ${ze(e.name)} {`,' type = "semantic"',` status = ${ze(((u=e.status)==null?void 0:u.trim())||"draft")}`],c=M0(e.domain);c&&a.push(` domain = ${ze(c)}`),(h=e.description)!=null&&h.trim()&&a.push(` description = ${ze(e.description.trim())}`);const l=Fr(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(", ")}]`),N0(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?` = ${$p(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("}"),g0(`${a.join(`
430
+ `)}
431
+ `)}function M0(e){const t=e==null?void 0:e.trim();if(!(!t||t==="uncategorized"||t==="_uncategorized"))return t}function Fr(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function L0(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 N0(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function $p(e){return Array.isArray(e)?`[${e.map($p).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 B0(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 $0({name:i,status:"draft",metrics:n,dimensions:r}).trimEnd()}function F0(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 z0(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=F0(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 q0(e,t){const n={path:"",folders:new Map,files:[]};for(const o of e){const i=U0(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 U0(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 Mp({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 W0(e,t){const n=To(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[...Qn(t).map(o=>o.value),...r?["uncategorized"]:[]]}function al(e,t,n="",r=[]){const o=t.trim().toLowerCase(),i=To(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:Q0(e.binding.status)}:void 0}}function K0(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 V0(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 H0(e){return e.split(".").filter(Boolean).at(-1)??e}function G0(e){const t=e.split(".").filter(Boolean);return t.length>1?t.slice(0,-1).join("."):""}function Q0(e){if(e==="draft"||e==="review"||e==="certified"||e==="deprecated"||e==="pending_recertification")return e}function J0({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=>K0(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=V0(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(ar,{t:e,children:[s.jsx(qn,{size:13,className:"dql-spin"})," Loading dbt database objects…"]}):S?s.jsx(Y0,{error:S,t:e}):o.length===0?s.jsx(ar,{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=H0(_.path),H=G0(_.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:X0(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(Eo,{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(ar,{t:e,compact:!0,children:[s.jsx(qn,{size:11,className:"dql-spin"})," Loading columns…"]}):null,!q&&G?s.jsx(ar,{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(ar,{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 Y0({error:e,t}){const n=e instanceof xt?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(ar,{t,children:r})}function ar({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}),X0=e=>({border:"none",background:"transparent",cursor:"pointer",color:e.textMuted,display:"flex",padding:"1px 0 0",flexShrink:0}),Z0=[{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 At(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 ek(e,t){return String((t==="dimension"||t==="time_dimension")&&e.reference||e.name)}function tk(e,t,n){const r=ek(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)}:{},...At(e).length>0?{semanticModelIds:At(e).join(",")}:{},...e.owner?{owner:String(e.owner)}:{},...Array.isArray(e.tags)&&e.tags.length>0?{tags:e.tags.join(",")}:{}}}}function Kt(e,t,n,r,o){if(r.length===0)return null;const i=r.map(a=>tk(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 dr(e){var t;return(t=e.children)!=null&&t.length?e.children.reduce((n,r)=>n+dr(r),0):1}function nk(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 At(u))o.add(h);const i=u=>{const h=r.get(u);if(h)return st(h.domain);const d=n.find(f=>At(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=Z0.flatMap(({collection:g,kind:I,label:T})=>{const O=e[g].filter(M=>{const q=At(M);return q.length===1&&q[0]===x&&(g!=="dimensions"||!M.isTimeDimension)}),_=Kt(`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+dr(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&&At(x).length>1),m=e.metrics.filter(x=>st(x.domain)===u&&At(x).length===0),S=[Kt(`group:${u}:unassigned-dimensions`,"Dimensions","dimension",e.dimensions.filter(x=>st(x.domain)===u&&At(x).length===0&&!x.isTimeDimension),t),Kt(`group:${u}:unassigned-time-dimensions`,"Time Dimensions","time_dimension",e.timeDimensions.filter(x=>st(x.domain)===u&&At(x).length===0),t),Kt(`group:${u}:unassigned-measures`,"Underlying measures","measure",e.measures.filter(x=>st(x.domain)===u&&At(x).length===0),t),Kt(`group:${u}:unassigned-entities`,"Entities","entity",e.entities.filter(x=>st(x.domain)===u&&At(x).length===0),t)].filter(x=>!!x),v=[...d],b=Kt(`group:${u}:cross-model-metrics`,"Cross-model metrics","metric",f,t);b&&v.push(b);const w=Kt(`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+dr(E),0),meta:{provider:t,domain:u},children:S});const j=Kt(`group:${u}:hierarchies`,"Hierarchies","hierarchy",e.hierarchies.filter(x=>st(x.domain)===u),t);j&&v.push(j);const C=Kt(`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+dr(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+dr(h),0),meta:{provider:t},children:l}]}}function rk(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+dr(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:Eo},{id:"blocks",label:"Blocks",icon:Oa}],ok={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 sk({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=>{Vw(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(gS,{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(ES,{size:14,strokeWidth:2})}):null]}),s.jsxs("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:[j==="notebooks"&&t&&s.jsx(ik,{t:b,onOpenFile:t,search:x,domain:P,onDomainChange:A}),j==="semantic"&&s.jsx(dk,{t:b,search:x,onInsert:g,notebookMode:!r||!!o,onSemanticCompose:o}),j==="database"&&s.jsx(J0,{t:b,search:x,onInsert:g}),j==="blocks"&&s.jsx(uk,{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 Lp=(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 fr({text:e,t}){return s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:t.textMuted,textAlign:"center"},children:e})}function ik({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=W0(i.files,i.authoredDomains),S=m.includes(r)?r:"",b=[...Qn(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=q0(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(Mp,{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(fr,{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(Np,{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
+ .dql-nb-delete { opacity: 0; transition: opacity .12s, color .12s, background .12s, border-color .12s; }
433
+ .dql-nb-row:hover .dql-nb-delete { opacity: 1; }
434
+ .dql-nb-delete:hover { color: ${e.error} !important; background: ${e.error}12 !important; border-color: ${e.error}44 !important; }
435
+ .dql-nb-delete:focus-visible { opacity: 1; }
436
+ `}),c?s.jsx(lk,{file:c,t:e,busy:u,error:d,onCancel:()=>{l(null),f(null)},onConfirm:()=>void E()}):null]})}function Np({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(ak,{node:a,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i},`notebook-folder:${a.path}`):s.jsx(ck,{file:a.file,active:t===a.file.path,onOpenFile:n,onDelete:r,t:o,depth:i},a.file.path))})}function ak({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(no,{size:13}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]}),a?s.jsx(Np,{nodes:e.children,activePath:t,onOpenFile:n,onDelete:r,t:o,depth:i+1}):null]})}function ck({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:{...Lp(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 lk({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 dk({t:e,search:t,onInsert:n,notebookMode:r,onSemanticCompose:o}){var X;const{state:i,dispatch:a}=et(),c=p.useMemo(()=>nk(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 xt?`${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:rk(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 xt?`${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=B0(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(fr,{text:"Loading semantic layer…",t:e}):!c||!M||(((X=c.children)==null?void 0:X.length)??0)===0?s.jsx(fr,{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(Zw,{tree:M,themeMode:i.themeMode,search:t,onInsert:n,selectionMode:r,selected:J,onToggleSelection:q,canSelect:G})]})}function uk({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=e0(u,c.authoredDomains),w=b.includes(n)?n:"",C=[...Qn(c.authoredDomains).filter(g=>b.includes(g.value)),...b.includes("uncategorized")?[{value:"uncategorized",label:"Unassigned"}]:[]],x=t0(u,w,t,c.authoredDomains),E=p.useMemo(()=>z0(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(fr,{text:"Loading blocks…",t:e}):u.length===0?s.jsx(fr,{text:"No blocks yet.",t:e}):s.jsxs("div",{children:[s.jsx(Mp,{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(fr,{text:t?`No ${P} blocks match this search.`:w?`No blocks in ${w} yet.`:"No blocks yet.",t:e}):s.jsx(Bp,{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 Bp({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(pk,{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:{...Lp(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(no,{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:Fp(l.children)})]}),u?s.jsx(Bp,{nodes:l.children,depth:t+1,expandAll:n,expandedFolders:r,onToggleFolder:o,onOpen:i,onDelete:a,t:c}):null]},`folder:${l.path}`)})})}function Fp(e){return e.reduce((t,n)=>t+(n.kind==="block"?1:Fp(n.children)),0)}function pk({block:e,depth:t=0,t:n,onOpen:r,onDelete:o}){const i=String(e.status??"draft"),a=ok[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}`,fk={duckdb:[Ho("duckdb","FFF000")],file:[Ho("duckdb","FFF000")],snowflake:[Ho("snowflake","29B5E8")],databricks:[Ho("databricks","FF3621")]},hk={duckdb:"#f4bc00",file:"#f4bc00",snowflake:"#29b5e8",databricks:"#ff3621"};function mk({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 Jr({driver:e,size:t=16,fallbackColor:n}){const r=fk[e]??[],o=n??hk[e]??"#888",[i,a]=p.useState(0);return r.length===0||i>=r.length?s.jsx(mk,{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 gk(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 yk({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(MS,{size:11}):s.jsx(DS,{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(hv,{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(qn,{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(qn,{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=gk($,X);I(W),t==null||t(W.message)}),style:L(j.reindexRequired),children:[x==="reindex"?s.jsx(qn,{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 bk({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 xk(e){var t;return((t=e.evaluation)==null?void 0:t.status)==="failed"?"Rerun checks & approve":"Run checks & approve"}function vk(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 Sk(e,t,n){const r=n.trim();return{...e,[t]:r||void 0}}async function wk(e,t){try{return await e()}finally{await t()}}const kk=["claude-code","codex","anthropic","openai","gemini","ollama","custom-openai"],Ck=["claude-code","codex"],jk=["anthropic","openai","gemini","ollama","custom-openai"];function zp(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(_k,{configured:E,total:l.length||kk.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(Ak,{providers:l,cliStatus:h,t:i,onSaved:A=>u(A),onStatus:C,editorMode:r,onProviderConfigured:o}),s.jsx(yk,{t:i,onStatus:C})]}),!n&&s.jsxs("section",{style:{marginTop:22},children:[s.jsx(rr,{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:Ck.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:jk.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(rr,{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(Ok,{memories:S,t:i,onChange:v,onStatus:C}),s.jsx(Rk,{t:i,onStatus:C})]}),n==="advanced"&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsx(rr,{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(rr,{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(rr,{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(rr,{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(()=>qr(e.entries)),[h,d]=p.useState(null),[f,m]=p.useState(!1);p.useEffect(()=>{i(e.entries),u(qr(e.entries)),d(null)},[e]);const S=O=>{i(O),u(qr(O)),d(null)},v=(O,_)=>{S(o.map((M,q)=>q===O?Vn({...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(qr(o)),d(null),c(O)},x=()=>{const O=Dk(l);return i(O),u(qr(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=>Vn(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:Nt(t,!1),children:"Add MCP server"}),s.jsx("button",{type:"button",onClick:j,style:Nt(t,!1),children:"Add OpenAI connector"}),s.jsx("button",{type:"button",onClick:A,disabled:f,style:Nt(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:Nt(t,!1),children:"Format JSON"}),s.jsx("button",{type:"button",onClick:P,style:Nt(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:Nt(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(bk,{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:zr(t),children:[s.jsx("input",{type:"checkbox",checked:O.enabled,onChange:M=>v(_,{enabled:M.target.checked})})," Enabled"]}),s.jsxs("label",{style:zr(t),children:[s.jsx("input",{type:"checkbox",checked:O.trusted,onChange:M=>v(_,{trusted:M.target.checked})})," Trusted"]}),s.jsxs("label",{style:zr(t),children:[s.jsx("input",{type:"checkbox",checked:!!O.deferLoading,onChange:M=>v(_,{deferLoading:M.target.checked})})," Defer tools"]}),s.jsxs("label",{style:zr(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:zr(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 Ek({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 qp(e){return e==="codex"?"codex":"claude"}function Up({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:Nt(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:Nt(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(Ek,{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 Tk(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 Ak({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(()=>Tk(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(Up,{oauthProvider:qp(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:zp(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:Ik(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(Up,{oauthProvider:qp(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:zp(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:Nt(n,!0),children:e.active?"Save active provider":"Save and use"}),s.jsx("button",{type:"button",onClick:I,disabled:v||w,style:Nt(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 Rk({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 wk(()=>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:vk(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(`
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:Sk(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…":xk(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 Ok({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(Pk,{present:n.present})]},n.key))]})}function rr({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 _k({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 Pk({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 Nt(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 Ik(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 zr(e){return{display:"flex",alignItems:"center",gap:5,fontSize:12,color:e.textSecondary}}function qr(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:Vn(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 Dk(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON: ${r instanceof Error?r.message:String(r)}`)}if(!Kn(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(...$k(t.tools)),Array.isArray(t.mcp_servers)&&n.push(...Mk(t.mcp_servers)),Kn(t.mcpServers)&&n.push(...Lk(t.mcpServers)),n.map(Vn)}function $k(e){return e.flatMap((t,n)=>{if(!Kn(t)||t.type!=="mcp")return[];const r=ct(t,["connectorId","connector_id"]),o=ct(t,["authorization"]);return r?[Vn({kind:"connector",name:ct(t,["name","server_label","serverLabel"])??r,connectorId:r,authorizationToken:o,allowedTools:po(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:po(t,["allowedTools","allowed_tools"]),enabled:!0,trusted:t.trusted===!0||t.require_approval==="never",providers:["openai"]},"server",`tools[${n}]`)]})}function Mk(e){return e.map((t,n)=>{const r=ms(t,"server",`mcp_servers[${n}]`);return Vn({...r,authorizationToken:r.authorizationToken??(Kn(t)?ct(t,["authorization_token"]):void 0),providers:["anthropic"]})})}function Lk(e){return Object.entries(e).map(([t,n])=>{if(!Kn(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 Vn({kind:"server",name:t,url:r,authorizationToken:La(n.headers),enabled:n.enabled!==!1,trusted:n.trusted===!0,allowedTools:po(n,["allowedTools","allowed_tools"]),providers:Wp(n,["providers"])??["openai","anthropic"]})})}function ms(e,t,n){if(!Kn(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:po(e,["allowedTools","allowed_tools"]),enabled:e.enabled!==!1,trusted:e.trusted===!0,deferLoading:e.deferLoading===!0||e.defer_loading===!0,providers:Wp(e,["providers"])}}function Sl(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>!(t==null||t===""||Array.isArray(t)&&t.length===0)))}function Kn(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 po(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 Wp(e,t){const n=po(e,t);if(!n)return;const r=n.filter(o=>o==="openai"||o==="anthropic");return r.length?r:void 0}function La(e){if(!Kn(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 Vn(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 Nk=e=>new Promise(t=>{window.setTimeout(t,e)});async function Bk({jobId:e,loadStatus:t,onCompleted:n,onFailed:r,isCancelled:o=()=>!1,wait:i=Nk,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 Fk(e){return/^(?:https?:\/\/|ssh:\/\/|git@|file:\/\/)/i.test(e.trim())}function zk(e){const t=e.trim();return t?Fk(t)?{repoUrl:t}:{projectDir:t}:{}}const oi={auto:"Auto",native:"Native (DQL)","metricflow-cli":"Local MetricFlow","dbt-cloud":"dbt Cloud"};function qk({compact:e=!1,reapplyRequired:t=!1,onConfigured:n}){var Zt,en,En,Tn;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,tn,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=((tn=U.dbt)==null?void 0:tn.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 Bk({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,(Zt=J==null?void 0:J.job)==null?void 0:Zt.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(zk(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",gt=t?"Reapply required after DQL update":Ke?"dbt project needs attention":Fe?"Preparing governed search":Ee?"dbt project ready":"dbt project missing",Dt=t?"Review the prefilled project, choose Preview, then Reapply project.":(S==null?void 0:S.message)??(Ee?((en=a==null?void 0:a.dbt)==null?void 0:en.repoUrl)||((En=a==null?void 0:a.dbt)==null?void 0:En.projectDir)||"Configured dbt project.":"Choose a local path or Git repository."),Ct={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"},jt={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(wv,{size:17}):Fe?s.jsx(qn,{className:"dql-dbt-preparing-icon",size:17}):Ee?s.jsx(hp,{size:17}):s.jsx(Lr,{size:17})}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:13,fontWeight:700,color:i.textPrimary},children:gt}),s.jsx("div",{style:{fontSize:11.5,color:Ke?"var(--status-error)":i.textMuted,marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Dt}),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:jt,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:Ct})]}),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:jt,children:b==="preview"?"Inspecting…":"Preview"}),f?s.jsx("button",{type:"button",onClick:()=>void ee(),disabled:!!b,style:{...jt,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 · ${(Tn=x.dbtCloud.executionTargetFingerprint)==null?void 0:Tn.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:{...Ct,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:{...jt,border:"none",background:i.accent,color:"#fff",opacity:!Ee||Je||!L?.55:1,cursor:!Ee||Je?"not-allowed":"pointer"},children:[Je?s.jsx(qn,{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(`
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:Ct})]}),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:Ct})]}),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:Ct}),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:jt,children:_==="test"?"Testing…":"Test draft"}),s.jsx("button",{type:"button",onClick:()=>void We(),disabled:!!_,style:{...jt,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 Uk(e,t,n){return e.some(r=>r.catalogOrDatabase.toLowerCase()===t.toLowerCase()&&r.schemas.some(o=>o.toLowerCase()===n.toLowerCase()))}function Wk(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 Kk(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"},Vk={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])),Hk=[{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 Yr(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 Gk(e){return`${e.profileName}_${e.targetName}`.toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||"dbt_profile"}function Qk(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 Jk(e){const n=e.indexOf("/.dbt/");return n>=0?`~${e.slice(n)}`:e.split("/").slice(-3).join("/")}function Yk(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 fo(e){const t=Yr(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 Xk(e,t,n,r){const o=r!==null&&r===t,i=!!(t&&e[t]),a=e[n];return r===null||o||!i||t==="default"&&fo(e.default)&&!fo(a)?n:t}function Zk(e){const t=Object.keys(e);return t.find(n=>!fo(e[n]))??t[0]}function Kp({variant:e="panel",onConfigured:t}={}){var Ga,Qa,Ja,Ya,Xa;const n=Ge(Mr(D=>({settingsTab:D.settingsTab,themeMode:D.themeMode}))),r=Cn(),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"),[gt,Dt]=p.useState({}),Ct=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 jt=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=>!fo(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}},[jt,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(Ct.current!==ae)if(Ct.current=ae,z){Ke(Yr(String(z.driver??z.type??"duckdb")));const ue={};Object.entries(z).forEach(([we,Ve])=>{we!=="driver"&&we!=="type"&&(ue[Ki(we)]=String(Ve??""))}),Dt(ue)}else Ke("duckdb"),Dt({})},[c]);const Zt=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)},en=D=>{l(z=>z&&{...z,metadataScope:D.scope,metadataStatus:D.status}),X(D.scope.mode),te(Qo(D.scope.selectedScopes??D.scope.scopes))},En=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)}}},Tn=(D,z,ae)=>{const re=Wk(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}});en(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);en(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(Yr((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)},tn=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 Tt=ue.get(Ye);if((Tt==null?void 0:Tt.type)==="checkbox"){nt!==""&&(ae[Ye]=nt==="true");return}const Io=nt.trim();Io&&((Tt==null?void 0:Tt.type)==="number"&&!isNaN(Number(Io))?ae[Ye]=Number(Io):ae[Ye]=Io)});const we={...c.connections},Ve=c.default,Xn={...c.connections};D.previousName&&D.previousName!==z&&delete Xn[D.previousName],Xn[z]=ae;const Cf=Xk(Xn,c.default,z,D.previousName);let Za=!1;try{await B.saveConnections(Xn,Cf);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 Tt=await B.getConnections();l(Tt),x(`Test failed. Previous connection preserved: ${nt.message}`)}}catch(nt){await B.saveConnections(we,Ve||void 0).catch(()=>{});const Tt=await B.getConnections().catch(()=>null);Tt&&l(Tt),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=Yr(String(D.connection.driver??D.adapter??"duckdb")),ae=Qk(D);f(null),(i||a)&&(Ke(z),Dt(ae)),b(!1),S(null),ie({name:Gk(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)}},Jn=()=>ie({name:We,driver:Ee,fields:Je,previousName:m}),Yn=()=>ie({name:(c==null?void 0:c.default)||"default",driver:Fe,fields:gt,previousName:(c==null?void 0:c.default)||null}),Ao=D=>{Ke(D),Dt({}),f(null)},ff=async D=>{if(!c)return;const z={...c.connections};delete z[D];const ae=D===c.default?Zk(z):c.default;j(!0);try{await B.saveConnections(z,ae);const re=await B.getConnections();l(re),S(null)}finally{j(!1)}},hf=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)}},Ro={fontSize:10,fontWeight:600,letterSpacing:"0.07em",textTransform:"uppercase",color:o.textMuted,fontFamily:o.font,marginBottom:6},Oo={background:o.cellBg,border:`1px solid ${o.cellBorder}`,borderRadius:7,padding:"10px 12px",marginBottom:10},_o=(c==null?void 0:c.connections)??{},mf=(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(_o).length,Po=Wa>0,gf=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:Ro,children:"Connections"}),c===null?s.jsx("div",{style:{fontSize:12,color:o.textMuted,fontFamily:o.font},children:"Loading…"}):Object.entries(_o).map(([D,z])=>{const ae=(z==null?void 0:z.driver)??(z==null?void 0:z.type)??"unknown",re=D===mf,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:Jn,onCancel:me,onDelete:()=>ff(D),saving:w,isNew:!1},D):s.jsxs("div",{style:{...Oo,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(Jr,{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:()=>hf(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:Yk(we)?"••••••••":String(Ve)})]},we))})]},D)}),c!==null&&Wa===0&&s.jsx("div",{style:{...Oo,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:{...Oo,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:{...Ro,marginTop:8},children:"dbt profiles"}),s.jsx("div",{style:{display:"grid",gap:8,marginBottom:12},children:qa.map(D=>{var we;const z=Yr(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:{...Oo,marginBottom:0,display:"flex",alignItems:"center",gap:10},children:[s.jsx(Jr,{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 ",Jk(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)})})]})}),yf=s.jsx(s.Fragment,{children:!v&&!m&&Object.keys(_o).length===0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Ro,marginTop:8},children:"Quick Connect"}),s.jsx("div",{style:{display:"grid",gap:6,marginBottom:12},children:Hk.map(D=>s.jsxs("button",{onClick:async()=>{j(!0);try{const z={..._o,[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(Jr,{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))})]})}),bf=s.jsx(s.Fragment,{children:v?s.jsx(Cl,{t:o,editName:We,setEditName:Be,editDriver:Ee,setEditDriver:ge,editFields:Je,setEditFields:tt,onSave:Jn,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"]})}),xf=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})}),vf=s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:Zt,disabled:u||!Po,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||!Po?"not-allowed":"pointer",marginBottom:8,opacity:u||!Po?.7:1,transition:"all 0.15s"},children:u?"Testing...":Po?"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]})]}),Sf=s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{...Ro,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=Vk[D]??"",ue=Ua[D],we=(ue==null?void 0:ue.installed)??!0,Ve=(ue==null?void 0:ue.builtIn)??!1,Xn=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(Jr,{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:()=>tn(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:Xn?"Installing...":"Install"})]}),s.jsx("code",{style:{fontSize:9,color:o.textMuted,fontFamily:o.fontMono},children:D})]},D)})})]}),Et=!!(c&&Object.values(c.connections??{}).some(D=>!fo(D))),Me=c==null?void 0:c.metadataStatus,wf=si(W),kf=Et?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 En(),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)"," · ",Kk(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=Uk(wf,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=>Tn(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:Et?"var(--status-success-bg)":"var(--status-warning-bg)",color:Et?"var(--status-success)":"var(--status-warning)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx(Eo,{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",Et?" · 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}`:Et?"Configured — run Test connection to verify.":"Add a connection below to get started."})]}),s.jsx("button",{type:"button",onClick:()=>void Zt(),disabled:u||!Et,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:Et?"pointer":"not-allowed",fontFamily:o.font,flexShrink:0,opacity:Et?1:.55},children:u?"Testing…":"Test connection"})]}),s.jsxs("div",{style:{maxWidth:640},children:[Ka,Va]}),s.jsx(r1,{t:o,driver:Fe,fields:gt,onDriverChange:Ao,onFieldsChange:Dt,onSave:()=>void Yn(),saving:w,saveMessage:C,connectorStatus:Ua[Fe],installing:E===Fe,onInstall:()=>void tn(Fe)}),kf]});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:t1}),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:Et?"var(--status-success)":"var(--status-warning)"},title:Et?"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(e1,{dbtConfigured:G,dbtPreparation:H,databaseConfigured:Et,databaseTest:d,providers:M}):D==="project"?s.jsx(qk,{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:[gf,Ka,Va,yf,bf,xf,vf,Sf]})}function e1({dbtConfigured:e,dbtPreparation:t,databaseConfigured:n,databaseTest:r,providers:o}){const i=Ge(d=>d.themeMode),a=Cn(),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(Lr,{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(Eo,{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(OS,{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 t1=`
444
+ .dql-connection-page-stack {
445
+ display: grid;
446
+ gap: 16px;
447
+ }
448
+
449
+ .dql-connection-page-grid {
450
+ display: grid;
451
+ grid-template-columns: minmax(0, 1.18fr) minmax(320px, 0.82fr);
452
+ gap: 16px;
453
+ align-items: start;
454
+ }
455
+
456
+ @media (max-width: 920px) {
457
+ .dql-connection-page-grid {
458
+ grid-template-columns: minmax(0, 1fr);
459
+ }
460
+ }
461
+
462
+ @keyframes dql-connector-shimmer {
463
+ 0% { opacity: 1; }
464
+ 50% { opacity: 0.45; }
465
+ 100% { opacity: 1; }
466
+ }
467
+
468
+ .dql-connector-installing {
469
+ animation: dql-connector-shimmer 1.4s ease-in-out infinite;
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 n1(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 r1({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=n1(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(o1,{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 o1({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(Jr,{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 s1=Object.freeze(Object.defineProperty({__proto__:null,ConnectionPanel:Kp},Symbol.toStringTag,{value:"Module"}));function i1({type:e}){const t=Ew[e]??"#8b949e";return s.jsx("span",{style:{color:t,fontSize:10,fontWeight:700,textTransform:"uppercase",minWidth:34},title:Cp[e]??e,children:Tw[e]??e.slice(0,4).toUpperCase()})}function a1({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 Vp({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(i1,{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 c1=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>c1,[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(Vp,{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 l1({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=Ow(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(to,{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(a1,{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(Vp,{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:pv,label:"Business",value:P.businessNodes,detail:`${E.terms.length} terms · ${E.businessViews.length} views · ${P.businessEdges} edges`,t:r}),s.jsx(ci,{Icon:Eo,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:pS,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:Aw[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 d1({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(u1,{report:t,t:a}),!c&&l&&s.jsx(h1,{diff:e,t:a}),!c&&!l&&s.jsx("div",{style:{color:a.textMuted},children:t&&t.identical?"No semantic changes.":"No unstaged changes."})]})}function u1({report:e,t}){return s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.changes.map((n,r)=>s.jsx(p1,{change:n,t},r))})}function p1({change:e,t}){const{marker:n,color:r,label:o}=m1(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(f1,{field:a,t},c))})]})}function f1({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 h1({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:g1(n,t)},children:n||" "},r))})}function m1(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 g1(e,t){return e.startsWith("+++")||e.startsWith("---")?t.textMuted:e.startsWith("+")?t.success:e.startsWith("-")?t.error:e.startsWith("@@")?t.accent:t.textPrimary}const y1=2e3,b1={modified:{label:"Modified",color:e=>e.warning,Icon:Bv},added:{label:"Added",color:e=>e.success,Icon:gp},deleted:{label:"Deleted",color:e=>e.error,Icon:Kv},renamed:{label:"Renamed",color:e=>e.accent,Icon:nv},untracked:{label:"Untracked",color:e=>e.textMuted,Icon:qv}},Rl=["modified","added","renamed","deleted","untracked"];function x1(e){const t=e.trim();return t==="??"?"untracked":t.startsWith("R")?"renamed":t.includes("D")?"deleted":t.includes("A")?"added":"modified"}function v1(){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=>S1(I,g)?I:g)})},y1);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(to,{title:"Loading…"}),n==="status"&&o&&s.jsx(w1,{status:o,t}),n==="log"&&a&&s.jsx(T1,{log:a,t}),n==="diff"&&s.jsx(d1,{diff:l,diffReport:h,activeFilePath:C,diffPath:f,onScopeToFile:()=>m(C),onClearScope:()=>m(null),t})]})}function S1(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 w1({status:e,t}){const n=p.useMemo(()=>{const r={modified:[],added:[],deleted:[],renamed:[],untracked:[]};for(const o of e.changes)r[x1(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(k1,{status:e,t}),e.changes.length===0?s.jsx(C1,{t}):Rl.map(r=>{const o=n[r];return o.length===0?null:s.jsx(j1,{group:r,items:o,t},r)})]}):s.jsx(Hp,{t})}function k1({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(Lr,{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(ov,{size:11,strokeWidth:2})," ",n]}),r>0&&s.jsxs("span",{title:`${r} commit(s) behind upstream`,style:ui(t.warning,t),children:[s.jsx(ev,{size:11,strokeWidth:2})," ",r]}),n===0&&r===0&&s.jsx("span",{style:{...ui(t.textMuted,t),opacity:.7},children:"up to date"})]})}function C1({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(Lv,{size:14,strokeWidth:1.75,color:e.success}),"Working tree clean"]})}function Hp({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 j1({group:e,items:t,t:n}){const r=b1[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(E1,{change:a,t:n,color:o,divider:c<t.length-1},a.path))})]})}function E1({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 T1({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(nS,{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(Hp,{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 A1(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=To(t.authoredDomains),b=Qn(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(to,{title:"Loading apps…"}):j.length===0?o.length===0?s.jsx(to,{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(to,{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 R1={files:"Build",block_library:"Build",lineage:"Lineage",connection:"Connection",git:"Git",apps:"Apps"};function O1({onOpenFile:e}){const t=Ge(Mr(w=>({schemaTables:w.schemaTables,semanticLayer:w.semanticLayer,sidebarPanel:w.sidebarPanel,themeMode:w.themeMode}))),n=Cn(),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:R1[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(sk,{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(l1,{}),m==="connection"&&s.jsx(Kp,{}),m==="git"&&s.jsx(v1,{}),m==="apps"&&s.jsx(A1,{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 Gp=2;function _1(e,t={}){const n=t.version??Gp,r=JSON.parse(e),{dqlnbVersion:o,...i}=r,a={dqlnbVersion:n,...i};return JSON.stringify(a,P1(),2)+`
473
+ `}function P1(){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 I1(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:bt(),type:"markdown",content:`# ${a}`,status:"idle"}),c&&r.push({id:bt(),type:"dql",name:a.toLowerCase().replace(/\s+/g,"_"),content:c,status:"idle"})}return r.length===0&&r.push({id:bt(),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:bt(),type:"dql",content:e.trim(),status:"idle"}]}}}const D1=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 $1(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])=>!D1.has(u)));return{id:c.id||bt(),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:bt(),type:"sql",content:e,status:"idle"}]}}}function M1(e,t,n){const r={dqlnbVersion:Gp,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 _1(JSON.stringify(r))}function L1(e,t){return e.endsWith(".dql")?I1(t):$1(t)}const Qp=/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;function Qj(e){const t=new Set;for(const n of e.matchAll(Qp))t.add(n[1]);return[...t]}function N1(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
+ `),i=n.map(a=>`"${a.replace(/"/g,'""')}"`).join(", ");return`${e} AS (
475
+ SELECT * FROM (VALUES
476
+ ${o}
477
+ ) AS _t(${i})
478
+ )`}function B1(e,t){if(t==="number"){const n=Number(e);return isNaN(n)?`'${e.replace(/'/g,"''")}'`:String(n)}return`'${e.replace(/'/g,"''")}'`}function F1(e,t){var u;const n=[...e.matchAll(Qp)];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],B1(v,b)),o.push(d);continue}if(!m.result||m.error||m.stale){i.push(d);continue}c.push(N1(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
+ `)},
480
+ `):l=`WITH ${c.join(`,
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 Jj(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 Jp(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 Yj(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=>`"${vn(o)}"`).join(", ")}]`)}function Yp(e,t,n){const r=Array.from(new Set(n.filter(Boolean))),o=`${t} = [${r.map(a=>`"${vn(a)}"`).join(", ")}]`,i=new RegExp(`\\b${t}\\s*=\\s*\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,o):Fa(e,` ${o}`)}function Xp(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:rf(l[4]),d=l[2]?`${l[2]}${l[3]??""}`:z1(of(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:U1(t.get(u)),...m?{binding:m}:{}}]})}function z1(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 Zp(e){return e.default===void 0?"":of(e.default)}function Xj(e){if(/^\s*block\s+"/i.test(e))return e;const t=e.trim();return`block "notebook_query" {
483
+ status = "draft"
484
+ domain = "uncategorized"
485
+ type = "custom"
486
+ description = "Notebook analysis"
487
+
488
+ query = """
489
+ ${t?t.split(/\r?\n/).map(r=>` ${r}`).join(`
490
+ `):" -- Write query"}
491
+ """
492
+ }
493
+ `}function Zj(e,t){const n=nf(t.name);if(!n)return e;const r=Xp(e).filter(o=>o.name!==t.previousName&&o.name!==n).map(o=>({name:o.name,type:o.type,required:o.required,defaultText:Zp(o),policy:o.policy}));return r.push({name:n,type:t.type,required:t.required,defaultText:t.defaultText??"",policy:t.policy}),ef(e,r)}function eE(e,t){const n=Xp(e).filter(r=>r.name!==t).map(r=>({name:r.name,type:r.type,required:r.required,defaultText:Zp(r),policy:r.policy}));return ef(e,n)}function tE(e,t,n){const r=nf(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} = "${vn(o)}"`),ys(e,"filterBindings",a.join(`
494
+ `))}function ef(e,t){const n=t.map(i=>{const a=`${i.name}: ${i.type}`;return i.required?a:`${a} = ${tf(i.defaultText,i.type)}`}).join(`
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 tf(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=>tf(i,r)).join(", ")}]`}return`"${vn(n)}"`}function nf(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 rf(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("]")?q1(t.slice(1,-1)).map(rf):t}function q1(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 of(e){return Array.isArray(e)?e.join(", "):String(e??"")}function U1(e){return e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:"dynamic"}function W1(e,t){const n=new Set(Jp(e).requestedFilters),r=Array.from(new Set(t.filter(Boolean)));let o=Yp(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} = "${vn(i)}"`),o}function pi(e,t,n,r,o){const c=[...J1(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=vn(n),o=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return o.test(e)?e.replace(o,`$1"${r}"`):Fa(e,` ${t} = "${r}"`)}function nE(e,t){const n=new Set(t.filter(Boolean)),r=Jp(e);let o=Yp(e,"dimensions",r.dimensions.filter(i=>n.has(i)));return o=W1(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 vn(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
+ ${t}
499
+
500
+ visualization {`):e.replace(/\n\}\s*$/,`
501
+ ${t}
502
+ }
503
+ `)}function K1(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 V1(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=H1(i),i.trim()||null}return null}function H1(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 rE(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 G1(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}"`):Nr(e,` ${t} = "${r}"`)}function Q1(e,t){const n=t.replace(/"/g,'\\"');return/^\s*block\s+"/i.test(e)?e.replace(/^(\s*block\s+)"[^"]+"/i,`$1"${n}"`):e}function oE(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}]`):Nr(e,` tags = [${n}]`)}function sE(e,t,n){const r=Array.from(new Set(n.map(a=>a.trim()).filter(Boolean))),o=`${t} = [${r.map(a=>`"${vn(a)}"`).join(", ")}]`,i=new RegExp(`(\\b${t}\\s*=\\s*)\\[[\\s\\S]*?\\]`,"i");return i.test(e)?e.replace(i,`$1[${r.map(a=>`"${vn(a)}"`).join(", ")}]`):Nr(e,` ${o}`)}function iE(e,t){const n=/visualization\s*\{[\s\S]*?\n\s*\}/i;if(!n.test(e)){const r=X1(t);return Nr(e,` ${r.replace(/\n/g,`
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
+ $1 ${i} = "${c}"
506
+ $1}`)}return o})}function J1(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
+ `).trim())??""}function ys(e,t,n){const r=n.trim(),o=r?` ${t} {
508
+ ${r.split(/\r?\n/).map(a=>` ${a.trimEnd()}`).join(`
509
+ `)}
510
+ }`:"",i=new RegExp(`\\n\\s*${t}\\s*\\{[\\s\\S]*?\\n\\s*\\}`,"i");return i.test(e)?e.replace(i,o?`
511
+ ${o}`:""):o?/\n\s*visualization\s*\{/i.test(e)?e.replace(/\n\s*visualization\s*\{/i,`
512
+ ${o}
513
+
514
+ visualization {`):Nr(e,o,!0):e}function aE(e,t){return e==="metric"?`@metric(${t})`:`@dim(${t})`}function cE(e,t){const n=za(e);if(!n||n.blockType!=="custom")return`${e.trimEnd()}
515
+ ${t}
516
+ `;const r=n.query.trimEnd(),o=r?`${r}
517
+ ${t}`:t;return Y1(e,o)}function Y1(e,t){if(!za(e))return e;const r=G1(e,"type","custom"),o=` query = """
518
+ ${t.trimEnd()}
519
+ """`,i=/\n\s*query\s*=\s*"""[\s\S]*?"""/i;return i.test(r)?r.replace(i,`
520
+ ${o}`):Nr(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:Ur(e,"metrics"),dimensions:Ur(e,"dimensions"),requestedFilters:Ur(e,"requested_filters"),sourceDqlKind:t("source_dql_kind"),sourceDqlName:t("source_dql_name"),sourceDqlPath:t("source_dql_path"),sourceDqlHash:t("source_dql_hash"),sourceDqlMetrics:Ur(e,"source_dql_metrics"),sourceDqlDimensions:Ur(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 Ur(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 X1(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 = "${Z1(e.title)}"`),t.push("}"),t.join(`
521
+ `)}function Z1(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Nr(e,t,n=!1){const r=e.trimEnd();if(!/^\s*block\s+"/i.test(r))return`${r}
522
+ ${t}
523
+ `;const o=n?`
524
+
525
+ ${t}
526
+ `:`
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=>sf(n.name).test(e)).map(n=>({id:n.datasetId,alias:n.name,role:n.objectType==="staged_dataset"?"staged":"source",fingerprint:n.fileFingerprint}))}function eC(e,t){return t.filter(n=>n.source==="database").filter(n=>sf(n.name).test(e)).map(n=>n.name)}function lE(e,t){const n=[];for(const r of e)for(const o of t){const i=tC(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 dE(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(rC)).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 uE(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.${or(i)} AS ${or(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
+ `),`FROM ${or(e.staged.alias)} AS warehouse`,`${e.joinType.toUpperCase()} JOIN ${or(e.local.alias)} AS local_data`,` ON warehouse.${or(e.warehouseKey)} = local_data.${or(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 tC(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 sf(e){return new RegExp(`(?:^|[^a-zA-Z0-9_])(?:["\`])?${nC(e)}(?:["\`])?(?=$|[^a-zA-Z0-9_])`,"i")}function or(e){return`"${e.replace(/"/g,'""')}"`}function nC(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rC(e){return typeof e=="string"?e:JSON.stringify(e)}const On=new Map,nn=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 oC(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?V1(t):null}function sC(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 Xr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function iC(e){const t=Xr(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 Wr(e,t,n){return new xt({status:400,code:e,message:t,recoverable:!0,details:{phase:"preflight",...n}})}function Jo(e){const t=e.error instanceof xt?e.error:void 0,n=Xr(t==null?void 0:t.details),r=Xr(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??iC(n==null?void 0:n.executionTarget),compiledSql:e.attemptedSql,semanticTrace:r,targetBinding:Xr(n==null?void 0:n.targetBinding),executionReceipt:Xr(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 af(){const e=Cn(),t=p.useCallback(async(i,a)=>{var P,A,g,I;const c=Pn.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:oC(u);if(u.type!=="dql"&&!d)return{cellId:i,status:"skipped"};const f=On.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};On.set(i,w),nn.set(i,m);const j=()=>{var T;return((T=On.get(i))==null?void 0:T.runId)===m&&nn.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:bt(),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=sC(ee.chartConfig)??K1(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:bt(),cellName:ee.blockName??u.name??u.id,rows:xe.rowCount??xe.rows.length,time:xe.executionTime??ke,ts:new Date}}),setTimeout(()=>{nn.get(i)===m&&(e({type:"UPDATE_CELL",id:i,updates:{status:"idle"}}),nn.delete(i))},2e3),{cellId:i,runId:m,status:"success",result:xe,execution:We}}const T=$l(d,c.schemaTables),O=eC(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,Wr("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=F1(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,Wr("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,Wr("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:bt(),cellName:u.name??u.id,rows:F.rowCount??F.rows.length,time:F.executionTime??J,ts:new Date}}),setTimeout(()=>{nn.get(i)===m&&(e({type:"UPDATE_CELL",id:i,updates:{status:"idle"}}),nn.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=On.get(i))==null?void 0:I.runId)===m&&On.delete(i)}},[e]),n=p.useCallback(async()=>{const i=Pn.getState().cells,a=Lx(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:Wr("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:Wr("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=Pn.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=On.get(i);if(!a)return;a.controller.abort(),On.delete(i),nn.get(i)===a.runId&&nn.delete(i);const c=new Date().toISOString(),l=Pn.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 aC(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 cC(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 lC(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
+ <div class="table-wrap">
534
+ <table>
535
+ <thead><tr>${i}</tr></thead>
536
+ <tbody>${a}</tbody>
537
+ </table>
538
+ ${o?`<p class="truncated">Showing first 200 of ${n.length.toLocaleString()} rows</p>`:""}
539
+ </div>`}function dC(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 uC(e){const t=dC(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
+ <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
+ <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">${aC(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 pC(e,t){const n=t.map(r=>{if(r.type==="markdown")return`<section class="cell md-cell">${cC(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=uC(r.result),l=lC(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
+ `);return`<!DOCTYPE html>
544
+ <html lang="en">
545
+ <head>
546
+ <meta charset="UTF-8">
547
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
548
+ <title>${lt(e)}</title>
549
+ <style>
550
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
551
+ body {
552
+ font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
553
+ background: #0d1117; color: #e6edf3;
554
+ line-height: 1.6; padding: 0;
555
+ }
556
+ .page-header {
557
+ background: #161b22; border-bottom: 1px solid #21262d;
558
+ padding: 16px 32px; display: flex; align-items: center; gap: 12px;
559
+ }
560
+ .logo {
561
+ width: 28px; height: 28px; border-radius: 6px;
562
+ background: linear-gradient(135deg, #388bfd, #1f6feb);
563
+ display: flex; align-items: center; justify-content: center;
564
+ font-size: 10px; font-weight: 700; color: #fff;
565
+ font-family: monospace; letter-spacing: -0.5px; flex-shrink: 0;
566
+ }
567
+ .page-title { font-size: 18px; font-weight: 600; color: #e6edf3; }
568
+ .page-meta { font-size: 12px; color: #8b949e; margin-left: auto; }
569
+ .content { max-width: 900px; margin: 0 auto; padding: 32px 24px; display: flex; flex-direction: column; gap: 24px; }
570
+ .cell { border-radius: 8px; overflow: hidden; }
571
+ .md-cell { padding: 4px 0; }
572
+ .md-cell h1 { font-size: 26px; font-weight: 700; color: #e6edf3; margin: 0 0 12px; }
573
+ .md-cell h2 { font-size: 20px; font-weight: 600; color: #e6edf3; margin: 20px 0 10px; }
574
+ .md-cell h3 { font-size: 16px; font-weight: 600; color: #e6edf3; margin: 16px 0 8px; }
575
+ .md-cell p { color: #c9d1d9; margin-bottom: 8px; }
576
+ .md-cell ul { padding-left: 20px; color: #c9d1d9; margin-bottom: 8px; }
577
+ .md-cell code { background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; }
578
+ .md-cell pre { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px; overflow-x: auto; margin-bottom: 8px; }
579
+ .md-cell pre code { background: none; padding: 0; }
580
+ .md-cell blockquote { border-left: 3px solid #388bfd; padding-left: 14px; color: #8b949e; }
581
+ .sql-cell { background: #161b22; border: 1px solid #30363d; }
582
+ .cell-header { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid #21262d; background: #1c2128; }
583
+ .cell-type { font-size: 10px; font-weight: 600; letter-spacing: 0.05em; color: #8b949e; background: #21262d; padding: 2px 6px; border-radius: 4px; font-family: monospace; }
584
+ .cell-name { font-size: 12px; color: #388bfd; font-family: monospace; }
585
+ .cell-code { background: #0d1117; padding: 14px; font-size: 12px; font-family: 'JetBrains Mono', monospace; color: #c9d1d9; overflow-x: auto; border-bottom: 1px solid #21262d; line-height: 1.55; white-space: pre; }
586
+ .cell-output { padding: 14px; }
587
+ .output-meta { font-size: 11px; color: #8b949e; margin-bottom: 10px; }
588
+ .table-wrap { overflow-x: auto; }
589
+ table { width: 100%; border-collapse: collapse; font-size: 12px; }
590
+ th { background: #1c2128; color: #8b949e; font-weight: 600; text-align: left; padding: 7px 12px; border-bottom: 1px solid #30363d; white-space: nowrap; }
591
+ td { padding: 6px 12px; border-bottom: 1px solid #21262d; color: #e6edf3; }
592
+ td.num { text-align: right; font-family: monospace; }
593
+ tr:last-child td { border-bottom: none; }
594
+ .truncated { font-size: 11px; color: #8b949e; margin-top: 8px; }
595
+ .cell-error { padding: 12px 14px; background: #3d1a1a; border-top: 1px solid #f85149; color: #f85149; font-size: 13px; }
596
+ .exported-by { text-align: center; color: #484f58; font-size: 11px; padding: 40px 0 24px; }
597
+ </style>
598
+ </head>
599
+ <body>
600
+ <div class="page-header">
601
+ <div class="logo">DQL</div>
602
+ <span class="page-title">${lt(e)}</span>
603
+ <span class="page-meta">Exported ${new Date().toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}</span>
604
+ </div>
605
+ <div class="content">
606
+ ${n}
607
+ </div>
608
+ <p class="exported-by">Built with DQL Workbench</p>
609
+ </body>
610
+ </html>`}function fC(e,t){const n=pC(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 hC=new Set(["succeeded","failed","cancelled","interrupted"]);function Pr(e){return hC.has(e.status)}function mC(e,t){if(e.id!==t.id)return t;const n=Pr(e),r=Pr(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 Zr(e,t){const n=e.find(o=>o.id===t.id),r=n?mC(n,t):t;return wC([...e.filter(o=>o.id!==t.id),r])}function gC(e,t){return t.reduce(Zr,e)}function yC(e){return e.filter(t=>!Pr(t)).map(t=>t.id)}function bC(e,t){for(const n of yC(t))e.add(n)}async function xC(e,t,n){await Promise.all([...e].map(async r=>{try{const o=await t(r);if(n(o)===!1)return;Pr(o)&&e.delete(r)}catch{}}))}function vC(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 pE(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=Kr(t.activePath),r=(o=t.sourceFingerprint)==null?void 0:o.trim();return e.filter(i=>i.type==="block_certification").filter(i=>{const a=SC(i),c=[Kr(i.scope.startsWith("block:")?i.scope.slice(6):void 0),Kr(a==null?void 0:a.oldPath),Kr(a==null?void 0:a.draftPath),Kr(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 SC(e){return e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:void 0}function Kr(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function wC(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=>Pr(r)?(n+=1,n<=t):!0)}const sr=["local-operations"],cf=p.createContext(null);function kC({children:e}){const t=Yi(),n=p.useRef(new Set),r=p.useRef(new Set),o=Ge(l=>l.dispatch),i=Ri({queryKey:sr,queryFn:async()=>{const l=(await B.listOperations(50)).operations,u=t.getQueryData(sr)??[];return gC(u,l)},staleTime:15e3,refetchOnWindowFocus:!1,refetchInterval:1500}),a=i.data??[];p.useEffect(()=>{let l=!0,u,h;const d=()=>{h=new AbortController,wp("/api/operations/events",f=>{if(f.event==="operation")try{const m=JSON.parse(f.data);t.setQueryData(sr,(S=[])=>Zr(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(()=>{bC(r.current,a)},[a]),p.useEffect(()=>{let l=!0,u=!1;const h=async()=>{if(!(u||r.current.size===0)){u=!0;try{await xC(r.current,f=>B.getOperation(f),f=>{if(!l)return!1;t.setQueryData(sr,(m=[])=>Zr(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 vC(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(sr,(h=[])=>Zr(h,u))},track:l=>{Pr(l)?r.current.delete(l.id):r.current.add(l.id),t.setQueryData(sr,(u=[])=>Zr(u,l))}}),[a,i.isLoading,t]);return s.jsx(cf.Provider,{value:c,children:e})}function CC(){const e=p.useContext(cf);if(!e)throw new Error("useOperations must be used inside OperationsProvider.");return e}const jC=new Set(["succeeded","failed","cancelled","interrupted"]);function EC(e,t=8){const n=TC(e).filter(o=>!jC.has(o.status)||o.type!=="project_refresh"),r=n.map(lf);return{operations:n.slice(0,t),activeCount:r.filter(o=>o.active).length,attentionCount:r.filter(o=>o.tone==="attention").length}}function TC(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 AC(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||RC(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 lf(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 AC(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([ir(n==null?void 0:n.path),ir(r==null?void 0:r.path),ir(t==null?void 0:t.oldPath),ir(t==null?void 0:t.draftPath),ir(t==null?void 0:t.newPath),ir(o)].filter(i=>!!i)))}function hi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ir(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function RC(e,t){return t.createdAt.localeCompare(e.createdAt)||t.updatedAt.localeCompare(e.updatedAt)||t.id.localeCompare(e.id)}function OC(){const e=Ge(d=>d.themeMode),t=Qe[e],{operations:n,loading:r,cancel:o}=CC(),[i,a]=p.useState(!1),c=p.useRef(null),{operations:l,activeCount:u,attentionCount:h}=EC(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=lf(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:_C(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 _C(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 PC(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 IC(e){const t=rs.get(e);return!!(t!=null&&t.running||t!=null&&t.pending)}function DC({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 $C(){var te;const e=Ge(Mr(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=Cn(),n=Qe[e.themeMode],{executeAll:r}=af(),[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:Q1(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},H=p.useCallback(async()=>{var K,oe,ee;const F=Pn.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)??"":M1(xe,ke,De);await PC(ce.path,We);const Be=Pn.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=Pn.getState().activeFile)==null?void 0:ee.path;(!ce||!IC(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(DC,{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(OC,{}),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(LC,{}),"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(MC,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{fC(e.notebookTitle||"dashboard",e.cells),P(!1)}})})]})]})]})}function MC({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 LC(){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 NC(e){return e.toTimeString().slice(0,8)}function BC(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function FC(){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(zC,{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 zC({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:NC(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:BC(e.time)})]})]})}function qC(){const{state:e,dispatch:t}=et(),{executeAll:n}=af();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 UC=600;function WC(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 KC(){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=WC(i,e.cells);B.saveRunSnapshot(i,l).catch(()=>{})},UC)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}const fE="core";function VC(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 HC=[{items:[{id:"diagram",label:"Modeling"},{id:"skills",label:"Skills"},{id:"blocks",label:"Blocks"},{id:"notebooks",label:"Notebooks"},{id:"apps",label:"Apps"}]}],GC=new Set(HC.flatMap(e=>e.items.map(t=>t.id)));function df(e){return e!==null&&GC.has(e)}function hE(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 QC(e){const t=new URL(e);for(const n of uf)t.searchParams.delete(n);return`${t.pathname}${t.search}${t.hash}`}const uf=["domain","domainSection","modelArea","domainObject"],mE="dql.domain-studio.location";function gE(e,t){const n=new URL(e).searchParams;if(uf.some(r=>n.has(r))){const r=n.get("domainSection"),o=df(r)?r:"diagram";return{domain:n.get("domain"),section:o,modelAreaId:n.get("modelArea"),selectedId:r==="diagram"?n.get("domainObject"):null}}return JC(t)}function JC(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"&&df(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 yE(e){return`modeling:${e??"all"}`}function bE(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 xE(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 pf(e){return Object.entries(e.entities).map(([t,n])=>({recordKey:t,entity:n}))}function vE(e,t){if(e.entities[t])return t;const n=pf(e).filter(({entity:r})=>r.id===t||r.qualifiedId===t);return n.length===1?n[0].recordKey:void 0}function SE(e,t){return pf(e).filter(({entity:n})=>!t||n.domain===t)}function wE(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)===VC(t.areaId)&&r.domain===t.domain}return e.operation==="upsert_area"?!!n&&e.value.domain===n.domain&&e.value.id===n.localId:!1}const YC=p.lazy(()=>_e(()=>import("./HomePage-2v3SRf8V.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.HomePage}))),XC=p.lazy(()=>_e(()=>import("./AnalyticsHome-uG3xCP_s.js"),__vite__mapDeps([7,8,9,10,1,11,12,3,13,14,15,16,17,2,18,6])).then(e=>({default:e.AnalyticsHome}))),ZC=p.lazy(()=>_e(()=>import("./GlobalAiRail-ovtL7nQu.js"),__vite__mapDeps([19,9,10,1,11,12,3,13,14,15,16,17,2,20,6])).then(e=>({default:e.GlobalAiRail}))),ej=p.lazy(()=>_e(()=>import("./NotebookEditor-CXZaKfYT.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}))),tj=p.lazy(()=>_e(()=>import("./NewNotebookModal-xjG7nZ3O.js"),__vite__mapDeps([30,4,15,6])).then(e=>({default:e.NewNotebookModal}))),nj=p.lazy(()=>_e(()=>import("./NewBlockModal-DAgJZbws.js"),__vite__mapDeps([31,6])).then(e=>({default:e.NewBlockModal}))),rj=p.lazy(()=>_e(()=>import("./SetupOnboarding-vKFtKtjh.js"),__vite__mapDeps([32,33,2,6])).then(e=>({default:e.SetupOnboarding}))),oj=p.lazy(()=>_e(()=>import("./BlockStudio-90J_wvWL.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}))),sj=p.lazy(()=>_e(()=>import("./BusinessArtifactView-_zSMae5q.js"),__vite__mapDeps([37,25,26,6,27])).then(e=>({default:e.BusinessArtifactView}))),ij=p.lazy(()=>_e(()=>import("./LineageDetailView-CFc8pm91.js"),__vite__mapDeps([38,25,26,6,27,39,33,16])).then(e=>({default:e.LineageDetailView}))),aj=p.lazy(()=>_e(()=>import("./LineageDAG-AaqLEiBN.js"),__vite__mapDeps([39,26,6,27])).then(e=>({default:e.LineageDAG}))),cj=p.lazy(()=>_e(()=>import("./HelpDocsPage-CEGUx28b.js"),__vite__mapDeps([40,6])).then(e=>({default:e.HelpDocsPage}))),lj=p.lazy(()=>_e(()=>Promise.resolve().then(()=>s1),void 0).then(e=>({default:e.ConnectionPanel}))),dj=p.lazy(()=>_e(()=>import("./GitPage-CUfAhS67.js"),__vite__mapDeps([41,42,15,6])).then(e=>({default:e.GitPage}))),uj=p.lazy(()=>_e(()=>import("./ReadinessPage-MuJBFwwg.js"),__vite__mapDeps([43,1,44,45,12,3,2,6])).then(e=>({default:e.ReadinessPage}))),pj=p.lazy(()=>_e(()=>import("./AgentLogPage-DYmHO6_i.js"),__vite__mapDeps([46,33,14,47,6])).then(e=>({default:e.AgentLogPage}))),fj=p.lazy(()=>_e(()=>import("./GovernedContextPage-CaMiKAzA.js"),__vite__mapDeps([48,3,12,9,10,1,11,13,14,15,16,17,2,49,6])).then(e=>({default:e.GovernedContextPage}))),hj=p.lazy(()=>_e(()=>import("./DbtFirstModelingPage-DoXiPssu.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}))),mj=p.lazy(()=>_e(()=>import("./AppsView-DfieNjkh.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}))),gj=p.lazy(()=>_e(()=>import("./LineageDrawer-DOkFjPq-.js"),__vite__mapDeps([54,25,26,6,27,36,15,17,13,53,42])).then(e=>({default:e.LineageDrawer}))),yj=p.lazy(()=>_e(()=>import("./AiBuildDialog-BfhaOd1h.js"),__vite__mapDeps([55,44,11,12,3,13,15,6])).then(e=>({default:e.AiBuildDialog})));function bj(){const e=Ge(Mr(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=Cn(),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=QC(window.location.href),f=`${window.location.pathname}${window.location.search}${window.location.hash}`;d!==f&&window.history.replaceState(window.history.state,"",d)},[e.mainView]),qC(),KC(),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}=L1(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($C,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(Uw,{}),e.appMode==="studio"&&e.sidebarOpen&&!o&&s.jsx(O1,{onOpenFile:u}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:s.jsx(p.Suspense,{fallback:s.jsx(xj,{t:n}),children:e.mainView==="home"?s.jsx(YC,{}):e.mainView==="ask"?s.jsx(XC,{}):e.mainView==="business_artifact"?s.jsx(sj,{}):e.mainView==="lineage"?s.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s.jsx(aj,{})}):e.mainView==="lineage_detail"?s.jsx(ij,{}):e.mainView==="help"?s.jsx(cj,{}):e.mainView==="connection"||e.mainView==="settings"?s.jsx(Sj,{children:s.jsx(lj,{variant:"page"})}):e.mainView==="git"?s.jsx(dj,{}):e.mainView==="readiness"?s.jsx(uj,{}):e.mainView==="skills"?s.jsx(fj,{initialTab:"skills"}):e.mainView==="domains"||e.mainView==="modeling"?s.jsx(hj,{}):e.mainView==="apps"?s.jsx(mj,{}):e.mainView==="agent_log"?s.jsx(wj,{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(pj,{})}):s.jsx(s.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?s.jsx(oj,{},"block-editor"):s.jsxs(s.Fragment,{children:[s.jsx(ej,{onOpenFile:u,registerCellRef:h}),e.appMode==="studio"&&s.jsx(FC,{})]})})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(gj,{})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(_w,{}),e.globalAi.open&&e.mainView==="apps"&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(ZC,{})})]}),e.newNotebookModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(tj,{onFileOpened:u})}),e.newBlockModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(nj,{onFileOpened:u})}),s.jsx(QS,{open:i,onClose:()=>a(!1)}),s.jsx(p.Suspense,{fallback:null,children:s.jsx(yj,{})}),e.setupOpen&&s.jsx(p.Suspense,{fallback:s.jsx(vj,{t:n}),children:s.jsx(rj,{launch:c!=null&&c.shouldOpen?c:void 0,onAcknowledged:()=>l(d=>d&&{...d,shouldOpen:!1,reason:null})})})]})}function xj({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 vj({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 Sj({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 wj({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 kj(){const e=Cn(),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,wp("/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 Cj=new rh({defaultOptions:{queries:{staleTime:15e3,gcTime:5*6e4,retry:1,refetchOnWindowFocus:!1}}});function jj(){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
+ * { margin: 0; padding: 0; box-sizing: border-box; }
612
+ body {
613
+ font-family: var(--font-ui, ${n.font});
614
+ overflow: hidden;
615
+ background: var(--color-bg-primary);
616
+ color: var(--color-text-primary);
617
+ }
618
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
619
+ ::-webkit-scrollbar-track { background: transparent; }
620
+ ::-webkit-scrollbar-thumb {
621
+ background: var(--color-border-secondary);
622
+ border-radius: 3px;
623
+ }
624
+ ::-webkit-scrollbar-thumb:hover {
625
+ background: var(--color-text-tertiary);
626
+ }
627
+ ::selection {
628
+ background: color-mix(in srgb, var(--color-accent-blue) 25%, transparent);
629
+ color: var(--color-text-primary);
630
+ }
631
+ .dql-meta-pill:hover {
632
+ background: var(--dql-pill-hover-bg) !important;
633
+ border-color: var(--dql-pill-hover-border) !important;
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]),kj(),s.jsx(bh,{theme:e,applyGlobal:!0,children:s.jsx(Rg,{delayDuration:200,skipDelayDuration:400,children:s.jsx(bj,{})})})}function Ej(){return s.jsx(oh,{client:Cj,children:s.jsx(Kx,{children:s.jsx(kC,{children:s.jsx(jj,{})})})})}_f.createRoot(document.getElementById("root")).render(s.jsx(Ej,{}));export{yp as $,Jp as A,Oa as B,jv as C,Eo as D,z1 as E,Pa as F,Lr as G,Zj as H,Xj as I,Pn as J,af as K,qn as L,bt as M,hS as N,uE as O,ES as P,bk as Q,qe as R,xp as S,vp as T,To as U,Qn as V,Bw as W,Bj as X,Fj as Y,Vj as Z,zj as _,B as a,L1 as a$,ps as a0,qk as a1,Kp as a2,ti as a3,Fi as a4,Hj as a5,CC as a6,Ri as a7,pE as a8,rE as a9,Nj as aA,Rw as aB,Ow as aC,$j as aD,Zc as aE,dS as aF,ev as aG,ov as aH,nS as aI,Yv as aJ,Tv as aK,wv as aL,vE as aM,pf as aN,xE as aO,fE as aP,SE as aQ,mE as aR,gE as aS,hE as aT,bE as aU,Mp as aV,HC as aW,Iv as aX,mp as aY,yE as aZ,wE as a_,sk as aa,aE as ab,cE as ac,G1 as ad,Q1 as ae,oE as af,Yj as ag,Yp as ah,Jj as ai,sE as aj,Y1 as ak,J1 as al,nE as am,Il as an,iE as ao,ys as ap,$0 as aq,xt as ar,Hc as as,Wj as at,Kj as au,Uj as av,qj as aw,Cp as ax,Mj as ay,Lj as az,Re as b,aS as b0,pS as b1,OS as b2,Zv as b3,_e as b4,Yi as b5,Gj as b6,$v as b7,up as b8,DS as b9,Bv as ba,zi as bb,tE as bc,Zi as bd,ne as c,_a as d,Is as e,hp as f,hv as g,Ge as h,Mr as i,s as j,Cn as k,MS as l,Ra as m,V1 as n,Qj as o,Ew as p,Tw as q,p as r,lE as s,Qe as t,et as u,dE as v,Xp as w,Zp as x,eE as y,W1 as z};